• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2008, 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 // Google C++ Testing and Mocking Framework (Google Test)
32 //
33 // Sometimes it's desirable to build Google Test by compiling a single file.
34 // This file serves this purpose.
35 
36 // This line ensures that gtest.h can be compiled on its own, even
37 // when it's fused.
38 #include "gtest/gtest.h"
39 
40 // The following lines pull in the real gtest *.cc files.
41 // Copyright 2005, Google Inc.
42 // All rights reserved.
43 //
44 // Redistribution and use in source and binary forms, with or without
45 // modification, are permitted provided that the following conditions are
46 // met:
47 //
48 //     * Redistributions of source code must retain the above copyright
49 // notice, this list of conditions and the following disclaimer.
50 //     * Redistributions in binary form must reproduce the above
51 // copyright notice, this list of conditions and the following disclaimer
52 // in the documentation and/or other materials provided with the
53 // distribution.
54 //     * Neither the name of Google Inc. nor the names of its
55 // contributors may be used to endorse or promote products derived from
56 // this software without specific prior written permission.
57 //
58 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
59 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
60 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
61 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
62 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
63 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
64 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
65 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
66 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
67 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
68 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
69 
70 //
71 // The Google C++ Testing and Mocking Framework (Google Test)
72 
73 // Copyright 2007, Google Inc.
74 // All rights reserved.
75 //
76 // Redistribution and use in source and binary forms, with or without
77 // modification, are permitted provided that the following conditions are
78 // met:
79 //
80 //     * Redistributions of source code must retain the above copyright
81 // notice, this list of conditions and the following disclaimer.
82 //     * Redistributions in binary form must reproduce the above
83 // copyright notice, this list of conditions and the following disclaimer
84 // in the documentation and/or other materials provided with the
85 // distribution.
86 //     * Neither the name of Google Inc. nor the names of its
87 // contributors may be used to endorse or promote products derived from
88 // this software without specific prior written permission.
89 //
90 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
91 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
92 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
93 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
94 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
95 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
96 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
97 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
98 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
99 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
100 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
101 
102 //
103 // Utilities for testing Google Test itself and code that uses Google Test
104 // (e.g. frameworks built on top of Google Test).
105 
106 // GOOGLETEST_CM0004 DO NOT DELETE
107 
108 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
109 #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
110 
111 
112 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
113 /* class A needs to have dll-interface to be used by clients of class B */)
114 
115 namespace testing {
116 
117 // This helper class can be used to mock out Google Test failure reporting
118 // so that we can test Google Test or code that builds on Google Test.
119 //
120 // An object of this class appends a TestPartResult object to the
121 // TestPartResultArray object given in the constructor whenever a Google Test
122 // failure is reported. It can either intercept only failures that are
123 // generated in the same thread that created this object or it can intercept
124 // all generated failures. The scope of this mock object can be controlled with
125 // the second argument to the two arguments constructor.
126 class GTEST_API_ ScopedFakeTestPartResultReporter
127     : public TestPartResultReporterInterface {
128  public:
129   // The two possible mocking modes of this object.
130   enum InterceptMode {
131     INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
132     INTERCEPT_ALL_THREADS           // Intercepts all failures.
133   };
134 
135   // The c'tor sets this object as the test part result reporter used
136   // by Google Test.  The 'result' parameter specifies where to report the
137   // results. This reporter will only catch failures generated in the current
138   // thread. DEPRECATED
139   explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
140 
141   // Same as above, but you can choose the interception scope of this object.
142   ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
143                                    TestPartResultArray* result);
144 
145   // The d'tor restores the previous test part result reporter.
146   ~ScopedFakeTestPartResultReporter() override;
147 
148   // Appends the TestPartResult object to the TestPartResultArray
149   // received in the constructor.
150   //
151   // This method is from the TestPartResultReporterInterface
152   // interface.
153   void ReportTestPartResult(const TestPartResult& result) override;
154 
155  private:
156   void Init();
157 
158   const InterceptMode intercept_mode_;
159   TestPartResultReporterInterface* old_reporter_;
160   TestPartResultArray* const result_;
161 
162   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
163 };
164 
165 namespace internal {
166 
167 // A helper class for implementing EXPECT_FATAL_FAILURE() and
168 // EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
169 // TestPartResultArray contains exactly one failure that has the given
170 // type and contains the given substring.  If that's not the case, a
171 // non-fatal failure will be generated.
172 class GTEST_API_ SingleFailureChecker {
173  public:
174   // The constructor remembers the arguments.
175   SingleFailureChecker(const TestPartResultArray* results,
176                        TestPartResult::Type type, const std::string& substr);
177   ~SingleFailureChecker();
178  private:
179   const TestPartResultArray* const results_;
180   const TestPartResult::Type type_;
181   const std::string substr_;
182 
183   GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
184 };
185 
186 }  // namespace internal
187 
188 }  // namespace testing
189 
190 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
191 
192 // A set of macros for testing Google Test assertions or code that's expected
193 // to generate Google Test fatal failures.  It verifies that the given
194 // statement will cause exactly one fatal Google Test failure with 'substr'
195 // being part of the failure message.
196 //
197 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
198 // affects and considers failures generated in the current thread and
199 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
200 //
201 // The verification of the assertion is done correctly even when the statement
202 // throws an exception or aborts the current function.
203 //
204 // Known restrictions:
205 //   - 'statement' cannot reference local non-static variables or
206 //     non-static members of the current object.
207 //   - 'statement' cannot return a value.
208 //   - You cannot stream a failure message to this macro.
209 //
210 // Note that even though the implementations of the following two
211 // macros are much alike, we cannot refactor them to use a common
212 // helper macro, due to some peculiarity in how the preprocessor
213 // works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
214 // gtest_unittest.cc will fail to compile if we do that.
215 #define EXPECT_FATAL_FAILURE(statement, substr) \
216   do { \
217     class GTestExpectFatalFailureHelper {\
218      public:\
219       static void Execute() { statement; }\
220     };\
221     ::testing::TestPartResultArray gtest_failures;\
222     ::testing::internal::SingleFailureChecker gtest_checker(\
223         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
224     {\
225       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
226           ::testing::ScopedFakeTestPartResultReporter:: \
227           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
228       GTestExpectFatalFailureHelper::Execute();\
229     }\
230   } while (::testing::internal::AlwaysFalse())
231 
232 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
233   do { \
234     class GTestExpectFatalFailureHelper {\
235      public:\
236       static void Execute() { statement; }\
237     };\
238     ::testing::TestPartResultArray gtest_failures;\
239     ::testing::internal::SingleFailureChecker gtest_checker(\
240         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
241     {\
242       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
243           ::testing::ScopedFakeTestPartResultReporter:: \
244           INTERCEPT_ALL_THREADS, &gtest_failures);\
245       GTestExpectFatalFailureHelper::Execute();\
246     }\
247   } while (::testing::internal::AlwaysFalse())
248 
249 // A macro for testing Google Test assertions or code that's expected to
250 // generate Google Test non-fatal failures.  It asserts that the given
251 // statement will cause exactly one non-fatal Google Test failure with 'substr'
252 // being part of the failure message.
253 //
254 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
255 // affects and considers failures generated in the current thread and
256 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
257 //
258 // 'statement' is allowed to reference local variables and members of
259 // the current object.
260 //
261 // The verification of the assertion is done correctly even when the statement
262 // throws an exception or aborts the current function.
263 //
264 // Known restrictions:
265 //   - You cannot stream a failure message to this macro.
266 //
267 // Note that even though the implementations of the following two
268 // macros are much alike, we cannot refactor them to use a common
269 // helper macro, due to some peculiarity in how the preprocessor
270 // works.  If we do that, the code won't compile when the user gives
271 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
272 // expands to code containing an unprotected comma.  The
273 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
274 // catches that.
275 //
276 // For the same reason, we have to write
277 //   if (::testing::internal::AlwaysTrue()) { statement; }
278 // instead of
279 //   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
280 // to avoid an MSVC warning on unreachable code.
281 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
282   do {\
283     ::testing::TestPartResultArray gtest_failures;\
284     ::testing::internal::SingleFailureChecker gtest_checker(\
285         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
286         (substr));\
287     {\
288       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
289           ::testing::ScopedFakeTestPartResultReporter:: \
290           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
291       if (::testing::internal::AlwaysTrue()) { statement; }\
292     }\
293   } while (::testing::internal::AlwaysFalse())
294 
295 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
296   do {\
297     ::testing::TestPartResultArray gtest_failures;\
298     ::testing::internal::SingleFailureChecker gtest_checker(\
299         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
300         (substr));\
301     {\
302       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
303           ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
304           &gtest_failures);\
305       if (::testing::internal::AlwaysTrue()) { statement; }\
306     }\
307   } while (::testing::internal::AlwaysFalse())
308 
309 #endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
310 
311 #include <ctype.h>
312 #include <stdarg.h>
313 #include <stdio.h>
314 #include <stdlib.h>
315 #include <time.h>
316 #include <wchar.h>
317 #include <wctype.h>
318 
319 #include <algorithm>
320 #include <chrono>  // NOLINT
321 #include <cmath>
322 #include <cstdint>
323 #include <iomanip>
324 #include <limits>
325 #include <list>
326 #include <map>
327 #include <ostream>  // NOLINT
328 #include <sstream>
329 #include <vector>
330 
331 #if GTEST_OS_LINUX
332 
333 # include <fcntl.h>  // NOLINT
334 # include <limits.h>  // NOLINT
335 # include <sched.h>  // NOLINT
336 // Declares vsnprintf().  This header is not available on Windows.
337 # include <strings.h>  // NOLINT
338 # include <sys/mman.h>  // NOLINT
339 # include <sys/time.h>  // NOLINT
340 # include <unistd.h>  // NOLINT
341 # include <string>
342 
343 #elif GTEST_OS_ZOS
344 # include <sys/time.h>  // NOLINT
345 
346 // On z/OS we additionally need strings.h for strcasecmp.
347 # include <strings.h>  // NOLINT
348 
349 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
350 
351 # include <windows.h>  // NOLINT
352 # undef min
353 
354 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
355 
356 # include <windows.h>  // NOLINT
357 # undef min
358 
359 #ifdef _MSC_VER
360 # include <crtdbg.h>  // NOLINT
361 #endif
362 
363 # include <io.h>  // NOLINT
364 # include <sys/timeb.h>  // NOLINT
365 # include <sys/types.h>  // NOLINT
366 # include <sys/stat.h>  // NOLINT
367 
368 # if GTEST_OS_WINDOWS_MINGW
369 #  include <sys/time.h>  // NOLINT
370 # endif  // GTEST_OS_WINDOWS_MINGW
371 
372 #else
373 
374 // cpplint thinks that the header is already included, so we want to
375 // silence it.
376 # include <sys/time.h>  // NOLINT
377 # include <unistd.h>  // NOLINT
378 
379 #endif  // GTEST_OS_LINUX
380 
381 #if GTEST_HAS_EXCEPTIONS
382 # include <stdexcept>
383 #endif
384 
385 #if GTEST_CAN_STREAM_RESULTS_
386 # include <arpa/inet.h>  // NOLINT
387 # include <netdb.h>  // NOLINT
388 # include <sys/socket.h>  // NOLINT
389 # include <sys/types.h>  // NOLINT
390 #endif
391 
392 // Copyright 2005, Google Inc.
393 // All rights reserved.
394 //
395 // Redistribution and use in source and binary forms, with or without
396 // modification, are permitted provided that the following conditions are
397 // met:
398 //
399 //     * Redistributions of source code must retain the above copyright
400 // notice, this list of conditions and the following disclaimer.
401 //     * Redistributions in binary form must reproduce the above
402 // copyright notice, this list of conditions and the following disclaimer
403 // in the documentation and/or other materials provided with the
404 // distribution.
405 //     * Neither the name of Google Inc. nor the names of its
406 // contributors may be used to endorse or promote products derived from
407 // this software without specific prior written permission.
408 //
409 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
410 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
411 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
412 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
413 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
414 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
415 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
416 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
417 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
418 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
419 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
420 
421 // Utility functions and classes used by the Google C++ testing framework.//
422 // This file contains purely Google Test's internal implementation.  Please
423 // DO NOT #INCLUDE IT IN A USER PROGRAM.
424 
425 #ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
426 #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
427 
428 #ifndef _WIN32_WCE
429 # include <errno.h>
430 #endif  // !_WIN32_WCE
431 #include <stddef.h>
432 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
433 #include <string.h>  // For memmove.
434 
435 #include <algorithm>
436 #include <cstdint>
437 #include <memory>
438 #include <string>
439 #include <vector>
440 
441 
442 #if GTEST_CAN_STREAM_RESULTS_
443 # include <arpa/inet.h>  // NOLINT
444 # include <netdb.h>  // NOLINT
445 #endif
446 
447 #if GTEST_OS_WINDOWS
448 # include <windows.h>  // NOLINT
449 #endif  // GTEST_OS_WINDOWS
450 
451 
452 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
453 /* class A needs to have dll-interface to be used by clients of class B */)
454 
455 namespace testing {
456 
457 // Declares the flags.
458 //
459 // We don't want the users to modify this flag in the code, but want
460 // Google Test's own unit tests to be able to access it. Therefore we
461 // declare it here as opposed to in gtest.h.
462 GTEST_DECLARE_bool_(death_test_use_fork);
463 
464 namespace internal {
465 
466 // The value of GetTestTypeId() as seen from within the Google Test
467 // library.  This is solely for testing GetTestTypeId().
468 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
469 
470 // Names of the flags (needed for parsing Google Test flags).
471 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
472 const char kBreakOnFailureFlag[] = "break_on_failure";
473 const char kCatchExceptionsFlag[] = "catch_exceptions";
474 const char kColorFlag[] = "color";
475 const char kFailFast[] = "fail_fast";
476 const char kFilterFlag[] = "filter";
477 const char kListTestsFlag[] = "list_tests";
478 const char kOutputFlag[] = "output";
479 const char kBriefFlag[] = "brief";
480 const char kPrintTimeFlag[] = "print_time";
481 const char kPrintUTF8Flag[] = "print_utf8";
482 const char kRandomSeedFlag[] = "random_seed";
483 const char kRepeatFlag[] = "repeat";
484 const char kShuffleFlag[] = "shuffle";
485 const char kStackTraceDepthFlag[] = "stack_trace_depth";
486 const char kStreamResultToFlag[] = "stream_result_to";
487 const char kThrowOnFailureFlag[] = "throw_on_failure";
488 const char kFlagfileFlag[] = "flagfile";
489 
490 // A valid random seed must be in [1, kMaxRandomSeed].
491 const int kMaxRandomSeed = 99999;
492 
493 // g_help_flag is true if and only if the --help flag or an equivalent form
494 // is specified on the command line.
495 GTEST_API_ extern bool g_help_flag;
496 
497 // Returns the current time in milliseconds.
498 GTEST_API_ TimeInMillis GetTimeInMillis();
499 
500 // Returns true if and only if Google Test should use colors in the output.
501 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
502 
503 // Formats the given time in milliseconds as seconds.
504 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
505 
506 // Converts the given time in milliseconds to a date string in the ISO 8601
507 // format, without the timezone information.  N.B.: due to the use the
508 // non-reentrant localtime() function, this function is not thread safe.  Do
509 // not use it in any code that can be called from multiple threads.
510 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
511 
512 // Parses a string for an Int32 flag, in the form of "--flag=value".
513 //
514 // On success, stores the value of the flag in *value, and returns
515 // true.  On failure, returns false without changing *value.
516 GTEST_API_ bool ParseInt32Flag(
517     const char* str, const char* flag, int32_t* value);
518 
519 // Returns a random seed in range [1, kMaxRandomSeed] based on the
520 // given --gtest_random_seed flag value.
GetRandomSeedFromFlag(int32_t random_seed_flag)521 inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
522   const unsigned int raw_seed = (random_seed_flag == 0) ?
523       static_cast<unsigned int>(GetTimeInMillis()) :
524       static_cast<unsigned int>(random_seed_flag);
525 
526   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
527   // it's easy to type.
528   const int normalized_seed =
529       static_cast<int>((raw_seed - 1U) %
530                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
531   return normalized_seed;
532 }
533 
534 // Returns the first valid random seed after 'seed'.  The behavior is
535 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
536 // considered to be 1.
GetNextRandomSeed(int seed)537 inline int GetNextRandomSeed(int seed) {
538   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
539       << "Invalid random seed " << seed << " - must be in [1, "
540       << kMaxRandomSeed << "].";
541   const int next_seed = seed + 1;
542   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
543 }
544 
545 // This class saves the values of all Google Test flags in its c'tor, and
546 // restores them in its d'tor.
547 class GTestFlagSaver {
548  public:
549   // The c'tor.
GTestFlagSaver()550   GTestFlagSaver() {
551     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
552     break_on_failure_ = GTEST_FLAG(break_on_failure);
553     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
554     color_ = GTEST_FLAG(color);
555     death_test_style_ = GTEST_FLAG(death_test_style);
556     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
557     fail_fast_ = GTEST_FLAG(fail_fast);
558     filter_ = GTEST_FLAG(filter);
559     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
560     list_tests_ = GTEST_FLAG(list_tests);
561     output_ = GTEST_FLAG(output);
562     brief_ = GTEST_FLAG(brief);
563     print_time_ = GTEST_FLAG(print_time);
564     print_utf8_ = GTEST_FLAG(print_utf8);
565     random_seed_ = GTEST_FLAG(random_seed);
566     repeat_ = GTEST_FLAG(repeat);
567     shuffle_ = GTEST_FLAG(shuffle);
568     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
569     stream_result_to_ = GTEST_FLAG(stream_result_to);
570     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
571   }
572 
573   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver()574   ~GTestFlagSaver() {
575     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
576     GTEST_FLAG(break_on_failure) = break_on_failure_;
577     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
578     GTEST_FLAG(color) = color_;
579     GTEST_FLAG(death_test_style) = death_test_style_;
580     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
581     GTEST_FLAG(filter) = filter_;
582     GTEST_FLAG(fail_fast) = fail_fast_;
583     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
584     GTEST_FLAG(list_tests) = list_tests_;
585     GTEST_FLAG(output) = output_;
586     GTEST_FLAG(brief) = brief_;
587     GTEST_FLAG(print_time) = print_time_;
588     GTEST_FLAG(print_utf8) = print_utf8_;
589     GTEST_FLAG(random_seed) = random_seed_;
590     GTEST_FLAG(repeat) = repeat_;
591     GTEST_FLAG(shuffle) = shuffle_;
592     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
593     GTEST_FLAG(stream_result_to) = stream_result_to_;
594     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
595   }
596 
597  private:
598   // Fields for saving the original values of flags.
599   bool also_run_disabled_tests_;
600   bool break_on_failure_;
601   bool catch_exceptions_;
602   std::string color_;
603   std::string death_test_style_;
604   bool death_test_use_fork_;
605   bool fail_fast_;
606   std::string filter_;
607   std::string internal_run_death_test_;
608   bool list_tests_;
609   std::string output_;
610   bool brief_;
611   bool print_time_;
612   bool print_utf8_;
613   int32_t random_seed_;
614   int32_t repeat_;
615   bool shuffle_;
616   int32_t stack_trace_depth_;
617   std::string stream_result_to_;
618   bool throw_on_failure_;
619 } GTEST_ATTRIBUTE_UNUSED_;
620 
621 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
622 // code_point parameter is of type UInt32 because wchar_t may not be
623 // wide enough to contain a code point.
624 // If the code_point is not a valid Unicode code point
625 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
626 // to "(Invalid Unicode 0xXXXXXXXX)".
627 GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
628 
629 // Converts a wide string to a narrow string in UTF-8 encoding.
630 // The wide string is assumed to have the following encoding:
631 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
632 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
633 // Parameter str points to a null-terminated wide string.
634 // Parameter num_chars may additionally limit the number
635 // of wchar_t characters processed. -1 is used when the entire string
636 // should be processed.
637 // If the string contains code points that are not valid Unicode code points
638 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
639 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
640 // and contains invalid UTF-16 surrogate pairs, values in those pairs
641 // will be encoded as individual Unicode characters from Basic Normal Plane.
642 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
643 
644 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
645 // if the variable is present. If a file already exists at this location, this
646 // function will write over it. If the variable is present, but the file cannot
647 // be created, prints an error and exits.
648 void WriteToShardStatusFileIfNeeded();
649 
650 // Checks whether sharding is enabled by examining the relevant
651 // environment variable values. If the variables are present,
652 // but inconsistent (e.g., shard_index >= total_shards), prints
653 // an error and exits. If in_subprocess_for_death_test, sharding is
654 // disabled because it must only be applied to the original test
655 // process. Otherwise, we could filter out death tests we intended to execute.
656 GTEST_API_ bool ShouldShard(const char* total_shards_str,
657                             const char* shard_index_str,
658                             bool in_subprocess_for_death_test);
659 
660 // Parses the environment variable var as a 32-bit integer. If it is unset,
661 // returns default_val. If it is not a 32-bit integer, prints an error and
662 // and aborts.
663 GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
664 
665 // Given the total number of shards, the shard index, and the test id,
666 // returns true if and only if the test should be run on this shard. The test id
667 // is some arbitrary but unique non-negative integer assigned to each test
668 // method. Assumes that 0 <= shard_index < total_shards.
669 GTEST_API_ bool ShouldRunTestOnShard(
670     int total_shards, int shard_index, int test_id);
671 
672 // STL container utilities.
673 
674 // Returns the number of elements in the given container that satisfy
675 // the given predicate.
676 template <class Container, typename Predicate>
CountIf(const Container & c,Predicate predicate)677 inline int CountIf(const Container& c, Predicate predicate) {
678   // Implemented as an explicit loop since std::count_if() in libCstd on
679   // Solaris has a non-standard signature.
680   int count = 0;
681   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
682     if (predicate(*it))
683       ++count;
684   }
685   return count;
686 }
687 
688 // Applies a function/functor to each element in the container.
689 template <class Container, typename Functor>
ForEach(const Container & c,Functor functor)690 void ForEach(const Container& c, Functor functor) {
691   std::for_each(c.begin(), c.end(), functor);
692 }
693 
694 // Returns the i-th element of the vector, or default_value if i is not
695 // in range [0, v.size()).
696 template <typename E>
GetElementOr(const std::vector<E> & v,int i,E default_value)697 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
698   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
699                                                     : v[static_cast<size_t>(i)];
700 }
701 
702 // Performs an in-place shuffle of a range of the vector's elements.
703 // 'begin' and 'end' are element indices as an STL-style range;
704 // i.e. [begin, end) are shuffled, where 'end' == size() means to
705 // shuffle to the end of the vector.
706 template <typename E>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)707 void ShuffleRange(internal::Random* random, int begin, int end,
708                   std::vector<E>* v) {
709   const int size = static_cast<int>(v->size());
710   GTEST_CHECK_(0 <= begin && begin <= size)
711       << "Invalid shuffle range start " << begin << ": must be in range [0, "
712       << size << "].";
713   GTEST_CHECK_(begin <= end && end <= size)
714       << "Invalid shuffle range finish " << end << ": must be in range ["
715       << begin << ", " << size << "].";
716 
717   // Fisher-Yates shuffle, from
718   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
719   for (int range_width = end - begin; range_width >= 2; range_width--) {
720     const int last_in_range = begin + range_width - 1;
721     const int selected =
722         begin +
723         static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
724     std::swap((*v)[static_cast<size_t>(selected)],
725               (*v)[static_cast<size_t>(last_in_range)]);
726   }
727 }
728 
729 // Performs an in-place shuffle of the vector's elements.
730 template <typename E>
Shuffle(internal::Random * random,std::vector<E> * v)731 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
732   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
733 }
734 
735 // A function for deleting an object.  Handy for being used as a
736 // functor.
737 template <typename T>
Delete(T * x)738 static void Delete(T* x) {
739   delete x;
740 }
741 
742 // A predicate that checks the key of a TestProperty against a known key.
743 //
744 // TestPropertyKeyIs is copyable.
745 class TestPropertyKeyIs {
746  public:
747   // Constructor.
748   //
749   // TestPropertyKeyIs has NO default constructor.
TestPropertyKeyIs(const std::string & key)750   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
751 
752   // Returns true if and only if the test name of test property matches on key_.
operator ()(const TestProperty & test_property) const753   bool operator()(const TestProperty& test_property) const {
754     return test_property.key() == key_;
755   }
756 
757  private:
758   std::string key_;
759 };
760 
761 // Class UnitTestOptions.
762 //
763 // This class contains functions for processing options the user
764 // specifies when running the tests.  It has only static members.
765 //
766 // In most cases, the user can specify an option using either an
767 // environment variable or a command line flag.  E.g. you can set the
768 // test filter using either GTEST_FILTER or --gtest_filter.  If both
769 // the variable and the flag are present, the latter overrides the
770 // former.
771 class GTEST_API_ UnitTestOptions {
772  public:
773   // Functions for processing the gtest_output flag.
774 
775   // Returns the output format, or "" for normal printed output.
776   static std::string GetOutputFormat();
777 
778   // Returns the absolute path of the requested output file, or the
779   // default (test_detail.xml in the original working directory) if
780   // none was explicitly specified.
781   static std::string GetAbsolutePathToOutputFile();
782 
783   // Functions for processing the gtest_filter flag.
784 
785   // Returns true if and only if the user-specified filter matches the test
786   // suite name and the test name.
787   static bool FilterMatchesTest(const std::string& test_suite_name,
788                                 const std::string& test_name);
789 
790 #if GTEST_OS_WINDOWS
791   // Function for supporting the gtest_catch_exception flag.
792 
793   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
794   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
795   // This function is useful as an __except condition.
796   static int GTestShouldProcessSEH(DWORD exception_code);
797 #endif  // GTEST_OS_WINDOWS
798 
799   // Returns true if "name" matches the ':' separated list of glob-style
800   // filters in "filter".
801   static bool MatchesFilter(const std::string& name, const char* filter);
802 };
803 
804 // Returns the current application's name, removing directory path if that
805 // is present.  Used by UnitTestOptions::GetOutputFile.
806 GTEST_API_ FilePath GetCurrentExecutableName();
807 
808 // The role interface for getting the OS stack trace as a string.
809 class OsStackTraceGetterInterface {
810  public:
OsStackTraceGetterInterface()811   OsStackTraceGetterInterface() {}
~OsStackTraceGetterInterface()812   virtual ~OsStackTraceGetterInterface() {}
813 
814   // Returns the current OS stack trace as an std::string.  Parameters:
815   //
816   //   max_depth  - the maximum number of stack frames to be included
817   //                in the trace.
818   //   skip_count - the number of top frames to be skipped; doesn't count
819   //                against max_depth.
820   virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
821 
822   // UponLeavingGTest() should be called immediately before Google Test calls
823   // user code. It saves some information about the current stack that
824   // CurrentStackTrace() will use to find and hide Google Test stack frames.
825   virtual void UponLeavingGTest() = 0;
826 
827   // This string is inserted in place of stack frames that are part of
828   // Google Test's implementation.
829   static const char* const kElidedFramesMarker;
830 
831  private:
832   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
833 };
834 
835 // A working implementation of the OsStackTraceGetterInterface interface.
836 class OsStackTraceGetter : public OsStackTraceGetterInterface {
837  public:
OsStackTraceGetter()838   OsStackTraceGetter() {}
839 
840   std::string CurrentStackTrace(int max_depth, int skip_count) override;
841   void UponLeavingGTest() override;
842 
843  private:
844 #if GTEST_HAS_ABSL
845   Mutex mutex_;  // Protects all internal state.
846 
847   // We save the stack frame below the frame that calls user code.
848   // We do this because the address of the frame immediately below
849   // the user code changes between the call to UponLeavingGTest()
850   // and any calls to the stack trace code from within the user code.
851   void* caller_frame_ = nullptr;
852 #endif  // GTEST_HAS_ABSL
853 
854   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
855 };
856 
857 // Information about a Google Test trace point.
858 struct TraceInfo {
859   const char* file;
860   int line;
861   std::string message;
862 };
863 
864 // This is the default global test part result reporter used in UnitTestImpl.
865 // This class should only be used by UnitTestImpl.
866 class DefaultGlobalTestPartResultReporter
867   : public TestPartResultReporterInterface {
868  public:
869   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
870   // Implements the TestPartResultReporterInterface. Reports the test part
871   // result in the current test.
872   void ReportTestPartResult(const TestPartResult& result) override;
873 
874  private:
875   UnitTestImpl* const unit_test_;
876 
877   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
878 };
879 
880 // This is the default per thread test part result reporter used in
881 // UnitTestImpl. This class should only be used by UnitTestImpl.
882 class DefaultPerThreadTestPartResultReporter
883     : public TestPartResultReporterInterface {
884  public:
885   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
886   // Implements the TestPartResultReporterInterface. The implementation just
887   // delegates to the current global test part result reporter of *unit_test_.
888   void ReportTestPartResult(const TestPartResult& result) override;
889 
890  private:
891   UnitTestImpl* const unit_test_;
892 
893   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
894 };
895 
896 // The private implementation of the UnitTest class.  We don't protect
897 // the methods under a mutex, as this class is not accessible by a
898 // user and the UnitTest class that delegates work to this class does
899 // proper locking.
900 class GTEST_API_ UnitTestImpl {
901  public:
902   explicit UnitTestImpl(UnitTest* parent);
903   virtual ~UnitTestImpl();
904 
905   // There are two different ways to register your own TestPartResultReporter.
906   // You can register your own repoter to listen either only for test results
907   // from the current thread or for results from all threads.
908   // By default, each per-thread test result repoter just passes a new
909   // TestPartResult to the global test result reporter, which registers the
910   // test part result for the currently running test.
911 
912   // Returns the global test part result reporter.
913   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
914 
915   // Sets the global test part result reporter.
916   void SetGlobalTestPartResultReporter(
917       TestPartResultReporterInterface* reporter);
918 
919   // Returns the test part result reporter for the current thread.
920   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
921 
922   // Sets the test part result reporter for the current thread.
923   void SetTestPartResultReporterForCurrentThread(
924       TestPartResultReporterInterface* reporter);
925 
926   // Gets the number of successful test suites.
927   int successful_test_suite_count() const;
928 
929   // Gets the number of failed test suites.
930   int failed_test_suite_count() const;
931 
932   // Gets the number of all test suites.
933   int total_test_suite_count() const;
934 
935   // Gets the number of all test suites that contain at least one test
936   // that should run.
937   int test_suite_to_run_count() const;
938 
939   // Gets the number of successful tests.
940   int successful_test_count() const;
941 
942   // Gets the number of skipped tests.
943   int skipped_test_count() const;
944 
945   // Gets the number of failed tests.
946   int failed_test_count() const;
947 
948   // Gets the number of disabled tests that will be reported in the XML report.
949   int reportable_disabled_test_count() const;
950 
951   // Gets the number of disabled tests.
952   int disabled_test_count() const;
953 
954   // Gets the number of tests to be printed in the XML report.
955   int reportable_test_count() const;
956 
957   // Gets the number of all tests.
958   int total_test_count() const;
959 
960   // Gets the number of tests that should run.
961   int test_to_run_count() const;
962 
963   // Gets the time of the test program start, in ms from the start of the
964   // UNIX epoch.
start_timestamp() const965   TimeInMillis start_timestamp() const { return start_timestamp_; }
966 
967   // Gets the elapsed time, in milliseconds.
elapsed_time() const968   TimeInMillis elapsed_time() const { return elapsed_time_; }
969 
970   // Returns true if and only if the unit test passed (i.e. all test suites
971   // passed).
Passed() const972   bool Passed() const { return !Failed(); }
973 
974   // Returns true if and only if the unit test failed (i.e. some test suite
975   // failed or something outside of all tests failed).
Failed() const976   bool Failed() const {
977     return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
978   }
979 
980   // Gets the i-th test suite among all the test suites. i can range from 0 to
981   // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetTestSuite(int i) const982   const TestSuite* GetTestSuite(int i) const {
983     const int index = GetElementOr(test_suite_indices_, i, -1);
984     return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
985   }
986 
987   //  Legacy API is deprecated but still available
988 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(int i) const989   const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
990 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
991 
992   // Gets the i-th test suite among all the test suites. i can range from 0 to
993   // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetMutableSuiteCase(int i)994   TestSuite* GetMutableSuiteCase(int i) {
995     const int index = GetElementOr(test_suite_indices_, i, -1);
996     return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
997   }
998 
999   // Provides access to the event listener list.
listeners()1000   TestEventListeners* listeners() { return &listeners_; }
1001 
1002   // Returns the TestResult for the test that's currently running, or
1003   // the TestResult for the ad hoc test if no test is running.
1004   TestResult* current_test_result();
1005 
1006   // Returns the TestResult for the ad hoc test.
ad_hoc_test_result() const1007   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1008 
1009   // Sets the OS stack trace getter.
1010   //
1011   // Does nothing if the input and the current OS stack trace getter
1012   // are the same; otherwise, deletes the old getter and makes the
1013   // input the current getter.
1014   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1015 
1016   // Returns the current OS stack trace getter if it is not NULL;
1017   // otherwise, creates an OsStackTraceGetter, makes it the current
1018   // getter, and returns it.
1019   OsStackTraceGetterInterface* os_stack_trace_getter();
1020 
1021   // Returns the current OS stack trace as an std::string.
1022   //
1023   // The maximum number of stack frames to be included is specified by
1024   // the gtest_stack_trace_depth flag.  The skip_count parameter
1025   // specifies the number of top frames to be skipped, which doesn't
1026   // count against the number of frames to be included.
1027   //
1028   // For example, if Foo() calls Bar(), which in turn calls
1029   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1030   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1031   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1032 
1033   // Finds and returns a TestSuite with the given name.  If one doesn't
1034   // exist, creates one and returns it.
1035   //
1036   // Arguments:
1037   //
1038   //   test_suite_name: name of the test suite
1039   //   type_param:      the name of the test's type parameter, or NULL if
1040   //                    this is not a typed or a type-parameterized test.
1041   //   set_up_tc:       pointer to the function that sets up the test suite
1042   //   tear_down_tc:    pointer to the function that tears down the test suite
1043   TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
1044                           internal::SetUpTestSuiteFunc set_up_tc,
1045                           internal::TearDownTestSuiteFunc tear_down_tc);
1046 
1047 //  Legacy API is deprecated but still available
1048 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(const char * test_case_name,const char * type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)1049   TestCase* GetTestCase(const char* test_case_name, const char* type_param,
1050                         internal::SetUpTestSuiteFunc set_up_tc,
1051                         internal::TearDownTestSuiteFunc tear_down_tc) {
1052     return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
1053   }
1054 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1055 
1056   // Adds a TestInfo to the unit test.
1057   //
1058   // Arguments:
1059   //
1060   //   set_up_tc:    pointer to the function that sets up the test suite
1061   //   tear_down_tc: pointer to the function that tears down the test suite
1062   //   test_info:    the TestInfo object
AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc,TestInfo * test_info)1063   void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
1064                    internal::TearDownTestSuiteFunc tear_down_tc,
1065                    TestInfo* test_info) {
1066 #if GTEST_HAS_DEATH_TEST
1067     // In order to support thread-safe death tests, we need to
1068     // remember the original working directory when the test program
1069     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
1070     // the user may have changed the current directory before calling
1071     // RUN_ALL_TESTS().  Therefore we capture the current directory in
1072     // AddTestInfo(), which is called to register a TEST or TEST_F
1073     // before main() is reached.
1074     if (original_working_dir_.IsEmpty()) {
1075       original_working_dir_.Set(FilePath::GetCurrentDir());
1076       GTEST_CHECK_(!original_working_dir_.IsEmpty())
1077           << "Failed to get the current working directory.";
1078     }
1079 #endif  // GTEST_HAS_DEATH_TEST
1080 
1081     GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
1082                  set_up_tc, tear_down_tc)
1083         ->AddTestInfo(test_info);
1084   }
1085 
1086   // Returns ParameterizedTestSuiteRegistry object used to keep track of
1087   // value-parameterized tests and instantiate and register them.
parameterized_test_registry()1088   internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
1089     return parameterized_test_registry_;
1090   }
1091 
ignored_parameterized_test_suites()1092   std::set<std::string>* ignored_parameterized_test_suites() {
1093     return &ignored_parameterized_test_suites_;
1094   }
1095 
1096   // Returns TypeParameterizedTestSuiteRegistry object used to keep track of
1097   // type-parameterized tests and instantiations of them.
1098   internal::TypeParameterizedTestSuiteRegistry&
type_parameterized_test_registry()1099   type_parameterized_test_registry() {
1100     return type_parameterized_test_registry_;
1101   }
1102 
1103   // Sets the TestSuite object for the test that's currently running.
set_current_test_suite(TestSuite * a_current_test_suite)1104   void set_current_test_suite(TestSuite* a_current_test_suite) {
1105     current_test_suite_ = a_current_test_suite;
1106   }
1107 
1108   // Sets the TestInfo object for the test that's currently running.  If
1109   // current_test_info is NULL, the assertion results will be stored in
1110   // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)1111   void set_current_test_info(TestInfo* a_current_test_info) {
1112     current_test_info_ = a_current_test_info;
1113   }
1114 
1115   // Registers all parameterized tests defined using TEST_P and
1116   // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
1117   // combination. This method can be called more then once; it has guards
1118   // protecting from registering the tests more then once.  If
1119   // value-parameterized tests are disabled, RegisterParameterizedTests is
1120   // present but does nothing.
1121   void RegisterParameterizedTests();
1122 
1123   // Runs all tests in this UnitTest object, prints the result, and
1124   // returns true if all tests are successful.  If any exception is
1125   // thrown during a test, this test is considered to be failed, but
1126   // the rest of the tests will still be run.
1127   bool RunAllTests();
1128 
1129   // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()1130   void ClearNonAdHocTestResult() {
1131     ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
1132   }
1133 
1134   // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()1135   void ClearAdHocTestResult() {
1136     ad_hoc_test_result_.Clear();
1137   }
1138 
1139   // Adds a TestProperty to the current TestResult object when invoked in a
1140   // context of a test or a test suite, or to the global property set. If the
1141   // result already contains a property with the same key, the value will be
1142   // updated.
1143   void RecordProperty(const TestProperty& test_property);
1144 
1145   enum ReactionToSharding {
1146     HONOR_SHARDING_PROTOCOL,
1147     IGNORE_SHARDING_PROTOCOL
1148   };
1149 
1150   // Matches the full name of each test against the user-specified
1151   // filter to decide whether the test should run, then records the
1152   // result in each TestSuite and TestInfo object.
1153   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1154   // based on sharding variables in the environment.
1155   // Returns the number of tests that should run.
1156   int FilterTests(ReactionToSharding shard_tests);
1157 
1158   // Prints the names of the tests matching the user-specified filter flag.
1159   void ListTestsMatchingFilter();
1160 
current_test_suite() const1161   const TestSuite* current_test_suite() const { return current_test_suite_; }
current_test_info()1162   TestInfo* current_test_info() { return current_test_info_; }
current_test_info() const1163   const TestInfo* current_test_info() const { return current_test_info_; }
1164 
1165   // Returns the vector of environments that need to be set-up/torn-down
1166   // before/after the tests are run.
environments()1167   std::vector<Environment*>& environments() { return environments_; }
1168 
1169   // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()1170   std::vector<TraceInfo>& gtest_trace_stack() {
1171     return *(gtest_trace_stack_.pointer());
1172   }
gtest_trace_stack() const1173   const std::vector<TraceInfo>& gtest_trace_stack() const {
1174     return gtest_trace_stack_.get();
1175   }
1176 
1177 #if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()1178   void InitDeathTestSubprocessControlInfo() {
1179     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1180   }
1181   // Returns a pointer to the parsed --gtest_internal_run_death_test
1182   // flag, or NULL if that flag was not specified.
1183   // This information is useful only in a death test child process.
1184   // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag() const1185   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1186     return internal_run_death_test_flag_.get();
1187   }
1188 
1189   // Returns a pointer to the current death test factory.
death_test_factory()1190   internal::DeathTestFactory* death_test_factory() {
1191     return death_test_factory_.get();
1192   }
1193 
1194   void SuppressTestEventsIfInSubprocess();
1195 
1196   friend class ReplaceDeathTestFactory;
1197 #endif  // GTEST_HAS_DEATH_TEST
1198 
1199   // Initializes the event listener performing XML output as specified by
1200   // UnitTestOptions. Must not be called before InitGoogleTest.
1201   void ConfigureXmlOutput();
1202 
1203 #if GTEST_CAN_STREAM_RESULTS_
1204   // Initializes the event listener for streaming test results to a socket.
1205   // Must not be called before InitGoogleTest.
1206   void ConfigureStreamingOutput();
1207 #endif
1208 
1209   // Performs initialization dependent upon flag values obtained in
1210   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
1211   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
1212   // this function is also called from RunAllTests.  Since this function can be
1213   // called more than once, it has to be idempotent.
1214   void PostFlagParsingInit();
1215 
1216   // Gets the random seed used at the start of the current test iteration.
random_seed() const1217   int random_seed() const { return random_seed_; }
1218 
1219   // Gets the random number generator.
random()1220   internal::Random* random() { return &random_; }
1221 
1222   // Shuffles all test suites, and the tests within each test suite,
1223   // making sure that death tests are still run first.
1224   void ShuffleTests();
1225 
1226   // Restores the test suites and tests to their order before the first shuffle.
1227   void UnshuffleTests();
1228 
1229   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1230   // UnitTest::Run() starts.
catch_exceptions() const1231   bool catch_exceptions() const { return catch_exceptions_; }
1232 
1233  private:
1234   friend class ::testing::UnitTest;
1235 
1236   // Used by UnitTest::Run() to capture the state of
1237   // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)1238   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1239 
1240   // The UnitTest object that owns this implementation object.
1241   UnitTest* const parent_;
1242 
1243   // The working directory when the first TEST() or TEST_F() was
1244   // executed.
1245   internal::FilePath original_working_dir_;
1246 
1247   // The default test part result reporters.
1248   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1249   DefaultPerThreadTestPartResultReporter
1250       default_per_thread_test_part_result_reporter_;
1251 
1252   // Points to (but doesn't own) the global test part result reporter.
1253   TestPartResultReporterInterface* global_test_part_result_repoter_;
1254 
1255   // Protects read and write access to global_test_part_result_reporter_.
1256   internal::Mutex global_test_part_result_reporter_mutex_;
1257 
1258   // Points to (but doesn't own) the per-thread test part result reporter.
1259   internal::ThreadLocal<TestPartResultReporterInterface*>
1260       per_thread_test_part_result_reporter_;
1261 
1262   // The vector of environments that need to be set-up/torn-down
1263   // before/after the tests are run.
1264   std::vector<Environment*> environments_;
1265 
1266   // The vector of TestSuites in their original order.  It owns the
1267   // elements in the vector.
1268   std::vector<TestSuite*> test_suites_;
1269 
1270   // Provides a level of indirection for the test suite list to allow
1271   // easy shuffling and restoring the test suite order.  The i-th
1272   // element of this vector is the index of the i-th test suite in the
1273   // shuffled order.
1274   std::vector<int> test_suite_indices_;
1275 
1276   // ParameterizedTestRegistry object used to register value-parameterized
1277   // tests.
1278   internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
1279   internal::TypeParameterizedTestSuiteRegistry
1280       type_parameterized_test_registry_;
1281 
1282   // The set holding the name of parameterized
1283   // test suites that may go uninstantiated.
1284   std::set<std::string> ignored_parameterized_test_suites_;
1285 
1286   // Indicates whether RegisterParameterizedTests() has been called already.
1287   bool parameterized_tests_registered_;
1288 
1289   // Index of the last death test suite registered.  Initially -1.
1290   int last_death_test_suite_;
1291 
1292   // This points to the TestSuite for the currently running test.  It
1293   // changes as Google Test goes through one test suite after another.
1294   // When no test is running, this is set to NULL and Google Test
1295   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
1296   TestSuite* current_test_suite_;
1297 
1298   // This points to the TestInfo for the currently running test.  It
1299   // changes as Google Test goes through one test after another.  When
1300   // no test is running, this is set to NULL and Google Test stores
1301   // assertion results in ad_hoc_test_result_.  Initially NULL.
1302   TestInfo* current_test_info_;
1303 
1304   // Normally, a user only writes assertions inside a TEST or TEST_F,
1305   // or inside a function called by a TEST or TEST_F.  Since Google
1306   // Test keeps track of which test is current running, it can
1307   // associate such an assertion with the test it belongs to.
1308   //
1309   // If an assertion is encountered when no TEST or TEST_F is running,
1310   // Google Test attributes the assertion result to an imaginary "ad hoc"
1311   // test, and records the result in ad_hoc_test_result_.
1312   TestResult ad_hoc_test_result_;
1313 
1314   // The list of event listeners that can be used to track events inside
1315   // Google Test.
1316   TestEventListeners listeners_;
1317 
1318   // The OS stack trace getter.  Will be deleted when the UnitTest
1319   // object is destructed.  By default, an OsStackTraceGetter is used,
1320   // but the user can set this field to use a custom getter if that is
1321   // desired.
1322   OsStackTraceGetterInterface* os_stack_trace_getter_;
1323 
1324   // True if and only if PostFlagParsingInit() has been called.
1325   bool post_flag_parse_init_performed_;
1326 
1327   // The random number seed used at the beginning of the test run.
1328   int random_seed_;
1329 
1330   // Our random number generator.
1331   internal::Random random_;
1332 
1333   // The time of the test program start, in ms from the start of the
1334   // UNIX epoch.
1335   TimeInMillis start_timestamp_;
1336 
1337   // How long the test took to run, in milliseconds.
1338   TimeInMillis elapsed_time_;
1339 
1340 #if GTEST_HAS_DEATH_TEST
1341   // The decomposed components of the gtest_internal_run_death_test flag,
1342   // parsed when RUN_ALL_TESTS is called.
1343   std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1344   std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
1345 #endif  // GTEST_HAS_DEATH_TEST
1346 
1347   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1348   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1349 
1350   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1351   // starts.
1352   bool catch_exceptions_;
1353 
1354   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1355 };  // class UnitTestImpl
1356 
1357 // Convenience function for accessing the global UnitTest
1358 // implementation object.
GetUnitTestImpl()1359 inline UnitTestImpl* GetUnitTestImpl() {
1360   return UnitTest::GetInstance()->impl();
1361 }
1362 
1363 #if GTEST_USES_SIMPLE_RE
1364 
1365 // Internal helper functions for implementing the simple regular
1366 // expression matcher.
1367 GTEST_API_ bool IsInSet(char ch, const char* str);
1368 GTEST_API_ bool IsAsciiDigit(char ch);
1369 GTEST_API_ bool IsAsciiPunct(char ch);
1370 GTEST_API_ bool IsRepeat(char ch);
1371 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1372 GTEST_API_ bool IsAsciiWordChar(char ch);
1373 GTEST_API_ bool IsValidEscape(char ch);
1374 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1375 GTEST_API_ bool ValidateRegex(const char* regex);
1376 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1377 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1378     bool escaped, char ch, char repeat, const char* regex, const char* str);
1379 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1380 
1381 #endif  // GTEST_USES_SIMPLE_RE
1382 
1383 // Parses the command line for Google Test flags, without initializing
1384 // other parts of Google Test.
1385 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1386 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1387 
1388 #if GTEST_HAS_DEATH_TEST
1389 
1390 // Returns the message describing the last system error, regardless of the
1391 // platform.
1392 GTEST_API_ std::string GetLastErrnoDescription();
1393 
1394 // Attempts to parse a string into a positive integer pointed to by the
1395 // number parameter.  Returns true if that is possible.
1396 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1397 // it here.
1398 template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)1399 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1400   // Fail fast if the given string does not begin with a digit;
1401   // this bypasses strtoXXX's "optional leading whitespace and plus
1402   // or minus sign" semantics, which are undesirable here.
1403   if (str.empty() || !IsDigit(str[0])) {
1404     return false;
1405   }
1406   errno = 0;
1407 
1408   char* end;
1409   // BiggestConvertible is the largest integer type that system-provided
1410   // string-to-number conversion routines can return.
1411   using BiggestConvertible = unsigned long long;  // NOLINT
1412 
1413   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);  // NOLINT
1414   const bool parse_success = *end == '\0' && errno == 0;
1415 
1416   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1417 
1418   const Integer result = static_cast<Integer>(parsed);
1419   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1420     *number = result;
1421     return true;
1422   }
1423   return false;
1424 }
1425 #endif  // GTEST_HAS_DEATH_TEST
1426 
1427 // TestResult contains some private methods that should be hidden from
1428 // Google Test user but are required for testing. This class allow our tests
1429 // to access them.
1430 //
1431 // This class is supplied only for the purpose of testing Google Test's own
1432 // constructs. Do not use it in user tests, either directly or indirectly.
1433 class TestResultAccessor {
1434  public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1435   static void RecordProperty(TestResult* test_result,
1436                              const std::string& xml_element,
1437                              const TestProperty& property) {
1438     test_result->RecordProperty(xml_element, property);
1439   }
1440 
ClearTestPartResults(TestResult * test_result)1441   static void ClearTestPartResults(TestResult* test_result) {
1442     test_result->ClearTestPartResults();
1443   }
1444 
test_part_results(const TestResult & test_result)1445   static const std::vector<testing::TestPartResult>& test_part_results(
1446       const TestResult& test_result) {
1447     return test_result.test_part_results();
1448   }
1449 };
1450 
1451 #if GTEST_CAN_STREAM_RESULTS_
1452 
1453 // Streams test results to the given port on the given host machine.
1454 class StreamingListener : public EmptyTestEventListener {
1455  public:
1456   // Abstract base class for writing strings to a socket.
1457   class AbstractSocketWriter {
1458    public:
~AbstractSocketWriter()1459     virtual ~AbstractSocketWriter() {}
1460 
1461     // Sends a string to the socket.
1462     virtual void Send(const std::string& message) = 0;
1463 
1464     // Closes the socket.
CloseConnection()1465     virtual void CloseConnection() {}
1466 
1467     // Sends a string and a newline to the socket.
SendLn(const std::string & message)1468     void SendLn(const std::string& message) { Send(message + "\n"); }
1469   };
1470 
1471   // Concrete class for actually writing strings to a socket.
1472   class SocketWriter : public AbstractSocketWriter {
1473    public:
SocketWriter(const std::string & host,const std::string & port)1474     SocketWriter(const std::string& host, const std::string& port)
1475         : sockfd_(-1), host_name_(host), port_num_(port) {
1476       MakeConnection();
1477     }
1478 
~SocketWriter()1479     ~SocketWriter() override {
1480       if (sockfd_ != -1)
1481         CloseConnection();
1482     }
1483 
1484     // Sends a string to the socket.
Send(const std::string & message)1485     void Send(const std::string& message) override {
1486       GTEST_CHECK_(sockfd_ != -1)
1487           << "Send() can be called only when there is a connection.";
1488 
1489       const auto len = static_cast<size_t>(message.length());
1490       if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
1491         GTEST_LOG_(WARNING)
1492             << "stream_result_to: failed to stream to "
1493             << host_name_ << ":" << port_num_;
1494       }
1495     }
1496 
1497    private:
1498     // Creates a client socket and connects to the server.
1499     void MakeConnection();
1500 
1501     // Closes the socket.
CloseConnection()1502     void CloseConnection() override {
1503       GTEST_CHECK_(sockfd_ != -1)
1504           << "CloseConnection() can be called only when there is a connection.";
1505 
1506       close(sockfd_);
1507       sockfd_ = -1;
1508     }
1509 
1510     int sockfd_;  // socket file descriptor
1511     const std::string host_name_;
1512     const std::string port_num_;
1513 
1514     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1515   };  // class SocketWriter
1516 
1517   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1518   static std::string UrlEncode(const char* str);
1519 
StreamingListener(const std::string & host,const std::string & port)1520   StreamingListener(const std::string& host, const std::string& port)
1521       : socket_writer_(new SocketWriter(host, port)) {
1522     Start();
1523   }
1524 
StreamingListener(AbstractSocketWriter * socket_writer)1525   explicit StreamingListener(AbstractSocketWriter* socket_writer)
1526       : socket_writer_(socket_writer) { Start(); }
1527 
OnTestProgramStart(const UnitTest &)1528   void OnTestProgramStart(const UnitTest& /* unit_test */) override {
1529     SendLn("event=TestProgramStart");
1530   }
1531 
OnTestProgramEnd(const UnitTest & unit_test)1532   void OnTestProgramEnd(const UnitTest& unit_test) override {
1533     // Note that Google Test current only report elapsed time for each
1534     // test iteration, not for the entire test program.
1535     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1536 
1537     // Notify the streaming server to stop.
1538     socket_writer_->CloseConnection();
1539   }
1540 
OnTestIterationStart(const UnitTest &,int iteration)1541   void OnTestIterationStart(const UnitTest& /* unit_test */,
1542                             int iteration) override {
1543     SendLn("event=TestIterationStart&iteration=" +
1544            StreamableToString(iteration));
1545   }
1546 
OnTestIterationEnd(const UnitTest & unit_test,int)1547   void OnTestIterationEnd(const UnitTest& unit_test,
1548                           int /* iteration */) override {
1549     SendLn("event=TestIterationEnd&passed=" +
1550            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1551            StreamableToString(unit_test.elapsed_time()) + "ms");
1552   }
1553 
1554   // Note that "event=TestCaseStart" is a wire format and has to remain
1555   // "case" for compatibility
OnTestCaseStart(const TestCase & test_case)1556   void OnTestCaseStart(const TestCase& test_case) override {
1557     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1558   }
1559 
1560   // Note that "event=TestCaseEnd" is a wire format and has to remain
1561   // "case" for compatibility
OnTestCaseEnd(const TestCase & test_case)1562   void OnTestCaseEnd(const TestCase& test_case) override {
1563     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
1564            "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
1565            "ms");
1566   }
1567 
OnTestStart(const TestInfo & test_info)1568   void OnTestStart(const TestInfo& test_info) override {
1569     SendLn(std::string("event=TestStart&name=") + test_info.name());
1570   }
1571 
OnTestEnd(const TestInfo & test_info)1572   void OnTestEnd(const TestInfo& test_info) override {
1573     SendLn("event=TestEnd&passed=" +
1574            FormatBool((test_info.result())->Passed()) +
1575            "&elapsed_time=" +
1576            StreamableToString((test_info.result())->elapsed_time()) + "ms");
1577   }
1578 
OnTestPartResult(const TestPartResult & test_part_result)1579   void OnTestPartResult(const TestPartResult& test_part_result) override {
1580     const char* file_name = test_part_result.file_name();
1581     if (file_name == nullptr) file_name = "";
1582     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1583            "&line=" + StreamableToString(test_part_result.line_number()) +
1584            "&message=" + UrlEncode(test_part_result.message()));
1585   }
1586 
1587  private:
1588   // Sends the given message and a newline to the socket.
SendLn(const std::string & message)1589   void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1590 
1591   // Called at the start of streaming to notify the receiver what
1592   // protocol we are using.
Start()1593   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1594 
FormatBool(bool value)1595   std::string FormatBool(bool value) { return value ? "1" : "0"; }
1596 
1597   const std::unique_ptr<AbstractSocketWriter> socket_writer_;
1598 
1599   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1600 };  // class StreamingListener
1601 
1602 #endif  // GTEST_CAN_STREAM_RESULTS_
1603 
1604 }  // namespace internal
1605 }  // namespace testing
1606 
1607 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
1608 
1609 #endif  // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
1610 
1611 #if GTEST_OS_WINDOWS
1612 # define vsnprintf _vsnprintf
1613 #endif  // GTEST_OS_WINDOWS
1614 
1615 #if GTEST_OS_MAC
1616 #ifndef GTEST_OS_IOS
1617 #include <crt_externs.h>
1618 #endif
1619 #endif
1620 
1621 #if GTEST_HAS_ABSL
1622 #include "absl/debugging/failure_signal_handler.h"
1623 #include "absl/debugging/stacktrace.h"
1624 #include "absl/debugging/symbolize.h"
1625 #include "absl/strings/str_cat.h"
1626 #endif  // GTEST_HAS_ABSL
1627 
1628 namespace testing {
1629 
1630 using internal::CountIf;
1631 using internal::ForEach;
1632 using internal::GetElementOr;
1633 using internal::Shuffle;
1634 
1635 // Constants.
1636 
1637 // A test whose test suite name or test name matches this filter is
1638 // disabled and not run.
1639 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1640 
1641 // A test suite whose name matches this filter is considered a death
1642 // test suite and will be run before test suites whose name doesn't
1643 // match this filter.
1644 static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
1645 
1646 // A test filter that matches everything.
1647 static const char kUniversalFilter[] = "*";
1648 
1649 // The default output format.
1650 static const char kDefaultOutputFormat[] = "xml";
1651 // The default output file.
1652 static const char kDefaultOutputFile[] = "test_detail";
1653 
1654 // The environment variable name for the test shard index.
1655 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1656 // The environment variable name for the total number of test shards.
1657 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1658 // The environment variable name for the test shard status file.
1659 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1660 
1661 namespace internal {
1662 
1663 // The text used in failure messages to indicate the start of the
1664 // stack trace.
1665 const char kStackTraceMarker[] = "\nStack trace:\n";
1666 
1667 // g_help_flag is true if and only if the --help flag or an equivalent form
1668 // is specified on the command line.
1669 bool g_help_flag = false;
1670 
1671 // Utilty function to Open File for Writing
OpenFileForWriting(const std::string & output_file)1672 static FILE* OpenFileForWriting(const std::string& output_file) {
1673   FILE* fileout = nullptr;
1674   FilePath output_file_path(output_file);
1675   FilePath output_dir(output_file_path.RemoveFileName());
1676 
1677   if (output_dir.CreateDirectoriesRecursively()) {
1678     fileout = posix::FOpen(output_file.c_str(), "w");
1679   }
1680   if (fileout == nullptr) {
1681     GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
1682   }
1683   return fileout;
1684 }
1685 
1686 }  // namespace internal
1687 
1688 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
1689 // environment variable.
GetDefaultFilter()1690 static const char* GetDefaultFilter() {
1691   const char* const testbridge_test_only =
1692       internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
1693   if (testbridge_test_only != nullptr) {
1694     return testbridge_test_only;
1695   }
1696   return kUniversalFilter;
1697 }
1698 
1699 // Bazel passes in the argument to '--test_runner_fail_fast' via the
1700 // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
GetDefaultFailFast()1701 static bool GetDefaultFailFast() {
1702   const char* const testbridge_test_runner_fail_fast =
1703       internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
1704   if (testbridge_test_runner_fail_fast != nullptr) {
1705     return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
1706   }
1707   return false;
1708 }
1709 
1710 GTEST_DEFINE_bool_(
1711     fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
1712     "True if and only if a test failure should stop further test execution.");
1713 
1714 GTEST_DEFINE_bool_(
1715     also_run_disabled_tests,
1716     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1717     "Run disabled tests too, in addition to the tests normally being run.");
1718 
1719 GTEST_DEFINE_bool_(
1720     break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
1721     "True if and only if a failed assertion should be a debugger "
1722     "break-point.");
1723 
1724 GTEST_DEFINE_bool_(catch_exceptions,
1725                    internal::BoolFromGTestEnv("catch_exceptions", true),
1726                    "True if and only if " GTEST_NAME_
1727                    " should catch exceptions and treat them as test failures.");
1728 
1729 GTEST_DEFINE_string_(
1730     color,
1731     internal::StringFromGTestEnv("color", "auto"),
1732     "Whether to use colors in the output.  Valid values: yes, no, "
1733     "and auto.  'auto' means to use colors if the output is "
1734     "being sent to a terminal and the TERM environment variable "
1735     "is set to a terminal type that supports colors.");
1736 
1737 GTEST_DEFINE_string_(
1738     filter,
1739     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1740     "A colon-separated list of glob (not regex) patterns "
1741     "for filtering the tests to run, optionally followed by a "
1742     "'-' and a : separated list of negative patterns (tests to "
1743     "exclude).  A test is run if it matches one of the positive "
1744     "patterns and does not match any of the negative patterns.");
1745 
1746 GTEST_DEFINE_bool_(
1747     install_failure_signal_handler,
1748     internal::BoolFromGTestEnv("install_failure_signal_handler", false),
1749     "If true and supported on the current platform, " GTEST_NAME_ " should "
1750     "install a signal handler that dumps debugging information when fatal "
1751     "signals are raised.");
1752 
1753 GTEST_DEFINE_bool_(list_tests, false,
1754                    "List all tests without running them.");
1755 
1756 // The net priority order after flag processing is thus:
1757 //   --gtest_output command line flag
1758 //   GTEST_OUTPUT environment variable
1759 //   XML_OUTPUT_FILE environment variable
1760 //   ''
1761 GTEST_DEFINE_string_(
1762     output,
1763     internal::StringFromGTestEnv("output",
1764       internal::OutputFlagAlsoCheckEnvVar().c_str()),
1765     "A format (defaults to \"xml\" but can be specified to be \"json\"), "
1766     "optionally followed by a colon and an output file name or directory. "
1767     "A directory is indicated by a trailing pathname separator. "
1768     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1769     "If a directory is specified, output files will be created "
1770     "within that directory, with file-names based on the test "
1771     "executable's name and, if necessary, made unique by adding "
1772     "digits.");
1773 
1774 GTEST_DEFINE_bool_(
1775     brief, internal::BoolFromGTestEnv("brief", false),
1776     "True if only test failures should be displayed in text output.");
1777 
1778 GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
1779                    "True if and only if " GTEST_NAME_
1780                    " should display elapsed time in text output.");
1781 
1782 GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true),
1783                    "True if and only if " GTEST_NAME_
1784                    " prints UTF8 characters as text.");
1785 
1786 GTEST_DEFINE_int32_(
1787     random_seed,
1788     internal::Int32FromGTestEnv("random_seed", 0),
1789     "Random number seed to use when shuffling test orders.  Must be in range "
1790     "[1, 99999], or 0 to use a seed based on the current time.");
1791 
1792 GTEST_DEFINE_int32_(
1793     repeat,
1794     internal::Int32FromGTestEnv("repeat", 1),
1795     "How many times to repeat each test.  Specify a negative number "
1796     "for repeating forever.  Useful for shaking out flaky tests.");
1797 
1798 GTEST_DEFINE_bool_(show_internal_stack_frames, false,
1799                    "True if and only if " GTEST_NAME_
1800                    " should include internal stack frames when "
1801                    "printing test failure stack traces.");
1802 
1803 GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
1804                    "True if and only if " GTEST_NAME_
1805                    " should randomize tests' order on every run.");
1806 
1807 GTEST_DEFINE_int32_(
1808     stack_trace_depth,
1809     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1810     "The maximum number of stack frames to print when an "
1811     "assertion fails.  The valid range is 0 through 100, inclusive.");
1812 
1813 GTEST_DEFINE_string_(
1814     stream_result_to,
1815     internal::StringFromGTestEnv("stream_result_to", ""),
1816     "This flag specifies the host name and the port number on which to stream "
1817     "test results. Example: \"localhost:555\". The flag is effective only on "
1818     "Linux.");
1819 
1820 GTEST_DEFINE_bool_(
1821     throw_on_failure,
1822     internal::BoolFromGTestEnv("throw_on_failure", false),
1823     "When this flag is specified, a failed assertion will throw an exception "
1824     "if exceptions are enabled or exit the program with a non-zero code "
1825     "otherwise. For use with an external test framework.");
1826 
1827 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1828 GTEST_DEFINE_string_(
1829     flagfile,
1830     internal::StringFromGTestEnv("flagfile", ""),
1831     "This flag specifies the flagfile to read command-line flags from.");
1832 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
1833 
1834 namespace internal {
1835 
1836 // Generates a random number from [0, range), using a Linear
1837 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
1838 // than kMaxRange.
Generate(uint32_t range)1839 uint32_t Random::Generate(uint32_t range) {
1840   // These constants are the same as are used in glibc's rand(3).
1841   // Use wider types than necessary to prevent unsigned overflow diagnostics.
1842   state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange;
1843 
1844   GTEST_CHECK_(range > 0)
1845       << "Cannot generate a number in the range [0, 0).";
1846   GTEST_CHECK_(range <= kMaxRange)
1847       << "Generation of a number in [0, " << range << ") was requested, "
1848       << "but this can only generate numbers in [0, " << kMaxRange << ").";
1849 
1850   // Converting via modulus introduces a bit of downward bias, but
1851   // it's simple, and a linear congruential generator isn't too good
1852   // to begin with.
1853   return state_ % range;
1854 }
1855 
1856 // GTestIsInitialized() returns true if and only if the user has initialized
1857 // Google Test.  Useful for catching the user mistake of not initializing
1858 // Google Test before calling RUN_ALL_TESTS().
GTestIsInitialized()1859 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1860 
1861 // Iterates over a vector of TestSuites, keeping a running sum of the
1862 // results of calling a given int-returning method on each.
1863 // Returns the sum.
SumOverTestSuiteList(const std::vector<TestSuite * > & case_list,int (TestSuite::* method)()const)1864 static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
1865                                 int (TestSuite::*method)() const) {
1866   int sum = 0;
1867   for (size_t i = 0; i < case_list.size(); i++) {
1868     sum += (case_list[i]->*method)();
1869   }
1870   return sum;
1871 }
1872 
1873 // Returns true if and only if the test suite passed.
TestSuitePassed(const TestSuite * test_suite)1874 static bool TestSuitePassed(const TestSuite* test_suite) {
1875   return test_suite->should_run() && test_suite->Passed();
1876 }
1877 
1878 // Returns true if and only if the test suite failed.
TestSuiteFailed(const TestSuite * test_suite)1879 static bool TestSuiteFailed(const TestSuite* test_suite) {
1880   return test_suite->should_run() && test_suite->Failed();
1881 }
1882 
1883 // Returns true if and only if test_suite contains at least one test that
1884 // should run.
ShouldRunTestSuite(const TestSuite * test_suite)1885 static bool ShouldRunTestSuite(const TestSuite* test_suite) {
1886   return test_suite->should_run();
1887 }
1888 
1889 // AssertHelper constructor.
AssertHelper(TestPartResult::Type type,const char * file,int line,const char * message)1890 AssertHelper::AssertHelper(TestPartResult::Type type,
1891                            const char* file,
1892                            int line,
1893                            const char* message)
1894     : data_(new AssertHelperData(type, file, line, message)) {
1895 }
1896 
~AssertHelper()1897 AssertHelper::~AssertHelper() {
1898   delete data_;
1899 }
1900 
1901 // Message assignment, for assertion streaming support.
operator =(const Message & message) const1902 void AssertHelper::operator=(const Message& message) const {
1903   UnitTest::GetInstance()->
1904     AddTestPartResult(data_->type, data_->file, data_->line,
1905                       AppendUserMessage(data_->message, message),
1906                       UnitTest::GetInstance()->impl()
1907                       ->CurrentOsStackTraceExceptTop(1)
1908                       // Skips the stack frame for this function itself.
1909                       );  // NOLINT
1910 }
1911 
1912 namespace {
1913 
1914 // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
1915 // to creates test cases for it, a syntetic test case is
1916 // inserted to report ether an error or a log message.
1917 //
1918 // This configuration bit will likely be removed at some point.
1919 constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
1920 constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
1921 
1922 // A test that fails at a given file/line location with a given message.
1923 class FailureTest : public Test {
1924  public:
FailureTest(const CodeLocation & loc,std::string error_message,bool as_error)1925   explicit FailureTest(const CodeLocation& loc, std::string error_message,
1926                        bool as_error)
1927       : loc_(loc),
1928         error_message_(std::move(error_message)),
1929         as_error_(as_error) {}
1930 
TestBody()1931   void TestBody() override {
1932     if (as_error_) {
1933       AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
1934                    loc_.line, "") = Message() << error_message_;
1935     } else {
1936       std::cout << error_message_ << std::endl;
1937     }
1938   }
1939 
1940  private:
1941   const CodeLocation loc_;
1942   const std::string error_message_;
1943   const bool as_error_;
1944 };
1945 
1946 
1947 }  // namespace
1948 
GetIgnoredParameterizedTestSuites()1949 std::set<std::string>* GetIgnoredParameterizedTestSuites() {
1950   return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
1951 }
1952 
1953 // Add a given test_suit to the list of them allow to go un-instantiated.
MarkAsIgnored(const char * test_suite)1954 MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
1955   GetIgnoredParameterizedTestSuites()->insert(test_suite);
1956 }
1957 
1958 // If this parameterized test suite has no instantiations (and that
1959 // has not been marked as okay), emit a test case reporting that.
InsertSyntheticTestCase(const std::string & name,CodeLocation location,bool has_test_p)1960 void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
1961                              bool has_test_p) {
1962   const auto& ignored = *GetIgnoredParameterizedTestSuites();
1963   if (ignored.find(name) != ignored.end()) return;
1964 
1965   const char kMissingInstantiation[] =  //
1966       " is defined via TEST_P, but never instantiated. None of the test cases "
1967       "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
1968       "ones provided expand to nothing."
1969       "\n\n"
1970       "Ideally, TEST_P definitions should only ever be included as part of "
1971       "binaries that intend to use them. (As opposed to, for example, being "
1972       "placed in a library that may be linked in to get other utilities.)";
1973 
1974   const char kMissingTestCase[] =  //
1975       " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
1976       "defined via TEST_P . No test cases will run."
1977       "\n\n"
1978       "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
1979       "code that always depend on code that provides TEST_P. Failing to do "
1980       "so is often an indication of dead code, e.g. the last TEST_P was "
1981       "removed but the rest got left behind.";
1982 
1983   std::string message =
1984       "Parameterized test suite " + name +
1985       (has_test_p ? kMissingInstantiation : kMissingTestCase) +
1986       "\n\n"
1987       "To suppress this error for this test suite, insert the following line "
1988       "(in a non-header) in the namespace it is defined in:"
1989       "\n\n"
1990       "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
1991 
1992   std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
1993   RegisterTest(  //
1994       "GoogleTestVerification", full_name.c_str(),
1995       nullptr,  // No type parameter.
1996       nullptr,  // No value parameter.
1997       location.file.c_str(), location.line, [message, location] {
1998         return new FailureTest(location, message,
1999                                kErrorOnUninstantiatedParameterizedTest);
2000       });
2001 }
2002 
RegisterTypeParameterizedTestSuite(const char * test_suite_name,CodeLocation code_location)2003 void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
2004                                         CodeLocation code_location) {
2005   GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
2006       test_suite_name, code_location);
2007 }
2008 
RegisterTypeParameterizedTestSuiteInstantiation(const char * case_name)2009 void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
2010   GetUnitTestImpl()
2011       ->type_parameterized_test_registry()
2012       .RegisterInstantiation(case_name);
2013 }
2014 
RegisterTestSuite(const char * test_suite_name,CodeLocation code_location)2015 void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
2016     const char* test_suite_name, CodeLocation code_location) {
2017   suites_.emplace(std::string(test_suite_name),
2018                  TypeParameterizedTestSuiteInfo(code_location));
2019 }
2020 
RegisterInstantiation(const char * test_suite_name)2021 void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
2022         const char* test_suite_name) {
2023   auto it = suites_.find(std::string(test_suite_name));
2024   if (it != suites_.end()) {
2025     it->second.instantiated = true;
2026   } else {
2027     GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
2028                       << test_suite_name << "'";
2029   }
2030 }
2031 
CheckForInstantiations()2032 void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
2033   const auto& ignored = *GetIgnoredParameterizedTestSuites();
2034   for (const auto& testcase : suites_) {
2035     if (testcase.second.instantiated) continue;
2036     if (ignored.find(testcase.first) != ignored.end()) continue;
2037 
2038     std::string message =
2039         "Type parameterized test suite " + testcase.first +
2040         " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
2041         "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
2042         "\n\n"
2043         "Ideally, TYPED_TEST_P definitions should only ever be included as "
2044         "part of binaries that intend to use them. (As opposed to, for "
2045         "example, being placed in a library that may be linked in to get other "
2046         "utilities.)"
2047         "\n\n"
2048         "To suppress this error for this test suite, insert the following line "
2049         "(in a non-header) in the namespace it is defined in:"
2050         "\n\n"
2051         "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
2052         testcase.first + ");";
2053 
2054     std::string full_name =
2055         "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
2056     RegisterTest(  //
2057         "GoogleTestVerification", full_name.c_str(),
2058         nullptr,  // No type parameter.
2059         nullptr,  // No value parameter.
2060         testcase.second.code_location.file.c_str(),
2061         testcase.second.code_location.line, [message, testcase] {
2062           return new FailureTest(testcase.second.code_location, message,
2063                                  kErrorOnUninstantiatedTypeParameterizedTest);
2064         });
2065   }
2066 }
2067 
2068 // A copy of all command line arguments.  Set by InitGoogleTest().
2069 static ::std::vector<std::string> g_argvs;
2070 
GetArgvs()2071 ::std::vector<std::string> GetArgvs() {
2072 #if defined(GTEST_CUSTOM_GET_ARGVS_)
2073   // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
2074   // ::string. This code converts it to the appropriate type.
2075   const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
2076   return ::std::vector<std::string>(custom.begin(), custom.end());
2077 #else   // defined(GTEST_CUSTOM_GET_ARGVS_)
2078   return g_argvs;
2079 #endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
2080 }
2081 
2082 // Returns the current application's name, removing directory path if that
2083 // is present.
GetCurrentExecutableName()2084 FilePath GetCurrentExecutableName() {
2085   FilePath result;
2086 
2087 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
2088   result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
2089 #else
2090   result.Set(FilePath(GetArgvs()[0]));
2091 #endif  // GTEST_OS_WINDOWS
2092 
2093   return result.RemoveDirectoryName();
2094 }
2095 
2096 // Functions for processing the gtest_output flag.
2097 
2098 // Returns the output format, or "" for normal printed output.
GetOutputFormat()2099 std::string UnitTestOptions::GetOutputFormat() {
2100   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
2101   const char* const colon = strchr(gtest_output_flag, ':');
2102   return (colon == nullptr)
2103              ? std::string(gtest_output_flag)
2104              : std::string(gtest_output_flag,
2105                            static_cast<size_t>(colon - gtest_output_flag));
2106 }
2107 
2108 // Returns the name of the requested output file, or the default if none
2109 // was explicitly specified.
GetAbsolutePathToOutputFile()2110 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
2111   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
2112 
2113   std::string format = GetOutputFormat();
2114   if (format.empty())
2115     format = std::string(kDefaultOutputFormat);
2116 
2117   const char* const colon = strchr(gtest_output_flag, ':');
2118   if (colon == nullptr)
2119     return internal::FilePath::MakeFileName(
2120         internal::FilePath(
2121             UnitTest::GetInstance()->original_working_dir()),
2122         internal::FilePath(kDefaultOutputFile), 0,
2123         format.c_str()).string();
2124 
2125   internal::FilePath output_name(colon + 1);
2126   if (!output_name.IsAbsolutePath())
2127     output_name = internal::FilePath::ConcatPaths(
2128         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
2129         internal::FilePath(colon + 1));
2130 
2131   if (!output_name.IsDirectory())
2132     return output_name.string();
2133 
2134   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
2135       output_name, internal::GetCurrentExecutableName(),
2136       GetOutputFormat().c_str()));
2137   return result.string();
2138 }
2139 
2140 // Returns true if and only if the wildcard pattern matches the string. Each
2141 // pattern consists of regular characters, single-character wildcards (?), and
2142 // multi-character wildcards (*).
2143 //
2144 // This function implements a linear-time string globbing algorithm based on
2145 // https://research.swtch.com/glob.
PatternMatchesString(const std::string & name_str,const char * pattern,const char * pattern_end)2146 static bool PatternMatchesString(const std::string& name_str,
2147                                  const char* pattern, const char* pattern_end) {
2148   const char* name = name_str.c_str();
2149   const char* const name_begin = name;
2150   const char* const name_end = name + name_str.size();
2151 
2152   const char* pattern_next = pattern;
2153   const char* name_next = name;
2154 
2155   while (pattern < pattern_end || name < name_end) {
2156     if (pattern < pattern_end) {
2157       switch (*pattern) {
2158         default:  // Match an ordinary character.
2159           if (name < name_end && *name == *pattern) {
2160             ++pattern;
2161             ++name;
2162             continue;
2163           }
2164           break;
2165         case '?':  // Match any single character.
2166           if (name < name_end) {
2167             ++pattern;
2168             ++name;
2169             continue;
2170           }
2171           break;
2172         case '*':
2173           // Match zero or more characters. Start by skipping over the wildcard
2174           // and matching zero characters from name. If that fails, restart and
2175           // match one more character than the last attempt.
2176           pattern_next = pattern;
2177           name_next = name + 1;
2178           ++pattern;
2179           continue;
2180       }
2181     }
2182     // Failed to match a character. Restart if possible.
2183     if (name_begin < name_next && name_next <= name_end) {
2184       pattern = pattern_next;
2185       name = name_next;
2186       continue;
2187     }
2188     return false;
2189   }
2190   return true;
2191 }
2192 
MatchesFilter(const std::string & name_str,const char * filter)2193 bool UnitTestOptions::MatchesFilter(const std::string& name_str,
2194                                     const char* filter) {
2195   // The filter is a list of patterns separated by colons (:).
2196   const char* pattern = filter;
2197   while (true) {
2198     // Find the bounds of this pattern.
2199     const char* const next_sep = strchr(pattern, ':');
2200     const char* const pattern_end =
2201         next_sep != nullptr ? next_sep : pattern + strlen(pattern);
2202 
2203     // Check if this pattern matches name_str.
2204     if (PatternMatchesString(name_str, pattern, pattern_end)) {
2205       return true;
2206     }
2207 
2208     // Give up on this pattern. However, if we found a pattern separator (:),
2209     // advance to the next pattern (skipping over the separator) and restart.
2210     if (next_sep == nullptr) {
2211       return false;
2212     }
2213     pattern = next_sep + 1;
2214   }
2215   return true;
2216 }
2217 
2218 // Returns true if and only if the user-specified filter matches the test
2219 // suite name and the test name.
FilterMatchesTest(const std::string & test_suite_name,const std::string & test_name)2220 bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
2221                                         const std::string& test_name) {
2222   const std::string& full_name = test_suite_name + "." + test_name.c_str();
2223 
2224   // Split --gtest_filter at '-', if there is one, to separate into
2225   // positive filter and negative filter portions
2226   const char* const p = GTEST_FLAG(filter).c_str();
2227   const char* const dash = strchr(p, '-');
2228   std::string positive;
2229   std::string negative;
2230   if (dash == nullptr) {
2231     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
2232     negative = "";
2233   } else {
2234     positive = std::string(p, dash);   // Everything up to the dash
2235     negative = std::string(dash + 1);  // Everything after the dash
2236     if (positive.empty()) {
2237       // Treat '-test1' as the same as '*-test1'
2238       positive = kUniversalFilter;
2239     }
2240   }
2241 
2242   // A filter is a colon-separated list of patterns.  It matches a
2243   // test if any pattern in it matches the test.
2244   return (MatchesFilter(full_name, positive.c_str()) &&
2245           !MatchesFilter(full_name, negative.c_str()));
2246 }
2247 
2248 #if GTEST_HAS_SEH
2249 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
2250 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
2251 // This function is useful as an __except condition.
GTestShouldProcessSEH(DWORD exception_code)2252 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2253   // Google Test should handle a SEH exception if:
2254   //   1. the user wants it to, AND
2255   //   2. this is not a breakpoint exception, AND
2256   //   3. this is not a C++ exception (VC++ implements them via SEH,
2257   //      apparently).
2258   //
2259   // SEH exception code for C++ exceptions.
2260   // (see http://support.microsoft.com/kb/185294 for more information).
2261   const DWORD kCxxExceptionCode = 0xe06d7363;
2262 
2263   bool should_handle = true;
2264 
2265   if (!GTEST_FLAG(catch_exceptions))
2266     should_handle = false;
2267   else if (exception_code == EXCEPTION_BREAKPOINT)
2268     should_handle = false;
2269   else if (exception_code == kCxxExceptionCode)
2270     should_handle = false;
2271 
2272   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2273 }
2274 #endif  // GTEST_HAS_SEH
2275 
2276 }  // namespace internal
2277 
2278 // The c'tor sets this object as the test part result reporter used by
2279 // Google Test.  The 'result' parameter specifies where to report the
2280 // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter(TestPartResultArray * result)2281 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2282     TestPartResultArray* result)
2283     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2284       result_(result) {
2285   Init();
2286 }
2287 
2288 // The c'tor sets this object as the test part result reporter used by
2289 // Google Test.  The 'result' parameter specifies where to report the
2290 // results.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,TestPartResultArray * result)2291 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2292     InterceptMode intercept_mode, TestPartResultArray* result)
2293     : intercept_mode_(intercept_mode),
2294       result_(result) {
2295   Init();
2296 }
2297 
Init()2298 void ScopedFakeTestPartResultReporter::Init() {
2299   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2300   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2301     old_reporter_ = impl->GetGlobalTestPartResultReporter();
2302     impl->SetGlobalTestPartResultReporter(this);
2303   } else {
2304     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2305     impl->SetTestPartResultReporterForCurrentThread(this);
2306   }
2307 }
2308 
2309 // The d'tor restores the test part result reporter used by Google Test
2310 // before.
~ScopedFakeTestPartResultReporter()2311 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2312   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2313   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2314     impl->SetGlobalTestPartResultReporter(old_reporter_);
2315   } else {
2316     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2317   }
2318 }
2319 
2320 // Increments the test part result count and remembers the result.
2321 // This method is from the TestPartResultReporterInterface interface.
ReportTestPartResult(const TestPartResult & result)2322 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2323     const TestPartResult& result) {
2324   result_->Append(result);
2325 }
2326 
2327 namespace internal {
2328 
2329 // Returns the type ID of ::testing::Test.  We should always call this
2330 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2331 // testing::Test.  This is to work around a suspected linker bug when
2332 // using Google Test as a framework on Mac OS X.  The bug causes
2333 // GetTypeId< ::testing::Test>() to return different values depending
2334 // on whether the call is from the Google Test framework itself or
2335 // from user test code.  GetTestTypeId() is guaranteed to always
2336 // return the same value, as it always calls GetTypeId<>() from the
2337 // gtest.cc, which is within the Google Test framework.
GetTestTypeId()2338 TypeId GetTestTypeId() {
2339   return GetTypeId<Test>();
2340 }
2341 
2342 // The value of GetTestTypeId() as seen from within the Google Test
2343 // library.  This is solely for testing GetTestTypeId().
2344 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2345 
2346 // This predicate-formatter checks that 'results' contains a test part
2347 // failure of the given type and that the failure message contains the
2348 // given substring.
HasOneFailure(const char *,const char *,const char *,const TestPartResultArray & results,TestPartResult::Type type,const std::string & substr)2349 static AssertionResult HasOneFailure(const char* /* results_expr */,
2350                                      const char* /* type_expr */,
2351                                      const char* /* substr_expr */,
2352                                      const TestPartResultArray& results,
2353                                      TestPartResult::Type type,
2354                                      const std::string& substr) {
2355   const std::string expected(type == TestPartResult::kFatalFailure ?
2356                         "1 fatal failure" :
2357                         "1 non-fatal failure");
2358   Message msg;
2359   if (results.size() != 1) {
2360     msg << "Expected: " << expected << "\n"
2361         << "  Actual: " << results.size() << " failures";
2362     for (int i = 0; i < results.size(); i++) {
2363       msg << "\n" << results.GetTestPartResult(i);
2364     }
2365     return AssertionFailure() << msg;
2366   }
2367 
2368   const TestPartResult& r = results.GetTestPartResult(0);
2369   if (r.type() != type) {
2370     return AssertionFailure() << "Expected: " << expected << "\n"
2371                               << "  Actual:\n"
2372                               << r;
2373   }
2374 
2375   if (strstr(r.message(), substr.c_str()) == nullptr) {
2376     return AssertionFailure() << "Expected: " << expected << " containing \""
2377                               << substr << "\"\n"
2378                               << "  Actual:\n"
2379                               << r;
2380   }
2381 
2382   return AssertionSuccess();
2383 }
2384 
2385 // The constructor of SingleFailureChecker remembers where to look up
2386 // test part results, what type of failure we expect, and what
2387 // substring the failure message should contain.
SingleFailureChecker(const TestPartResultArray * results,TestPartResult::Type type,const std::string & substr)2388 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2389                                            TestPartResult::Type type,
2390                                            const std::string& substr)
2391     : results_(results), type_(type), substr_(substr) {}
2392 
2393 // The destructor of SingleFailureChecker verifies that the given
2394 // TestPartResultArray contains exactly one failure that has the given
2395 // type and contains the given substring.  If that's not the case, a
2396 // non-fatal failure will be generated.
~SingleFailureChecker()2397 SingleFailureChecker::~SingleFailureChecker() {
2398   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2399 }
2400 
DefaultGlobalTestPartResultReporter(UnitTestImpl * unit_test)2401 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2402     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2403 
ReportTestPartResult(const TestPartResult & result)2404 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2405     const TestPartResult& result) {
2406   unit_test_->current_test_result()->AddTestPartResult(result);
2407   unit_test_->listeners()->repeater()->OnTestPartResult(result);
2408 }
2409 
DefaultPerThreadTestPartResultReporter(UnitTestImpl * unit_test)2410 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2411     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2412 
ReportTestPartResult(const TestPartResult & result)2413 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2414     const TestPartResult& result) {
2415   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2416 }
2417 
2418 // Returns the global test part result reporter.
2419 TestPartResultReporterInterface*
GetGlobalTestPartResultReporter()2420 UnitTestImpl::GetGlobalTestPartResultReporter() {
2421   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2422   return global_test_part_result_repoter_;
2423 }
2424 
2425 // Sets the global test part result reporter.
SetGlobalTestPartResultReporter(TestPartResultReporterInterface * reporter)2426 void UnitTestImpl::SetGlobalTestPartResultReporter(
2427     TestPartResultReporterInterface* reporter) {
2428   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2429   global_test_part_result_repoter_ = reporter;
2430 }
2431 
2432 // Returns the test part result reporter for the current thread.
2433 TestPartResultReporterInterface*
GetTestPartResultReporterForCurrentThread()2434 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2435   return per_thread_test_part_result_reporter_.get();
2436 }
2437 
2438 // Sets the test part result reporter for the current thread.
SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface * reporter)2439 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2440     TestPartResultReporterInterface* reporter) {
2441   per_thread_test_part_result_reporter_.set(reporter);
2442 }
2443 
2444 // Gets the number of successful test suites.
successful_test_suite_count() const2445 int UnitTestImpl::successful_test_suite_count() const {
2446   return CountIf(test_suites_, TestSuitePassed);
2447 }
2448 
2449 // Gets the number of failed test suites.
failed_test_suite_count() const2450 int UnitTestImpl::failed_test_suite_count() const {
2451   return CountIf(test_suites_, TestSuiteFailed);
2452 }
2453 
2454 // Gets the number of all test suites.
total_test_suite_count() const2455 int UnitTestImpl::total_test_suite_count() const {
2456   return static_cast<int>(test_suites_.size());
2457 }
2458 
2459 // Gets the number of all test suites that contain at least one test
2460 // that should run.
test_suite_to_run_count() const2461 int UnitTestImpl::test_suite_to_run_count() const {
2462   return CountIf(test_suites_, ShouldRunTestSuite);
2463 }
2464 
2465 // Gets the number of successful tests.
successful_test_count() const2466 int UnitTestImpl::successful_test_count() const {
2467   return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
2468 }
2469 
2470 // Gets the number of skipped tests.
skipped_test_count() const2471 int UnitTestImpl::skipped_test_count() const {
2472   return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
2473 }
2474 
2475 // Gets the number of failed tests.
failed_test_count() const2476 int UnitTestImpl::failed_test_count() const {
2477   return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
2478 }
2479 
2480 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const2481 int UnitTestImpl::reportable_disabled_test_count() const {
2482   return SumOverTestSuiteList(test_suites_,
2483                               &TestSuite::reportable_disabled_test_count);
2484 }
2485 
2486 // Gets the number of disabled tests.
disabled_test_count() const2487 int UnitTestImpl::disabled_test_count() const {
2488   return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
2489 }
2490 
2491 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const2492 int UnitTestImpl::reportable_test_count() const {
2493   return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
2494 }
2495 
2496 // Gets the number of all tests.
total_test_count() const2497 int UnitTestImpl::total_test_count() const {
2498   return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
2499 }
2500 
2501 // Gets the number of tests that should run.
test_to_run_count() const2502 int UnitTestImpl::test_to_run_count() const {
2503   return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
2504 }
2505 
2506 // Returns the current OS stack trace as an std::string.
2507 //
2508 // The maximum number of stack frames to be included is specified by
2509 // the gtest_stack_trace_depth flag.  The skip_count parameter
2510 // specifies the number of top frames to be skipped, which doesn't
2511 // count against the number of frames to be included.
2512 //
2513 // For example, if Foo() calls Bar(), which in turn calls
2514 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2515 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
CurrentOsStackTraceExceptTop(int skip_count)2516 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2517   return os_stack_trace_getter()->CurrentStackTrace(
2518       static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2519       skip_count + 1
2520       // Skips the user-specified number of frames plus this function
2521       // itself.
2522       );  // NOLINT
2523 }
2524 
2525 // A helper class for measuring elapsed times.
2526 class Timer {
2527  public:
Timer()2528   Timer() : start_(std::chrono::steady_clock::now()) {}
2529 
2530   // Return time elapsed in milliseconds since the timer was created.
Elapsed()2531   TimeInMillis Elapsed() {
2532     return std::chrono::duration_cast<std::chrono::milliseconds>(
2533                std::chrono::steady_clock::now() - start_)
2534         .count();
2535   }
2536 
2537  private:
2538   std::chrono::steady_clock::time_point start_;
2539 };
2540 
2541 // Returns a timestamp as milliseconds since the epoch. Note this time may jump
2542 // around subject to adjustments by the system, to measure elapsed time use
2543 // Timer instead.
GetTimeInMillis()2544 TimeInMillis GetTimeInMillis() {
2545   return std::chrono::duration_cast<std::chrono::milliseconds>(
2546              std::chrono::system_clock::now() -
2547              std::chrono::system_clock::from_time_t(0))
2548       .count();
2549 }
2550 
2551 // Utilities
2552 
2553 // class String.
2554 
2555 #if GTEST_OS_WINDOWS_MOBILE
2556 // Creates a UTF-16 wide string from the given ANSI string, allocating
2557 // memory using new. The caller is responsible for deleting the return
2558 // value using delete[]. Returns the wide string, or NULL if the
2559 // input is NULL.
AnsiToUtf16(const char * ansi)2560 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2561   if (!ansi) return nullptr;
2562   const int length = strlen(ansi);
2563   const int unicode_length =
2564       MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
2565   WCHAR* unicode = new WCHAR[unicode_length + 1];
2566   MultiByteToWideChar(CP_ACP, 0, ansi, length,
2567                       unicode, unicode_length);
2568   unicode[unicode_length] = 0;
2569   return unicode;
2570 }
2571 
2572 // Creates an ANSI string from the given wide string, allocating
2573 // memory using new. The caller is responsible for deleting the return
2574 // value using delete[]. Returns the ANSI string, or NULL if the
2575 // input is NULL.
Utf16ToAnsi(LPCWSTR utf16_str)2576 const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
2577   if (!utf16_str) return nullptr;
2578   const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
2579                                               0, nullptr, nullptr);
2580   char* ansi = new char[ansi_length + 1];
2581   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
2582                       nullptr);
2583   ansi[ansi_length] = 0;
2584   return ansi;
2585 }
2586 
2587 #endif  // GTEST_OS_WINDOWS_MOBILE
2588 
2589 // Compares two C strings.  Returns true if and only if they have the same
2590 // content.
2591 //
2592 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
2593 // C string is considered different to any non-NULL C string,
2594 // including the empty string.
CStringEquals(const char * lhs,const char * rhs)2595 bool String::CStringEquals(const char * lhs, const char * rhs) {
2596   if (lhs == nullptr) return rhs == nullptr;
2597 
2598   if (rhs == nullptr) return false;
2599 
2600   return strcmp(lhs, rhs) == 0;
2601 }
2602 
2603 #if GTEST_HAS_STD_WSTRING
2604 
2605 // Converts an array of wide chars to a narrow string using the UTF-8
2606 // encoding, and streams the result to the given Message object.
StreamWideCharsToMessage(const wchar_t * wstr,size_t length,Message * msg)2607 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2608                                      Message* msg) {
2609   for (size_t i = 0; i != length; ) {  // NOLINT
2610     if (wstr[i] != L'\0') {
2611       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2612       while (i != length && wstr[i] != L'\0')
2613         i++;
2614     } else {
2615       *msg << '\0';
2616       i++;
2617     }
2618   }
2619 }
2620 
2621 #endif  // GTEST_HAS_STD_WSTRING
2622 
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)2623 void SplitString(const ::std::string& str, char delimiter,
2624                  ::std::vector< ::std::string>* dest) {
2625   ::std::vector< ::std::string> parsed;
2626   ::std::string::size_type pos = 0;
2627   while (::testing::internal::AlwaysTrue()) {
2628     const ::std::string::size_type colon = str.find(delimiter, pos);
2629     if (colon == ::std::string::npos) {
2630       parsed.push_back(str.substr(pos));
2631       break;
2632     } else {
2633       parsed.push_back(str.substr(pos, colon - pos));
2634       pos = colon + 1;
2635     }
2636   }
2637   dest->swap(parsed);
2638 }
2639 
2640 }  // namespace internal
2641 
2642 // Constructs an empty Message.
2643 // We allocate the stringstream separately because otherwise each use of
2644 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2645 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2646 // the stack space.
Message()2647 Message::Message() : ss_(new ::std::stringstream) {
2648   // By default, we want there to be enough precision when printing
2649   // a double to a Message.
2650   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2651 }
2652 
2653 // These two overloads allow streaming a wide C string to a Message
2654 // using the UTF-8 encoding.
operator <<(const wchar_t * wide_c_str)2655 Message& Message::operator <<(const wchar_t* wide_c_str) {
2656   return *this << internal::String::ShowWideCString(wide_c_str);
2657 }
operator <<(wchar_t * wide_c_str)2658 Message& Message::operator <<(wchar_t* wide_c_str) {
2659   return *this << internal::String::ShowWideCString(wide_c_str);
2660 }
2661 
2662 #if GTEST_HAS_STD_WSTRING
2663 // Converts the given wide string to a narrow string using the UTF-8
2664 // encoding, and streams the result to this Message object.
operator <<(const::std::wstring & wstr)2665 Message& Message::operator <<(const ::std::wstring& wstr) {
2666   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2667   return *this;
2668 }
2669 #endif  // GTEST_HAS_STD_WSTRING
2670 
2671 // Gets the text streamed to this object so far as an std::string.
2672 // Each '\0' character in the buffer is replaced with "\\0".
GetString() const2673 std::string Message::GetString() const {
2674   return internal::StringStreamToString(ss_.get());
2675 }
2676 
2677 // AssertionResult constructors.
2678 // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult & other)2679 AssertionResult::AssertionResult(const AssertionResult& other)
2680     : success_(other.success_),
2681       message_(other.message_.get() != nullptr
2682                    ? new ::std::string(*other.message_)
2683                    : static_cast< ::std::string*>(nullptr)) {}
2684 
2685 // Swaps two AssertionResults.
swap(AssertionResult & other)2686 void AssertionResult::swap(AssertionResult& other) {
2687   using std::swap;
2688   swap(success_, other.success_);
2689   swap(message_, other.message_);
2690 }
2691 
2692 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
operator !() const2693 AssertionResult AssertionResult::operator!() const {
2694   AssertionResult negation(!success_);
2695   if (message_.get() != nullptr) negation << *message_;
2696   return negation;
2697 }
2698 
2699 // Makes a successful assertion result.
AssertionSuccess()2700 AssertionResult AssertionSuccess() {
2701   return AssertionResult(true);
2702 }
2703 
2704 // Makes a failed assertion result.
AssertionFailure()2705 AssertionResult AssertionFailure() {
2706   return AssertionResult(false);
2707 }
2708 
2709 // Makes a failed assertion result with the given failure message.
2710 // Deprecated; use AssertionFailure() << message.
AssertionFailure(const Message & message)2711 AssertionResult AssertionFailure(const Message& message) {
2712   return AssertionFailure() << message;
2713 }
2714 
2715 namespace internal {
2716 
2717 namespace edit_distance {
CalculateOptimalEdits(const std::vector<size_t> & left,const std::vector<size_t> & right)2718 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2719                                             const std::vector<size_t>& right) {
2720   std::vector<std::vector<double> > costs(
2721       left.size() + 1, std::vector<double>(right.size() + 1));
2722   std::vector<std::vector<EditType> > best_move(
2723       left.size() + 1, std::vector<EditType>(right.size() + 1));
2724 
2725   // Populate for empty right.
2726   for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2727     costs[l_i][0] = static_cast<double>(l_i);
2728     best_move[l_i][0] = kRemove;
2729   }
2730   // Populate for empty left.
2731   for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2732     costs[0][r_i] = static_cast<double>(r_i);
2733     best_move[0][r_i] = kAdd;
2734   }
2735 
2736   for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2737     for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2738       if (left[l_i] == right[r_i]) {
2739         // Found a match. Consume it.
2740         costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2741         best_move[l_i + 1][r_i + 1] = kMatch;
2742         continue;
2743       }
2744 
2745       const double add = costs[l_i + 1][r_i];
2746       const double remove = costs[l_i][r_i + 1];
2747       const double replace = costs[l_i][r_i];
2748       if (add < remove && add < replace) {
2749         costs[l_i + 1][r_i + 1] = add + 1;
2750         best_move[l_i + 1][r_i + 1] = kAdd;
2751       } else if (remove < add && remove < replace) {
2752         costs[l_i + 1][r_i + 1] = remove + 1;
2753         best_move[l_i + 1][r_i + 1] = kRemove;
2754       } else {
2755         // We make replace a little more expensive than add/remove to lower
2756         // their priority.
2757         costs[l_i + 1][r_i + 1] = replace + 1.00001;
2758         best_move[l_i + 1][r_i + 1] = kReplace;
2759       }
2760     }
2761   }
2762 
2763   // Reconstruct the best path. We do it in reverse order.
2764   std::vector<EditType> best_path;
2765   for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2766     EditType move = best_move[l_i][r_i];
2767     best_path.push_back(move);
2768     l_i -= move != kAdd;
2769     r_i -= move != kRemove;
2770   }
2771   std::reverse(best_path.begin(), best_path.end());
2772   return best_path;
2773 }
2774 
2775 namespace {
2776 
2777 // Helper class to convert string into ids with deduplication.
2778 class InternalStrings {
2779  public:
GetId(const std::string & str)2780   size_t GetId(const std::string& str) {
2781     IdMap::iterator it = ids_.find(str);
2782     if (it != ids_.end()) return it->second;
2783     size_t id = ids_.size();
2784     return ids_[str] = id;
2785   }
2786 
2787  private:
2788   typedef std::map<std::string, size_t> IdMap;
2789   IdMap ids_;
2790 };
2791 
2792 }  // namespace
2793 
CalculateOptimalEdits(const std::vector<std::string> & left,const std::vector<std::string> & right)2794 std::vector<EditType> CalculateOptimalEdits(
2795     const std::vector<std::string>& left,
2796     const std::vector<std::string>& right) {
2797   std::vector<size_t> left_ids, right_ids;
2798   {
2799     InternalStrings intern_table;
2800     for (size_t i = 0; i < left.size(); ++i) {
2801       left_ids.push_back(intern_table.GetId(left[i]));
2802     }
2803     for (size_t i = 0; i < right.size(); ++i) {
2804       right_ids.push_back(intern_table.GetId(right[i]));
2805     }
2806   }
2807   return CalculateOptimalEdits(left_ids, right_ids);
2808 }
2809 
2810 namespace {
2811 
2812 // Helper class that holds the state for one hunk and prints it out to the
2813 // stream.
2814 // It reorders adds/removes when possible to group all removes before all
2815 // adds. It also adds the hunk header before printint into the stream.
2816 class Hunk {
2817  public:
Hunk(size_t left_start,size_t right_start)2818   Hunk(size_t left_start, size_t right_start)
2819       : left_start_(left_start),
2820         right_start_(right_start),
2821         adds_(),
2822         removes_(),
2823         common_() {}
2824 
PushLine(char edit,const char * line)2825   void PushLine(char edit, const char* line) {
2826     switch (edit) {
2827       case ' ':
2828         ++common_;
2829         FlushEdits();
2830         hunk_.push_back(std::make_pair(' ', line));
2831         break;
2832       case '-':
2833         ++removes_;
2834         hunk_removes_.push_back(std::make_pair('-', line));
2835         break;
2836       case '+':
2837         ++adds_;
2838         hunk_adds_.push_back(std::make_pair('+', line));
2839         break;
2840     }
2841   }
2842 
PrintTo(std::ostream * os)2843   void PrintTo(std::ostream* os) {
2844     PrintHeader(os);
2845     FlushEdits();
2846     for (std::list<std::pair<char, const char*> >::const_iterator it =
2847              hunk_.begin();
2848          it != hunk_.end(); ++it) {
2849       *os << it->first << it->second << "\n";
2850     }
2851   }
2852 
has_edits() const2853   bool has_edits() const { return adds_ || removes_; }
2854 
2855  private:
FlushEdits()2856   void FlushEdits() {
2857     hunk_.splice(hunk_.end(), hunk_removes_);
2858     hunk_.splice(hunk_.end(), hunk_adds_);
2859   }
2860 
2861   // Print a unified diff header for one hunk.
2862   // The format is
2863   //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2864   // where the left/right parts are omitted if unnecessary.
PrintHeader(std::ostream * ss) const2865   void PrintHeader(std::ostream* ss) const {
2866     *ss << "@@ ";
2867     if (removes_) {
2868       *ss << "-" << left_start_ << "," << (removes_ + common_);
2869     }
2870     if (removes_ && adds_) {
2871       *ss << " ";
2872     }
2873     if (adds_) {
2874       *ss << "+" << right_start_ << "," << (adds_ + common_);
2875     }
2876     *ss << " @@\n";
2877   }
2878 
2879   size_t left_start_, right_start_;
2880   size_t adds_, removes_, common_;
2881   std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2882 };
2883 
2884 }  // namespace
2885 
2886 // Create a list of diff hunks in Unified diff format.
2887 // Each hunk has a header generated by PrintHeader above plus a body with
2888 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
2889 // addition.
2890 // 'context' represents the desired unchanged prefix/suffix around the diff.
2891 // If two hunks are close enough that their contexts overlap, then they are
2892 // joined into one hunk.
CreateUnifiedDiff(const std::vector<std::string> & left,const std::vector<std::string> & right,size_t context)2893 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2894                               const std::vector<std::string>& right,
2895                               size_t context) {
2896   const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2897 
2898   size_t l_i = 0, r_i = 0, edit_i = 0;
2899   std::stringstream ss;
2900   while (edit_i < edits.size()) {
2901     // Find first edit.
2902     while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2903       ++l_i;
2904       ++r_i;
2905       ++edit_i;
2906     }
2907 
2908     // Find the first line to include in the hunk.
2909     const size_t prefix_context = std::min(l_i, context);
2910     Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2911     for (size_t i = prefix_context; i > 0; --i) {
2912       hunk.PushLine(' ', left[l_i - i].c_str());
2913     }
2914 
2915     // Iterate the edits until we found enough suffix for the hunk or the input
2916     // is over.
2917     size_t n_suffix = 0;
2918     for (; edit_i < edits.size(); ++edit_i) {
2919       if (n_suffix >= context) {
2920         // Continue only if the next hunk is very close.
2921         auto it = edits.begin() + static_cast<int>(edit_i);
2922         while (it != edits.end() && *it == kMatch) ++it;
2923         if (it == edits.end() ||
2924             static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
2925           // There is no next edit or it is too far away.
2926           break;
2927         }
2928       }
2929 
2930       EditType edit = edits[edit_i];
2931       // Reset count when a non match is found.
2932       n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2933 
2934       if (edit == kMatch || edit == kRemove || edit == kReplace) {
2935         hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2936       }
2937       if (edit == kAdd || edit == kReplace) {
2938         hunk.PushLine('+', right[r_i].c_str());
2939       }
2940 
2941       // Advance indices, depending on edit type.
2942       l_i += edit != kAdd;
2943       r_i += edit != kRemove;
2944     }
2945 
2946     if (!hunk.has_edits()) {
2947       // We are done. We don't want this hunk.
2948       break;
2949     }
2950 
2951     hunk.PrintTo(&ss);
2952   }
2953   return ss.str();
2954 }
2955 
2956 }  // namespace edit_distance
2957 
2958 namespace {
2959 
2960 // The string representation of the values received in EqFailure() are already
2961 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2962 // characters the same.
SplitEscapedString(const std::string & str)2963 std::vector<std::string> SplitEscapedString(const std::string& str) {
2964   std::vector<std::string> lines;
2965   size_t start = 0, end = str.size();
2966   if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2967     ++start;
2968     --end;
2969   }
2970   bool escaped = false;
2971   for (size_t i = start; i + 1 < end; ++i) {
2972     if (escaped) {
2973       escaped = false;
2974       if (str[i] == 'n') {
2975         lines.push_back(str.substr(start, i - start - 1));
2976         start = i + 1;
2977       }
2978     } else {
2979       escaped = str[i] == '\\';
2980     }
2981   }
2982   lines.push_back(str.substr(start, end - start));
2983   return lines;
2984 }
2985 
2986 }  // namespace
2987 
2988 // Constructs and returns the message for an equality assertion
2989 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2990 //
2991 // The first four parameters are the expressions used in the assertion
2992 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
2993 // where foo is 5 and bar is 6, we have:
2994 //
2995 //   lhs_expression: "foo"
2996 //   rhs_expression: "bar"
2997 //   lhs_value:      "5"
2998 //   rhs_value:      "6"
2999 //
3000 // The ignoring_case parameter is true if and only if the assertion is a
3001 // *_STRCASEEQ*.  When it's true, the string "Ignoring case" will
3002 // be inserted into the message.
EqFailure(const char * lhs_expression,const char * rhs_expression,const std::string & lhs_value,const std::string & rhs_value,bool ignoring_case)3003 AssertionResult EqFailure(const char* lhs_expression,
3004                           const char* rhs_expression,
3005                           const std::string& lhs_value,
3006                           const std::string& rhs_value,
3007                           bool ignoring_case) {
3008   Message msg;
3009   msg << "Expected equality of these values:";
3010   msg << "\n  " << lhs_expression;
3011   if (lhs_value != lhs_expression) {
3012     msg << "\n    Which is: " << lhs_value;
3013   }
3014   msg << "\n  " << rhs_expression;
3015   if (rhs_value != rhs_expression) {
3016     msg << "\n    Which is: " << rhs_value;
3017   }
3018 
3019   if (ignoring_case) {
3020     msg << "\nIgnoring case";
3021   }
3022 
3023   if (!lhs_value.empty() && !rhs_value.empty()) {
3024     const std::vector<std::string> lhs_lines =
3025         SplitEscapedString(lhs_value);
3026     const std::vector<std::string> rhs_lines =
3027         SplitEscapedString(rhs_value);
3028     if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
3029       msg << "\nWith diff:\n"
3030           << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
3031     }
3032   }
3033 
3034   return AssertionFailure() << msg;
3035 }
3036 
3037 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GetBoolAssertionFailureMessage(const AssertionResult & assertion_result,const char * expression_text,const char * actual_predicate_value,const char * expected_predicate_value)3038 std::string GetBoolAssertionFailureMessage(
3039     const AssertionResult& assertion_result,
3040     const char* expression_text,
3041     const char* actual_predicate_value,
3042     const char* expected_predicate_value) {
3043   const char* actual_message = assertion_result.message();
3044   Message msg;
3045   msg << "Value of: " << expression_text
3046       << "\n  Actual: " << actual_predicate_value;
3047   if (actual_message[0] != '\0')
3048     msg << " (" << actual_message << ")";
3049   msg << "\nExpected: " << expected_predicate_value;
3050   return msg.GetString();
3051 }
3052 
3053 // Helper function for implementing ASSERT_NEAR.
DoubleNearPredFormat(const char * expr1,const char * expr2,const char * abs_error_expr,double val1,double val2,double abs_error)3054 AssertionResult DoubleNearPredFormat(const char* expr1,
3055                                      const char* expr2,
3056                                      const char* abs_error_expr,
3057                                      double val1,
3058                                      double val2,
3059                                      double abs_error) {
3060   const double diff = fabs(val1 - val2);
3061   if (diff <= abs_error) return AssertionSuccess();
3062 
3063   // Find the value which is closest to zero.
3064   const double min_abs = std::min(fabs(val1), fabs(val2));
3065   // Find the distance to the next double from that value.
3066   const double epsilon =
3067       nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
3068   // Detect the case where abs_error is so small that EXPECT_NEAR is
3069   // effectively the same as EXPECT_EQUAL, and give an informative error
3070   // message so that the situation can be more easily understood without
3071   // requiring exotic floating-point knowledge.
3072   // Don't do an epsilon check if abs_error is zero because that implies
3073   // that an equality check was actually intended.
3074   if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
3075       abs_error < epsilon) {
3076     return AssertionFailure()
3077            << "The difference between " << expr1 << " and " << expr2 << " is "
3078            << diff << ", where\n"
3079            << expr1 << " evaluates to " << val1 << ",\n"
3080            << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
3081            << abs_error_expr << " evaluates to " << abs_error
3082            << " which is smaller than the minimum distance between doubles for "
3083               "numbers of this magnitude which is "
3084            << epsilon
3085            << ", thus making this EXPECT_NEAR check equivalent to "
3086               "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
3087   }
3088   return AssertionFailure()
3089       << "The difference between " << expr1 << " and " << expr2
3090       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
3091       << expr1 << " evaluates to " << val1 << ",\n"
3092       << expr2 << " evaluates to " << val2 << ", and\n"
3093       << abs_error_expr << " evaluates to " << abs_error << ".";
3094 }
3095 
3096 
3097 // Helper template for implementing FloatLE() and DoubleLE().
3098 template <typename RawType>
FloatingPointLE(const char * expr1,const char * expr2,RawType val1,RawType val2)3099 AssertionResult FloatingPointLE(const char* expr1,
3100                                 const char* expr2,
3101                                 RawType val1,
3102                                 RawType val2) {
3103   // Returns success if val1 is less than val2,
3104   if (val1 < val2) {
3105     return AssertionSuccess();
3106   }
3107 
3108   // or if val1 is almost equal to val2.
3109   const FloatingPoint<RawType> lhs(val1), rhs(val2);
3110   if (lhs.AlmostEquals(rhs)) {
3111     return AssertionSuccess();
3112   }
3113 
3114   // Note that the above two checks will both fail if either val1 or
3115   // val2 is NaN, as the IEEE floating-point standard requires that
3116   // any predicate involving a NaN must return false.
3117 
3118   ::std::stringstream val1_ss;
3119   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
3120           << val1;
3121 
3122   ::std::stringstream val2_ss;
3123   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
3124           << val2;
3125 
3126   return AssertionFailure()
3127       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
3128       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
3129       << StringStreamToString(&val2_ss);
3130 }
3131 
3132 }  // namespace internal
3133 
3134 // Asserts that val1 is less than, or almost equal to, val2.  Fails
3135 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
FloatLE(const char * expr1,const char * expr2,float val1,float val2)3136 AssertionResult FloatLE(const char* expr1, const char* expr2,
3137                         float val1, float val2) {
3138   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
3139 }
3140 
3141 // Asserts that val1 is less than, or almost equal to, val2.  Fails
3142 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
DoubleLE(const char * expr1,const char * expr2,double val1,double val2)3143 AssertionResult DoubleLE(const char* expr1, const char* expr2,
3144                          double val1, double val2) {
3145   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
3146 }
3147 
3148 namespace internal {
3149 
3150 // The helper function for {ASSERT|EXPECT}_STREQ.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)3151 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3152                                const char* rhs_expression,
3153                                const char* lhs,
3154                                const char* rhs) {
3155   if (String::CStringEquals(lhs, rhs)) {
3156     return AssertionSuccess();
3157   }
3158 
3159   return EqFailure(lhs_expression,
3160                    rhs_expression,
3161                    PrintToString(lhs),
3162                    PrintToString(rhs),
3163                    false);
3164 }
3165 
3166 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)3167 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
3168                                    const char* rhs_expression,
3169                                    const char* lhs,
3170                                    const char* rhs) {
3171   if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
3172     return AssertionSuccess();
3173   }
3174 
3175   return EqFailure(lhs_expression,
3176                    rhs_expression,
3177                    PrintToString(lhs),
3178                    PrintToString(rhs),
3179                    true);
3180 }
3181 
3182 // The helper function for {ASSERT|EXPECT}_STRNE.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)3183 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3184                                const char* s2_expression,
3185                                const char* s1,
3186                                const char* s2) {
3187   if (!String::CStringEquals(s1, s2)) {
3188     return AssertionSuccess();
3189   } else {
3190     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3191                               << s2_expression << "), actual: \""
3192                               << s1 << "\" vs \"" << s2 << "\"";
3193   }
3194 }
3195 
3196 // The helper function for {ASSERT|EXPECT}_STRCASENE.
CmpHelperSTRCASENE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)3197 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
3198                                    const char* s2_expression,
3199                                    const char* s1,
3200                                    const char* s2) {
3201   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3202     return AssertionSuccess();
3203   } else {
3204     return AssertionFailure()
3205         << "Expected: (" << s1_expression << ") != ("
3206         << s2_expression << ") (ignoring case), actual: \""
3207         << s1 << "\" vs \"" << s2 << "\"";
3208   }
3209 }
3210 
3211 }  // namespace internal
3212 
3213 namespace {
3214 
3215 // Helper functions for implementing IsSubString() and IsNotSubstring().
3216 
3217 // This group of overloaded functions return true if and only if needle
3218 // is a substring of haystack.  NULL is considered a substring of
3219 // itself only.
3220 
IsSubstringPred(const char * needle,const char * haystack)3221 bool IsSubstringPred(const char* needle, const char* haystack) {
3222   if (needle == nullptr || haystack == nullptr) return needle == haystack;
3223 
3224   return strstr(haystack, needle) != nullptr;
3225 }
3226 
IsSubstringPred(const wchar_t * needle,const wchar_t * haystack)3227 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3228   if (needle == nullptr || haystack == nullptr) return needle == haystack;
3229 
3230   return wcsstr(haystack, needle) != nullptr;
3231 }
3232 
3233 // StringType here can be either ::std::string or ::std::wstring.
3234 template <typename StringType>
IsSubstringPred(const StringType & needle,const StringType & haystack)3235 bool IsSubstringPred(const StringType& needle,
3236                      const StringType& haystack) {
3237   return haystack.find(needle) != StringType::npos;
3238 }
3239 
3240 // This function implements either IsSubstring() or IsNotSubstring(),
3241 // depending on the value of the expected_to_be_substring parameter.
3242 // StringType here can be const char*, const wchar_t*, ::std::string,
3243 // or ::std::wstring.
3244 template <typename StringType>
IsSubstringImpl(bool expected_to_be_substring,const char * needle_expr,const char * haystack_expr,const StringType & needle,const StringType & haystack)3245 AssertionResult IsSubstringImpl(
3246     bool expected_to_be_substring,
3247     const char* needle_expr, const char* haystack_expr,
3248     const StringType& needle, const StringType& haystack) {
3249   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3250     return AssertionSuccess();
3251 
3252   const bool is_wide_string = sizeof(needle[0]) > 1;
3253   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3254   return AssertionFailure()
3255       << "Value of: " << needle_expr << "\n"
3256       << "  Actual: " << begin_string_quote << needle << "\"\n"
3257       << "Expected: " << (expected_to_be_substring ? "" : "not ")
3258       << "a substring of " << haystack_expr << "\n"
3259       << "Which is: " << begin_string_quote << haystack << "\"";
3260 }
3261 
3262 }  // namespace
3263 
3264 // IsSubstring() and IsNotSubstring() check whether needle is a
3265 // substring of haystack (NULL is considered a substring of itself
3266 // only), and return an appropriate error message when they fail.
3267 
IsSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3268 AssertionResult IsSubstring(
3269     const char* needle_expr, const char* haystack_expr,
3270     const char* needle, const char* haystack) {
3271   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3272 }
3273 
IsSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3274 AssertionResult IsSubstring(
3275     const char* needle_expr, const char* haystack_expr,
3276     const wchar_t* needle, const wchar_t* haystack) {
3277   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3278 }
3279 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3280 AssertionResult IsNotSubstring(
3281     const char* needle_expr, const char* haystack_expr,
3282     const char* needle, const char* haystack) {
3283   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3284 }
3285 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3286 AssertionResult IsNotSubstring(
3287     const char* needle_expr, const char* haystack_expr,
3288     const wchar_t* needle, const wchar_t* haystack) {
3289   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3290 }
3291 
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3292 AssertionResult IsSubstring(
3293     const char* needle_expr, const char* haystack_expr,
3294     const ::std::string& needle, const ::std::string& haystack) {
3295   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3296 }
3297 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3298 AssertionResult IsNotSubstring(
3299     const char* needle_expr, const char* haystack_expr,
3300     const ::std::string& needle, const ::std::string& haystack) {
3301   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3302 }
3303 
3304 #if GTEST_HAS_STD_WSTRING
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3305 AssertionResult IsSubstring(
3306     const char* needle_expr, const char* haystack_expr,
3307     const ::std::wstring& needle, const ::std::wstring& haystack) {
3308   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3309 }
3310 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3311 AssertionResult IsNotSubstring(
3312     const char* needle_expr, const char* haystack_expr,
3313     const ::std::wstring& needle, const ::std::wstring& haystack) {
3314   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3315 }
3316 #endif  // GTEST_HAS_STD_WSTRING
3317 
3318 namespace internal {
3319 
3320 #if GTEST_OS_WINDOWS
3321 
3322 namespace {
3323 
3324 // Helper function for IsHRESULT{SuccessFailure} predicates
HRESULTFailureHelper(const char * expr,const char * expected,long hr)3325 AssertionResult HRESULTFailureHelper(const char* expr,
3326                                      const char* expected,
3327                                      long hr) {  // NOLINT
3328 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
3329 
3330   // Windows CE doesn't support FormatMessage.
3331   const char error_text[] = "";
3332 
3333 # else
3334 
3335   // Looks up the human-readable system message for the HRESULT code
3336   // and since we're not passing any params to FormatMessage, we don't
3337   // want inserts expanded.
3338   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3339                        FORMAT_MESSAGE_IGNORE_INSERTS;
3340   const DWORD kBufSize = 4096;
3341   // Gets the system's human readable message string for this HRESULT.
3342   char error_text[kBufSize] = { '\0' };
3343   DWORD message_length = ::FormatMessageA(kFlags,
3344                                           0,   // no source, we're asking system
3345                                           static_cast<DWORD>(hr),  // the error
3346                                           0,   // no line width restrictions
3347                                           error_text,  // output buffer
3348                                           kBufSize,    // buf size
3349                                           nullptr);  // no arguments for inserts
3350   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3351   for (; message_length && IsSpace(error_text[message_length - 1]);
3352           --message_length) {
3353     error_text[message_length - 1] = '\0';
3354   }
3355 
3356 # endif  // GTEST_OS_WINDOWS_MOBILE
3357 
3358   const std::string error_hex("0x" + String::FormatHexInt(hr));
3359   return ::testing::AssertionFailure()
3360       << "Expected: " << expr << " " << expected << ".\n"
3361       << "  Actual: " << error_hex << " " << error_text << "\n";
3362 }
3363 
3364 }  // namespace
3365 
IsHRESULTSuccess(const char * expr,long hr)3366 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
3367   if (SUCCEEDED(hr)) {
3368     return AssertionSuccess();
3369   }
3370   return HRESULTFailureHelper(expr, "succeeds", hr);
3371 }
3372 
IsHRESULTFailure(const char * expr,long hr)3373 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
3374   if (FAILED(hr)) {
3375     return AssertionSuccess();
3376   }
3377   return HRESULTFailureHelper(expr, "fails", hr);
3378 }
3379 
3380 #endif  // GTEST_OS_WINDOWS
3381 
3382 // Utility functions for encoding Unicode text (wide strings) in
3383 // UTF-8.
3384 
3385 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
3386 // like this:
3387 //
3388 // Code-point length   Encoding
3389 //   0 -  7 bits       0xxxxxxx
3390 //   8 - 11 bits       110xxxxx 10xxxxxx
3391 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
3392 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3393 
3394 // The maximum code-point a one-byte UTF-8 sequence can represent.
3395 constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) <<  7) - 1;
3396 
3397 // The maximum code-point a two-byte UTF-8 sequence can represent.
3398 constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
3399 
3400 // The maximum code-point a three-byte UTF-8 sequence can represent.
3401 constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1;
3402 
3403 // The maximum code-point a four-byte UTF-8 sequence can represent.
3404 constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1;
3405 
3406 // Chops off the n lowest bits from a bit pattern.  Returns the n
3407 // lowest bits.  As a side effect, the original bit pattern will be
3408 // shifted to the right by n bits.
ChopLowBits(uint32_t * bits,int n)3409 inline uint32_t ChopLowBits(uint32_t* bits, int n) {
3410   const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
3411   *bits >>= n;
3412   return low_bits;
3413 }
3414 
3415 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
3416 // code_point parameter is of type uint32_t because wchar_t may not be
3417 // wide enough to contain a code point.
3418 // If the code_point is not a valid Unicode code point
3419 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3420 // to "(Invalid Unicode 0xXXXXXXXX)".
CodePointToUtf8(uint32_t code_point)3421 std::string CodePointToUtf8(uint32_t code_point) {
3422   if (code_point > kMaxCodePoint4) {
3423     return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
3424   }
3425 
3426   char str[5];  // Big enough for the largest valid code point.
3427   if (code_point <= kMaxCodePoint1) {
3428     str[1] = '\0';
3429     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
3430   } else if (code_point <= kMaxCodePoint2) {
3431     str[2] = '\0';
3432     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3433     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
3434   } else if (code_point <= kMaxCodePoint3) {
3435     str[3] = '\0';
3436     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3437     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3438     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
3439   } else {  // code_point <= kMaxCodePoint4
3440     str[4] = '\0';
3441     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3442     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3443     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3444     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
3445   }
3446   return str;
3447 }
3448 
3449 // The following two functions only make sense if the system
3450 // uses UTF-16 for wide string encoding. All supported systems
3451 // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
3452 
3453 // Determines if the arguments constitute UTF-16 surrogate pair
3454 // and thus should be combined into a single Unicode code point
3455 // using CreateCodePointFromUtf16SurrogatePair.
IsUtf16SurrogatePair(wchar_t first,wchar_t second)3456 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3457   return sizeof(wchar_t) == 2 &&
3458       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3459 }
3460 
3461 // Creates a Unicode code point from UTF16 surrogate pair.
CreateCodePointFromUtf16SurrogatePair(wchar_t first,wchar_t second)3462 inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3463                                                       wchar_t second) {
3464   const auto first_u = static_cast<uint32_t>(first);
3465   const auto second_u = static_cast<uint32_t>(second);
3466   const uint32_t mask = (1 << 10) - 1;
3467   return (sizeof(wchar_t) == 2)
3468              ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
3469              :
3470              // This function should not be called when the condition is
3471              // false, but we provide a sensible default in case it is.
3472              first_u;
3473 }
3474 
3475 // Converts a wide string to a narrow string in UTF-8 encoding.
3476 // The wide string is assumed to have the following encoding:
3477 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
3478 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3479 // Parameter str points to a null-terminated wide string.
3480 // Parameter num_chars may additionally limit the number
3481 // of wchar_t characters processed. -1 is used when the entire string
3482 // should be processed.
3483 // If the string contains code points that are not valid Unicode code points
3484 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3485 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3486 // and contains invalid UTF-16 surrogate pairs, values in those pairs
3487 // will be encoded as individual Unicode characters from Basic Normal Plane.
WideStringToUtf8(const wchar_t * str,int num_chars)3488 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3489   if (num_chars == -1)
3490     num_chars = static_cast<int>(wcslen(str));
3491 
3492   ::std::stringstream stream;
3493   for (int i = 0; i < num_chars; ++i) {
3494     uint32_t unicode_code_point;
3495 
3496     if (str[i] == L'\0') {
3497       break;
3498     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3499       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3500                                                                  str[i + 1]);
3501       i++;
3502     } else {
3503       unicode_code_point = static_cast<uint32_t>(str[i]);
3504     }
3505 
3506     stream << CodePointToUtf8(unicode_code_point);
3507   }
3508   return StringStreamToString(&stream);
3509 }
3510 
3511 // Converts a wide C string to an std::string using the UTF-8 encoding.
3512 // NULL will be converted to "(null)".
ShowWideCString(const wchar_t * wide_c_str)3513 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3514   if (wide_c_str == nullptr) return "(null)";
3515 
3516   return internal::WideStringToUtf8(wide_c_str, -1);
3517 }
3518 
3519 // Compares two wide C strings.  Returns true if and only if they have the
3520 // same content.
3521 //
3522 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
3523 // C string is considered different to any non-NULL C string,
3524 // including the empty string.
WideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3525 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3526   if (lhs == nullptr) return rhs == nullptr;
3527 
3528   if (rhs == nullptr) return false;
3529 
3530   return wcscmp(lhs, rhs) == 0;
3531 }
3532 
3533 // Helper function for *_STREQ on wide strings.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const wchar_t * lhs,const wchar_t * rhs)3534 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3535                                const char* rhs_expression,
3536                                const wchar_t* lhs,
3537                                const wchar_t* rhs) {
3538   if (String::WideCStringEquals(lhs, rhs)) {
3539     return AssertionSuccess();
3540   }
3541 
3542   return EqFailure(lhs_expression,
3543                    rhs_expression,
3544                    PrintToString(lhs),
3545                    PrintToString(rhs),
3546                    false);
3547 }
3548 
3549 // Helper function for *_STRNE on wide strings.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const wchar_t * s1,const wchar_t * s2)3550 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3551                                const char* s2_expression,
3552                                const wchar_t* s1,
3553                                const wchar_t* s2) {
3554   if (!String::WideCStringEquals(s1, s2)) {
3555     return AssertionSuccess();
3556   }
3557 
3558   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3559                             << s2_expression << "), actual: "
3560                             << PrintToString(s1)
3561                             << " vs " << PrintToString(s2);
3562 }
3563 
3564 // Compares two C strings, ignoring case.  Returns true if and only if they have
3565 // the same content.
3566 //
3567 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
3568 // NULL C string is considered different to any non-NULL C string,
3569 // including the empty string.
CaseInsensitiveCStringEquals(const char * lhs,const char * rhs)3570 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3571   if (lhs == nullptr) return rhs == nullptr;
3572   if (rhs == nullptr) return false;
3573   return posix::StrCaseCmp(lhs, rhs) == 0;
3574 }
3575 
3576 // Compares two wide C strings, ignoring case.  Returns true if and only if they
3577 // have the same content.
3578 //
3579 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3580 // A NULL C string is considered different to any non-NULL wide C string,
3581 // including the empty string.
3582 // NB: The implementations on different platforms slightly differ.
3583 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3584 // environment variable. On GNU platform this method uses wcscasecmp
3585 // which compares according to LC_CTYPE category of the current locale.
3586 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3587 // current locale.
CaseInsensitiveWideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3588 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3589                                               const wchar_t* rhs) {
3590   if (lhs == nullptr) return rhs == nullptr;
3591 
3592   if (rhs == nullptr) return false;
3593 
3594 #if GTEST_OS_WINDOWS
3595   return _wcsicmp(lhs, rhs) == 0;
3596 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3597   return wcscasecmp(lhs, rhs) == 0;
3598 #else
3599   // Android, Mac OS X and Cygwin don't define wcscasecmp.
3600   // Other unknown OSes may not define it either.
3601   wint_t left, right;
3602   do {
3603     left = towlower(static_cast<wint_t>(*lhs++));
3604     right = towlower(static_cast<wint_t>(*rhs++));
3605   } while (left && left == right);
3606   return left == right;
3607 #endif  // OS selector
3608 }
3609 
3610 // Returns true if and only if str ends with the given suffix, ignoring case.
3611 // Any string is considered to end with an empty suffix.
EndsWithCaseInsensitive(const std::string & str,const std::string & suffix)3612 bool String::EndsWithCaseInsensitive(
3613     const std::string& str, const std::string& suffix) {
3614   const size_t str_len = str.length();
3615   const size_t suffix_len = suffix.length();
3616   return (str_len >= suffix_len) &&
3617          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3618                                       suffix.c_str());
3619 }
3620 
3621 // Formats an int value as "%02d".
FormatIntWidth2(int value)3622 std::string String::FormatIntWidth2(int value) {
3623   return FormatIntWidthN(value, 2);
3624 }
3625 
3626 // Formats an int value to given width with leading zeros.
FormatIntWidthN(int value,int width)3627 std::string String::FormatIntWidthN(int value, int width) {
3628   std::stringstream ss;
3629   ss << std::setfill('0') << std::setw(width) << value;
3630   return ss.str();
3631 }
3632 
3633 // Formats an int value as "%X".
FormatHexUInt32(uint32_t value)3634 std::string String::FormatHexUInt32(uint32_t value) {
3635   std::stringstream ss;
3636   ss << std::hex << std::uppercase << value;
3637   return ss.str();
3638 }
3639 
3640 // Formats an int value as "%X".
FormatHexInt(int value)3641 std::string String::FormatHexInt(int value) {
3642   return FormatHexUInt32(static_cast<uint32_t>(value));
3643 }
3644 
3645 // Formats a byte as "%02X".
FormatByte(unsigned char value)3646 std::string String::FormatByte(unsigned char value) {
3647   std::stringstream ss;
3648   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3649      << static_cast<unsigned int>(value);
3650   return ss.str();
3651 }
3652 
3653 // Converts the buffer in a stringstream to an std::string, converting NUL
3654 // bytes to "\\0" along the way.
StringStreamToString(::std::stringstream * ss)3655 std::string StringStreamToString(::std::stringstream* ss) {
3656   const ::std::string& str = ss->str();
3657   const char* const start = str.c_str();
3658   const char* const end = start + str.length();
3659 
3660   std::string result;
3661   result.reserve(static_cast<size_t>(2 * (end - start)));
3662   for (const char* ch = start; ch != end; ++ch) {
3663     if (*ch == '\0') {
3664       result += "\\0";  // Replaces NUL with "\\0";
3665     } else {
3666       result += *ch;
3667     }
3668   }
3669 
3670   return result;
3671 }
3672 
3673 // Appends the user-supplied message to the Google-Test-generated message.
AppendUserMessage(const std::string & gtest_msg,const Message & user_msg)3674 std::string AppendUserMessage(const std::string& gtest_msg,
3675                               const Message& user_msg) {
3676   // Appends the user message if it's non-empty.
3677   const std::string user_msg_string = user_msg.GetString();
3678   if (user_msg_string.empty()) {
3679     return gtest_msg;
3680   }
3681   if (gtest_msg.empty()) {
3682     return user_msg_string;
3683   }
3684   return gtest_msg + "\n" + user_msg_string;
3685 }
3686 
3687 }  // namespace internal
3688 
3689 // class TestResult
3690 
3691 // Creates an empty TestResult.
TestResult()3692 TestResult::TestResult()
3693     : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
3694 
3695 // D'tor.
~TestResult()3696 TestResult::~TestResult() {
3697 }
3698 
3699 // Returns the i-th test part result among all the results. i can
3700 // range from 0 to total_part_count() - 1. If i is not in that range,
3701 // aborts the program.
GetTestPartResult(int i) const3702 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3703   if (i < 0 || i >= total_part_count())
3704     internal::posix::Abort();
3705   return test_part_results_.at(static_cast<size_t>(i));
3706 }
3707 
3708 // Returns the i-th test property. i can range from 0 to
3709 // test_property_count() - 1. If i is not in that range, aborts the
3710 // program.
GetTestProperty(int i) const3711 const TestProperty& TestResult::GetTestProperty(int i) const {
3712   if (i < 0 || i >= test_property_count())
3713     internal::posix::Abort();
3714   return test_properties_.at(static_cast<size_t>(i));
3715 }
3716 
3717 // Clears the test part results.
ClearTestPartResults()3718 void TestResult::ClearTestPartResults() {
3719   test_part_results_.clear();
3720 }
3721 
3722 // Adds a test part result to the list.
AddTestPartResult(const TestPartResult & test_part_result)3723 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3724   test_part_results_.push_back(test_part_result);
3725 }
3726 
3727 // Adds a test property to the list. If a property with the same key as the
3728 // supplied property is already represented, the value of this test_property
3729 // replaces the old value for that key.
RecordProperty(const std::string & xml_element,const TestProperty & test_property)3730 void TestResult::RecordProperty(const std::string& xml_element,
3731                                 const TestProperty& test_property) {
3732   if (!ValidateTestProperty(xml_element, test_property)) {
3733     return;
3734   }
3735   internal::MutexLock lock(&test_properties_mutex_);
3736   const std::vector<TestProperty>::iterator property_with_matching_key =
3737       std::find_if(test_properties_.begin(), test_properties_.end(),
3738                    internal::TestPropertyKeyIs(test_property.key()));
3739   if (property_with_matching_key == test_properties_.end()) {
3740     test_properties_.push_back(test_property);
3741     return;
3742   }
3743   property_with_matching_key->SetValue(test_property.value());
3744 }
3745 
3746 // The list of reserved attributes used in the <testsuites> element of XML
3747 // output.
3748 static const char* const kReservedTestSuitesAttributes[] = {
3749   "disabled",
3750   "errors",
3751   "failures",
3752   "name",
3753   "random_seed",
3754   "tests",
3755   "time",
3756   "timestamp"
3757 };
3758 
3759 // The list of reserved attributes used in the <testsuite> element of XML
3760 // output.
3761 static const char* const kReservedTestSuiteAttributes[] = {
3762     "disabled", "errors", "failures",  "name",
3763     "tests",    "time",   "timestamp", "skipped"};
3764 
3765 // The list of reserved attributes used in the <testcase> element of XML output.
3766 static const char* const kReservedTestCaseAttributes[] = {
3767     "classname",   "name", "status", "time",  "type_param",
3768     "value_param", "file", "line"};
3769 
3770 // Use a slightly different set for allowed output to ensure existing tests can
3771 // still RecordProperty("result") or "RecordProperty(timestamp")
3772 static const char* const kReservedOutputTestCaseAttributes[] = {
3773     "classname",   "name", "status", "time",   "type_param",
3774     "value_param", "file", "line",   "result", "timestamp"};
3775 
3776 template <size_t kSize>
ArrayAsVector(const char * const (& array)[kSize])3777 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3778   return std::vector<std::string>(array, array + kSize);
3779 }
3780 
GetReservedAttributesForElement(const std::string & xml_element)3781 static std::vector<std::string> GetReservedAttributesForElement(
3782     const std::string& xml_element) {
3783   if (xml_element == "testsuites") {
3784     return ArrayAsVector(kReservedTestSuitesAttributes);
3785   } else if (xml_element == "testsuite") {
3786     return ArrayAsVector(kReservedTestSuiteAttributes);
3787   } else if (xml_element == "testcase") {
3788     return ArrayAsVector(kReservedTestCaseAttributes);
3789   } else {
3790     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3791   }
3792   // This code is unreachable but some compilers may not realizes that.
3793   return std::vector<std::string>();
3794 }
3795 
3796 // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
GetReservedOutputAttributesForElement(const std::string & xml_element)3797 static std::vector<std::string> GetReservedOutputAttributesForElement(
3798     const std::string& xml_element) {
3799   if (xml_element == "testsuites") {
3800     return ArrayAsVector(kReservedTestSuitesAttributes);
3801   } else if (xml_element == "testsuite") {
3802     return ArrayAsVector(kReservedTestSuiteAttributes);
3803   } else if (xml_element == "testcase") {
3804     return ArrayAsVector(kReservedOutputTestCaseAttributes);
3805   } else {
3806     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3807   }
3808   // This code is unreachable but some compilers may not realizes that.
3809   return std::vector<std::string>();
3810 }
3811 
FormatWordList(const std::vector<std::string> & words)3812 static std::string FormatWordList(const std::vector<std::string>& words) {
3813   Message word_list;
3814   for (size_t i = 0; i < words.size(); ++i) {
3815     if (i > 0 && words.size() > 2) {
3816       word_list << ", ";
3817     }
3818     if (i == words.size() - 1) {
3819       word_list << "and ";
3820     }
3821     word_list << "'" << words[i] << "'";
3822   }
3823   return word_list.GetString();
3824 }
3825 
ValidateTestPropertyName(const std::string & property_name,const std::vector<std::string> & reserved_names)3826 static bool ValidateTestPropertyName(
3827     const std::string& property_name,
3828     const std::vector<std::string>& reserved_names) {
3829   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3830           reserved_names.end()) {
3831     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3832                   << " (" << FormatWordList(reserved_names)
3833                   << " are reserved by " << GTEST_NAME_ << ")";
3834     return false;
3835   }
3836   return true;
3837 }
3838 
3839 // Adds a failure if the key is a reserved attribute of the element named
3840 // xml_element.  Returns true if the property is valid.
ValidateTestProperty(const std::string & xml_element,const TestProperty & test_property)3841 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3842                                       const TestProperty& test_property) {
3843   return ValidateTestPropertyName(test_property.key(),
3844                                   GetReservedAttributesForElement(xml_element));
3845 }
3846 
3847 // Clears the object.
Clear()3848 void TestResult::Clear() {
3849   test_part_results_.clear();
3850   test_properties_.clear();
3851   death_test_count_ = 0;
3852   elapsed_time_ = 0;
3853 }
3854 
3855 // Returns true off the test part was skipped.
TestPartSkipped(const TestPartResult & result)3856 static bool TestPartSkipped(const TestPartResult& result) {
3857   return result.skipped();
3858 }
3859 
3860 // Returns true if and only if the test was skipped.
Skipped() const3861 bool TestResult::Skipped() const {
3862   return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
3863 }
3864 
3865 // Returns true if and only if the test failed.
Failed() const3866 bool TestResult::Failed() const {
3867   for (int i = 0; i < total_part_count(); ++i) {
3868     if (GetTestPartResult(i).failed())
3869       return true;
3870   }
3871   return false;
3872 }
3873 
3874 // Returns true if and only if the test part fatally failed.
TestPartFatallyFailed(const TestPartResult & result)3875 static bool TestPartFatallyFailed(const TestPartResult& result) {
3876   return result.fatally_failed();
3877 }
3878 
3879 // Returns true if and only if the test fatally failed.
HasFatalFailure() const3880 bool TestResult::HasFatalFailure() const {
3881   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3882 }
3883 
3884 // Returns true if and only if the test part non-fatally failed.
TestPartNonfatallyFailed(const TestPartResult & result)3885 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3886   return result.nonfatally_failed();
3887 }
3888 
3889 // Returns true if and only if the test has a non-fatal failure.
HasNonfatalFailure() const3890 bool TestResult::HasNonfatalFailure() const {
3891   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3892 }
3893 
3894 // Gets the number of all test parts.  This is the sum of the number
3895 // of successful test parts and the number of failed test parts.
total_part_count() const3896 int TestResult::total_part_count() const {
3897   return static_cast<int>(test_part_results_.size());
3898 }
3899 
3900 // Returns the number of the test properties.
test_property_count() const3901 int TestResult::test_property_count() const {
3902   return static_cast<int>(test_properties_.size());
3903 }
3904 
3905 // class Test
3906 
3907 // Creates a Test object.
3908 
3909 // The c'tor saves the states of all flags.
Test()3910 Test::Test()
3911     : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3912 }
3913 
3914 // The d'tor restores the states of all flags.  The actual work is
3915 // done by the d'tor of the gtest_flag_saver_ field, and thus not
3916 // visible here.
~Test()3917 Test::~Test() {
3918 }
3919 
3920 // Sets up the test fixture.
3921 //
3922 // A sub-class may override this.
SetUp()3923 void Test::SetUp() {
3924 }
3925 
3926 // Tears down the test fixture.
3927 //
3928 // A sub-class may override this.
TearDown()3929 void Test::TearDown() {
3930 }
3931 
3932 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,const std::string & value)3933 void Test::RecordProperty(const std::string& key, const std::string& value) {
3934   UnitTest::GetInstance()->RecordProperty(key, value);
3935 }
3936 
3937 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,int value)3938 void Test::RecordProperty(const std::string& key, int value) {
3939   Message value_message;
3940   value_message << value;
3941   RecordProperty(key, value_message.GetString().c_str());
3942 }
3943 
3944 namespace internal {
3945 
ReportFailureInUnknownLocation(TestPartResult::Type result_type,const std::string & message)3946 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3947                                     const std::string& message) {
3948   // This function is a friend of UnitTest and as such has access to
3949   // AddTestPartResult.
3950   UnitTest::GetInstance()->AddTestPartResult(
3951       result_type,
3952       nullptr,  // No info about the source file where the exception occurred.
3953       -1,       // We have no info on which line caused the exception.
3954       message,
3955       "");  // No stack trace, either.
3956 }
3957 
3958 }  // namespace internal
3959 
3960 // Google Test requires all tests in the same test suite to use the same test
3961 // fixture class.  This function checks if the current test has the
3962 // same fixture class as the first test in the current test suite.  If
3963 // yes, it returns true; otherwise it generates a Google Test failure and
3964 // returns false.
HasSameFixtureClass()3965 bool Test::HasSameFixtureClass() {
3966   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3967   const TestSuite* const test_suite = impl->current_test_suite();
3968 
3969   // Info about the first test in the current test suite.
3970   const TestInfo* const first_test_info = test_suite->test_info_list()[0];
3971   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3972   const char* const first_test_name = first_test_info->name();
3973 
3974   // Info about the current test.
3975   const TestInfo* const this_test_info = impl->current_test_info();
3976   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3977   const char* const this_test_name = this_test_info->name();
3978 
3979   if (this_fixture_id != first_fixture_id) {
3980     // Is the first test defined using TEST?
3981     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3982     // Is this test defined using TEST?
3983     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3984 
3985     if (first_is_TEST || this_is_TEST) {
3986       // Both TEST and TEST_F appear in same test suite, which is incorrect.
3987       // Tell the user how to fix this.
3988 
3989       // Gets the name of the TEST and the name of the TEST_F.  Note
3990       // that first_is_TEST and this_is_TEST cannot both be true, as
3991       // the fixture IDs are different for the two tests.
3992       const char* const TEST_name =
3993           first_is_TEST ? first_test_name : this_test_name;
3994       const char* const TEST_F_name =
3995           first_is_TEST ? this_test_name : first_test_name;
3996 
3997       ADD_FAILURE()
3998           << "All tests in the same test suite must use the same test fixture\n"
3999           << "class, so mixing TEST_F and TEST in the same test suite is\n"
4000           << "illegal.  In test suite " << this_test_info->test_suite_name()
4001           << ",\n"
4002           << "test " << TEST_F_name << " is defined using TEST_F but\n"
4003           << "test " << TEST_name << " is defined using TEST.  You probably\n"
4004           << "want to change the TEST to TEST_F or move it to another test\n"
4005           << "case.";
4006     } else {
4007       // Two fixture classes with the same name appear in two different
4008       // namespaces, which is not allowed. Tell the user how to fix this.
4009       ADD_FAILURE()
4010           << "All tests in the same test suite must use the same test fixture\n"
4011           << "class.  However, in test suite "
4012           << this_test_info->test_suite_name() << ",\n"
4013           << "you defined test " << first_test_name << " and test "
4014           << this_test_name << "\n"
4015           << "using two different test fixture classes.  This can happen if\n"
4016           << "the two classes are from different namespaces or translation\n"
4017           << "units and have the same name.  You should probably rename one\n"
4018           << "of the classes to put the tests into different test suites.";
4019     }
4020     return false;
4021   }
4022 
4023   return true;
4024 }
4025 
4026 #if GTEST_HAS_SEH
4027 
4028 // Adds an "exception thrown" fatal failure to the current test.  This
4029 // function returns its result via an output parameter pointer because VC++
4030 // prohibits creation of objects with destructors on stack in functions
4031 // using __try (see error C2712).
FormatSehExceptionMessage(DWORD exception_code,const char * location)4032 static std::string* FormatSehExceptionMessage(DWORD exception_code,
4033                                               const char* location) {
4034   Message message;
4035   message << "SEH exception with code 0x" << std::setbase(16) <<
4036     exception_code << std::setbase(10) << " thrown in " << location << ".";
4037 
4038   return new std::string(message.GetString());
4039 }
4040 
4041 #endif  // GTEST_HAS_SEH
4042 
4043 namespace internal {
4044 
4045 #if GTEST_HAS_EXCEPTIONS
4046 
4047 // Adds an "exception thrown" fatal failure to the current test.
FormatCxxExceptionMessage(const char * description,const char * location)4048 static std::string FormatCxxExceptionMessage(const char* description,
4049                                              const char* location) {
4050   Message message;
4051   if (description != nullptr) {
4052     message << "C++ exception with description \"" << description << "\"";
4053   } else {
4054     message << "Unknown C++ exception";
4055   }
4056   message << " thrown in " << location << ".";
4057 
4058   return message.GetString();
4059 }
4060 
4061 static std::string PrintTestPartResultToString(
4062     const TestPartResult& test_part_result);
4063 
GoogleTestFailureException(const TestPartResult & failure)4064 GoogleTestFailureException::GoogleTestFailureException(
4065     const TestPartResult& failure)
4066     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
4067 
4068 #endif  // GTEST_HAS_EXCEPTIONS
4069 
4070 // We put these helper functions in the internal namespace as IBM's xlC
4071 // compiler rejects the code if they were declared static.
4072 
4073 // Runs the given method and handles SEH exceptions it throws, when
4074 // SEH is supported; returns the 0-value for type Result in case of an
4075 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
4076 // exceptions in the same function.  Therefore, we provide a separate
4077 // wrapper function for handling SEH exceptions.)
4078 template <class T, typename Result>
HandleSehExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)4079 Result HandleSehExceptionsInMethodIfSupported(
4080     T* object, Result (T::*method)(), const char* location) {
4081 #if GTEST_HAS_SEH
4082   __try {
4083     return (object->*method)();
4084   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
4085       GetExceptionCode())) {
4086     // We create the exception message on the heap because VC++ prohibits
4087     // creation of objects with destructors on stack in functions using __try
4088     // (see error C2712).
4089     std::string* exception_message = FormatSehExceptionMessage(
4090         GetExceptionCode(), location);
4091     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
4092                                              *exception_message);
4093     delete exception_message;
4094     return static_cast<Result>(0);
4095   }
4096 #else
4097   (void)location;
4098   return (object->*method)();
4099 #endif  // GTEST_HAS_SEH
4100 }
4101 
4102 // Runs the given method and catches and reports C++ and/or SEH-style
4103 // exceptions, if they are supported; returns the 0-value for type
4104 // Result in case of an SEH exception.
4105 template <class T, typename Result>
HandleExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)4106 Result HandleExceptionsInMethodIfSupported(
4107     T* object, Result (T::*method)(), const char* location) {
4108   // NOTE: The user code can affect the way in which Google Test handles
4109   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
4110   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
4111   // after the exception is caught and either report or re-throw the
4112   // exception based on the flag's value:
4113   //
4114   // try {
4115   //   // Perform the test method.
4116   // } catch (...) {
4117   //   if (GTEST_FLAG(catch_exceptions))
4118   //     // Report the exception as failure.
4119   //   else
4120   //     throw;  // Re-throws the original exception.
4121   // }
4122   //
4123   // However, the purpose of this flag is to allow the program to drop into
4124   // the debugger when the exception is thrown. On most platforms, once the
4125   // control enters the catch block, the exception origin information is
4126   // lost and the debugger will stop the program at the point of the
4127   // re-throw in this function -- instead of at the point of the original
4128   // throw statement in the code under test.  For this reason, we perform
4129   // the check early, sacrificing the ability to affect Google Test's
4130   // exception handling in the method where the exception is thrown.
4131   if (internal::GetUnitTestImpl()->catch_exceptions()) {
4132 #if GTEST_HAS_EXCEPTIONS
4133     try {
4134       return HandleSehExceptionsInMethodIfSupported(object, method, location);
4135     } catch (const AssertionException&) {  // NOLINT
4136       // This failure was reported already.
4137     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
4138       // This exception type can only be thrown by a failed Google
4139       // Test assertion with the intention of letting another testing
4140       // framework catch it.  Therefore we just re-throw it.
4141       throw;
4142     } catch (const std::exception& e) {  // NOLINT
4143       internal::ReportFailureInUnknownLocation(
4144           TestPartResult::kFatalFailure,
4145           FormatCxxExceptionMessage(e.what(), location));
4146     } catch (...) {  // NOLINT
4147       internal::ReportFailureInUnknownLocation(
4148           TestPartResult::kFatalFailure,
4149           FormatCxxExceptionMessage(nullptr, location));
4150     }
4151     return static_cast<Result>(0);
4152 #else
4153     return HandleSehExceptionsInMethodIfSupported(object, method, location);
4154 #endif  // GTEST_HAS_EXCEPTIONS
4155   } else {
4156     return (object->*method)();
4157   }
4158 }
4159 
4160 }  // namespace internal
4161 
4162 // Runs the test and updates the test result.
Run()4163 void Test::Run() {
4164   if (!HasSameFixtureClass()) return;
4165 
4166   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4167   impl->os_stack_trace_getter()->UponLeavingGTest();
4168   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
4169   // We will run the test only if SetUp() was successful and didn't call
4170   // GTEST_SKIP().
4171   if (!HasFatalFailure() && !IsSkipped()) {
4172     impl->os_stack_trace_getter()->UponLeavingGTest();
4173     internal::HandleExceptionsInMethodIfSupported(
4174         this, &Test::TestBody, "the test body");
4175   }
4176 
4177   // However, we want to clean up as much as possible.  Hence we will
4178   // always call TearDown(), even if SetUp() or the test body has
4179   // failed.
4180   impl->os_stack_trace_getter()->UponLeavingGTest();
4181   internal::HandleExceptionsInMethodIfSupported(
4182       this, &Test::TearDown, "TearDown()");
4183 }
4184 
4185 // Returns true if and only if the current test has a fatal failure.
HasFatalFailure()4186 bool Test::HasFatalFailure() {
4187   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
4188 }
4189 
4190 // Returns true if and only if the current test has a non-fatal failure.
HasNonfatalFailure()4191 bool Test::HasNonfatalFailure() {
4192   return internal::GetUnitTestImpl()->current_test_result()->
4193       HasNonfatalFailure();
4194 }
4195 
4196 // Returns true if and only if the current test was skipped.
IsSkipped()4197 bool Test::IsSkipped() {
4198   return internal::GetUnitTestImpl()->current_test_result()->Skipped();
4199 }
4200 
4201 // class TestInfo
4202 
4203 // Constructs a TestInfo object. It assumes ownership of the test factory
4204 // object.
TestInfo(const std::string & a_test_suite_name,const std::string & a_name,const char * a_type_param,const char * a_value_param,internal::CodeLocation a_code_location,internal::TypeId fixture_class_id,internal::TestFactoryBase * factory)4205 TestInfo::TestInfo(const std::string& a_test_suite_name,
4206                    const std::string& a_name, const char* a_type_param,
4207                    const char* a_value_param,
4208                    internal::CodeLocation a_code_location,
4209                    internal::TypeId fixture_class_id,
4210                    internal::TestFactoryBase* factory)
4211     : test_suite_name_(a_test_suite_name),
4212       name_(a_name),
4213       type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4214       value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
4215       location_(a_code_location),
4216       fixture_class_id_(fixture_class_id),
4217       should_run_(false),
4218       is_disabled_(false),
4219       matches_filter_(false),
4220       is_in_another_shard_(false),
4221       factory_(factory),
4222       result_() {}
4223 
4224 // Destructs a TestInfo object.
~TestInfo()4225 TestInfo::~TestInfo() { delete factory_; }
4226 
4227 namespace internal {
4228 
4229 // Creates a new TestInfo object and registers it with Google Test;
4230 // returns the created object.
4231 //
4232 // Arguments:
4233 //
4234 //   test_suite_name:  name of the test suite
4235 //   name:             name of the test
4236 //   type_param:       the name of the test's type parameter, or NULL if
4237 //                     this is not a typed or a type-parameterized test.
4238 //   value_param:      text representation of the test's value parameter,
4239 //                     or NULL if this is not a value-parameterized test.
4240 //   code_location:    code location where the test is defined
4241 //   fixture_class_id: ID of the test fixture class
4242 //   set_up_tc:        pointer to the function that sets up the test suite
4243 //   tear_down_tc:     pointer to the function that tears down the test suite
4244 //   factory:          pointer to the factory that creates a test object.
4245 //                     The newly created TestInfo instance will assume
4246 //                     ownership of the factory object.
MakeAndRegisterTestInfo(const char * test_suite_name,const char * name,const char * type_param,const char * value_param,CodeLocation code_location,TypeId fixture_class_id,SetUpTestSuiteFunc set_up_tc,TearDownTestSuiteFunc tear_down_tc,TestFactoryBase * factory)4247 TestInfo* MakeAndRegisterTestInfo(
4248     const char* test_suite_name, const char* name, const char* type_param,
4249     const char* value_param, CodeLocation code_location,
4250     TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
4251     TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
4252   TestInfo* const test_info =
4253       new TestInfo(test_suite_name, name, type_param, value_param,
4254                    code_location, fixture_class_id, factory);
4255   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4256   return test_info;
4257 }
4258 
ReportInvalidTestSuiteType(const char * test_suite_name,CodeLocation code_location)4259 void ReportInvalidTestSuiteType(const char* test_suite_name,
4260                                 CodeLocation code_location) {
4261   Message errors;
4262   errors
4263       << "Attempted redefinition of test suite " << test_suite_name << ".\n"
4264       << "All tests in the same test suite must use the same test fixture\n"
4265       << "class.  However, in test suite " << test_suite_name << ", you tried\n"
4266       << "to define a test using a fixture class different from the one\n"
4267       << "used earlier. This can happen if the two fixture classes are\n"
4268       << "from different namespaces and have the same name. You should\n"
4269       << "probably rename one of the classes to put the tests into different\n"
4270       << "test suites.";
4271 
4272   GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
4273                                           code_location.line)
4274                     << " " << errors.GetString();
4275 }
4276 }  // namespace internal
4277 
4278 namespace {
4279 
4280 // A predicate that checks the test name of a TestInfo against a known
4281 // value.
4282 //
4283 // This is used for implementation of the TestSuite class only.  We put
4284 // it in the anonymous namespace to prevent polluting the outer
4285 // namespace.
4286 //
4287 // TestNameIs is copyable.
4288 class TestNameIs {
4289  public:
4290   // Constructor.
4291   //
4292   // TestNameIs has NO default constructor.
TestNameIs(const char * name)4293   explicit TestNameIs(const char* name)
4294       : name_(name) {}
4295 
4296   // Returns true if and only if the test name of test_info matches name_.
operator ()(const TestInfo * test_info) const4297   bool operator()(const TestInfo * test_info) const {
4298     return test_info && test_info->name() == name_;
4299   }
4300 
4301  private:
4302   std::string name_;
4303 };
4304 
4305 }  // namespace
4306 
4307 namespace internal {
4308 
4309 // This method expands all parameterized tests registered with macros TEST_P
4310 // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
4311 // This will be done just once during the program runtime.
RegisterParameterizedTests()4312 void UnitTestImpl::RegisterParameterizedTests() {
4313   if (!parameterized_tests_registered_) {
4314     parameterized_test_registry_.RegisterTests();
4315     type_parameterized_test_registry_.CheckForInstantiations();
4316     parameterized_tests_registered_ = true;
4317   }
4318 }
4319 
4320 }  // namespace internal
4321 
4322 // Creates the test object, runs it, records its result, and then
4323 // deletes it.
Run()4324 void TestInfo::Run() {
4325   if (!should_run_) return;
4326 
4327   // Tells UnitTest where to store test result.
4328   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4329   impl->set_current_test_info(this);
4330 
4331   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4332 
4333   // Notifies the unit test event listeners that a test is about to start.
4334   repeater->OnTestStart(*this);
4335 
4336   result_.set_start_timestamp(internal::GetTimeInMillis());
4337   internal::Timer timer;
4338 
4339   impl->os_stack_trace_getter()->UponLeavingGTest();
4340 
4341   // Creates the test object.
4342   Test* const test = internal::HandleExceptionsInMethodIfSupported(
4343       factory_, &internal::TestFactoryBase::CreateTest,
4344       "the test fixture's constructor");
4345 
4346   // Runs the test if the constructor didn't generate a fatal failure or invoke
4347   // GTEST_SKIP().
4348   // Note that the object will not be null
4349   if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
4350     // This doesn't throw as all user code that can throw are wrapped into
4351     // exception handling code.
4352     test->Run();
4353   }
4354 
4355   if (test != nullptr) {
4356     // Deletes the test object.
4357     impl->os_stack_trace_getter()->UponLeavingGTest();
4358     internal::HandleExceptionsInMethodIfSupported(
4359         test, &Test::DeleteSelf_, "the test fixture's destructor");
4360   }
4361 
4362   result_.set_elapsed_time(timer.Elapsed());
4363 
4364   // Notifies the unit test event listener that a test has just finished.
4365   repeater->OnTestEnd(*this);
4366 
4367   // Tells UnitTest to stop associating assertion results to this
4368   // test.
4369   impl->set_current_test_info(nullptr);
4370 }
4371 
4372 // Skip and records a skipped test result for this object.
Skip()4373 void TestInfo::Skip() {
4374   if (!should_run_) return;
4375 
4376   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4377   impl->set_current_test_info(this);
4378 
4379   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4380 
4381   // Notifies the unit test event listeners that a test is about to start.
4382   repeater->OnTestStart(*this);
4383 
4384   const TestPartResult test_part_result =
4385       TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
4386   impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
4387       test_part_result);
4388 
4389   // Notifies the unit test event listener that a test has just finished.
4390   repeater->OnTestEnd(*this);
4391   impl->set_current_test_info(nullptr);
4392 }
4393 
4394 // class TestSuite
4395 
4396 // Gets the number of successful tests in this test suite.
successful_test_count() const4397 int TestSuite::successful_test_count() const {
4398   return CountIf(test_info_list_, TestPassed);
4399 }
4400 
4401 // Gets the number of successful tests in this test suite.
skipped_test_count() const4402 int TestSuite::skipped_test_count() const {
4403   return CountIf(test_info_list_, TestSkipped);
4404 }
4405 
4406 // Gets the number of failed tests in this test suite.
failed_test_count() const4407 int TestSuite::failed_test_count() const {
4408   return CountIf(test_info_list_, TestFailed);
4409 }
4410 
4411 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const4412 int TestSuite::reportable_disabled_test_count() const {
4413   return CountIf(test_info_list_, TestReportableDisabled);
4414 }
4415 
4416 // Gets the number of disabled tests in this test suite.
disabled_test_count() const4417 int TestSuite::disabled_test_count() const {
4418   return CountIf(test_info_list_, TestDisabled);
4419 }
4420 
4421 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const4422 int TestSuite::reportable_test_count() const {
4423   return CountIf(test_info_list_, TestReportable);
4424 }
4425 
4426 // Get the number of tests in this test suite that should run.
test_to_run_count() const4427 int TestSuite::test_to_run_count() const {
4428   return CountIf(test_info_list_, ShouldRunTest);
4429 }
4430 
4431 // Gets the number of all tests.
total_test_count() const4432 int TestSuite::total_test_count() const {
4433   return static_cast<int>(test_info_list_.size());
4434 }
4435 
4436 // Creates a TestSuite with the given name.
4437 //
4438 // Arguments:
4439 //
4440 //   a_name:       name of the test suite
4441 //   a_type_param: the name of the test suite's type parameter, or NULL if
4442 //                 this is not a typed or a type-parameterized test suite.
4443 //   set_up_tc:    pointer to the function that sets up the test suite
4444 //   tear_down_tc: pointer to the function that tears down the test suite
TestSuite(const char * a_name,const char * a_type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)4445 TestSuite::TestSuite(const char* a_name, const char* a_type_param,
4446                      internal::SetUpTestSuiteFunc set_up_tc,
4447                      internal::TearDownTestSuiteFunc tear_down_tc)
4448     : name_(a_name),
4449       type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4450       set_up_tc_(set_up_tc),
4451       tear_down_tc_(tear_down_tc),
4452       should_run_(false),
4453       start_timestamp_(0),
4454       elapsed_time_(0) {}
4455 
4456 // Destructor of TestSuite.
~TestSuite()4457 TestSuite::~TestSuite() {
4458   // Deletes every Test in the collection.
4459   ForEach(test_info_list_, internal::Delete<TestInfo>);
4460 }
4461 
4462 // Returns the i-th test among all the tests. i can range from 0 to
4463 // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const4464 const TestInfo* TestSuite::GetTestInfo(int i) const {
4465   const int index = GetElementOr(test_indices_, i, -1);
4466   return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
4467 }
4468 
4469 // Returns the i-th test among all the tests. i can range from 0 to
4470 // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)4471 TestInfo* TestSuite::GetMutableTestInfo(int i) {
4472   const int index = GetElementOr(test_indices_, i, -1);
4473   return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
4474 }
4475 
4476 // Adds a test to this test suite.  Will delete the test upon
4477 // destruction of the TestSuite object.
AddTestInfo(TestInfo * test_info)4478 void TestSuite::AddTestInfo(TestInfo* test_info) {
4479   test_info_list_.push_back(test_info);
4480   test_indices_.push_back(static_cast<int>(test_indices_.size()));
4481 }
4482 
4483 // Runs every test in this TestSuite.
Run()4484 void TestSuite::Run() {
4485   if (!should_run_) return;
4486 
4487   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4488   impl->set_current_test_suite(this);
4489 
4490   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4491 
4492   // Call both legacy and the new API
4493   repeater->OnTestSuiteStart(*this);
4494 //  Legacy API is deprecated but still available
4495 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4496   repeater->OnTestCaseStart(*this);
4497 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4498 
4499   impl->os_stack_trace_getter()->UponLeavingGTest();
4500   internal::HandleExceptionsInMethodIfSupported(
4501       this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
4502 
4503   start_timestamp_ = internal::GetTimeInMillis();
4504   internal::Timer timer;
4505   for (int i = 0; i < total_test_count(); i++) {
4506     GetMutableTestInfo(i)->Run();
4507     if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {
4508       for (int j = i + 1; j < total_test_count(); j++) {
4509         GetMutableTestInfo(j)->Skip();
4510       }
4511       break;
4512     }
4513   }
4514   elapsed_time_ = timer.Elapsed();
4515 
4516   impl->os_stack_trace_getter()->UponLeavingGTest();
4517   internal::HandleExceptionsInMethodIfSupported(
4518       this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
4519 
4520   // Call both legacy and the new API
4521   repeater->OnTestSuiteEnd(*this);
4522 //  Legacy API is deprecated but still available
4523 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4524   repeater->OnTestCaseEnd(*this);
4525 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4526 
4527   impl->set_current_test_suite(nullptr);
4528 }
4529 
4530 // Skips all tests under this TestSuite.
Skip()4531 void TestSuite::Skip() {
4532   if (!should_run_) return;
4533 
4534   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4535   impl->set_current_test_suite(this);
4536 
4537   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4538 
4539   // Call both legacy and the new API
4540   repeater->OnTestSuiteStart(*this);
4541 //  Legacy API is deprecated but still available
4542 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4543   repeater->OnTestCaseStart(*this);
4544 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4545 
4546   for (int i = 0; i < total_test_count(); i++) {
4547     GetMutableTestInfo(i)->Skip();
4548   }
4549 
4550   // Call both legacy and the new API
4551   repeater->OnTestSuiteEnd(*this);
4552   // Legacy API is deprecated but still available
4553 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4554   repeater->OnTestCaseEnd(*this);
4555 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4556 
4557   impl->set_current_test_suite(nullptr);
4558 }
4559 
4560 // Clears the results of all tests in this test suite.
ClearResult()4561 void TestSuite::ClearResult() {
4562   ad_hoc_test_result_.Clear();
4563   ForEach(test_info_list_, TestInfo::ClearTestResult);
4564 }
4565 
4566 // Shuffles the tests in this test suite.
ShuffleTests(internal::Random * random)4567 void TestSuite::ShuffleTests(internal::Random* random) {
4568   Shuffle(random, &test_indices_);
4569 }
4570 
4571 // Restores the test order to before the first shuffle.
UnshuffleTests()4572 void TestSuite::UnshuffleTests() {
4573   for (size_t i = 0; i < test_indices_.size(); i++) {
4574     test_indices_[i] = static_cast<int>(i);
4575   }
4576 }
4577 
4578 // Formats a countable noun.  Depending on its quantity, either the
4579 // singular form or the plural form is used. e.g.
4580 //
4581 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4582 // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)4583 static std::string FormatCountableNoun(int count,
4584                                        const char * singular_form,
4585                                        const char * plural_form) {
4586   return internal::StreamableToString(count) + " " +
4587       (count == 1 ? singular_form : plural_form);
4588 }
4589 
4590 // Formats the count of tests.
FormatTestCount(int test_count)4591 static std::string FormatTestCount(int test_count) {
4592   return FormatCountableNoun(test_count, "test", "tests");
4593 }
4594 
4595 // Formats the count of test suites.
FormatTestSuiteCount(int test_suite_count)4596 static std::string FormatTestSuiteCount(int test_suite_count) {
4597   return FormatCountableNoun(test_suite_count, "test suite", "test suites");
4598 }
4599 
4600 // Converts a TestPartResult::Type enum to human-friendly string
4601 // representation.  Both kNonFatalFailure and kFatalFailure are translated
4602 // to "Failure", as the user usually doesn't care about the difference
4603 // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)4604 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4605   switch (type) {
4606     case TestPartResult::kSkip:
4607       return "Skipped\n";
4608     case TestPartResult::kSuccess:
4609       return "Success";
4610 
4611     case TestPartResult::kNonFatalFailure:
4612     case TestPartResult::kFatalFailure:
4613 #ifdef _MSC_VER
4614       return "error: ";
4615 #else
4616       return "Failure\n";
4617 #endif
4618     default:
4619       return "Unknown result type";
4620   }
4621 }
4622 
4623 namespace internal {
4624 namespace {
4625 enum class GTestColor { kDefault, kRed, kGreen, kYellow };
4626 }  // namespace
4627 
4628 // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)4629 static std::string PrintTestPartResultToString(
4630     const TestPartResult& test_part_result) {
4631   return (Message()
4632           << internal::FormatFileLocation(test_part_result.file_name(),
4633                                           test_part_result.line_number())
4634           << " " << TestPartResultTypeToString(test_part_result.type())
4635           << test_part_result.message()).GetString();
4636 }
4637 
4638 // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)4639 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4640   const std::string& result =
4641       PrintTestPartResultToString(test_part_result);
4642   printf("%s\n", result.c_str());
4643   fflush(stdout);
4644   // If the test program runs in Visual Studio or a debugger, the
4645   // following statements add the test part result message to the Output
4646   // window such that the user can double-click on it to jump to the
4647   // corresponding source code location; otherwise they do nothing.
4648 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4649   // We don't call OutputDebugString*() on Windows Mobile, as printing
4650   // to stdout is done by OutputDebugString() there already - we don't
4651   // want the same message printed twice.
4652   ::OutputDebugStringA(result.c_str());
4653   ::OutputDebugStringA("\n");
4654 #endif
4655 }
4656 
4657 // class PrettyUnitTestResultPrinter
4658 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4659     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4660 
4661 // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)4662 static WORD GetColorAttribute(GTestColor color) {
4663   switch (color) {
4664     case GTestColor::kRed:
4665       return FOREGROUND_RED;
4666     case GTestColor::kGreen:
4667       return FOREGROUND_GREEN;
4668     case GTestColor::kYellow:
4669       return FOREGROUND_RED | FOREGROUND_GREEN;
4670     default:           return 0;
4671   }
4672 }
4673 
GetBitOffset(WORD color_mask)4674 static int GetBitOffset(WORD color_mask) {
4675   if (color_mask == 0) return 0;
4676 
4677   int bitOffset = 0;
4678   while ((color_mask & 1) == 0) {
4679     color_mask >>= 1;
4680     ++bitOffset;
4681   }
4682   return bitOffset;
4683 }
4684 
GetNewColor(GTestColor color,WORD old_color_attrs)4685 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
4686   // Let's reuse the BG
4687   static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4688                                       BACKGROUND_RED | BACKGROUND_INTENSITY;
4689   static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4690                                       FOREGROUND_RED | FOREGROUND_INTENSITY;
4691   const WORD existing_bg = old_color_attrs & background_mask;
4692 
4693   WORD new_color =
4694       GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4695   static const int bg_bitOffset = GetBitOffset(background_mask);
4696   static const int fg_bitOffset = GetBitOffset(foreground_mask);
4697 
4698   if (((new_color & background_mask) >> bg_bitOffset) ==
4699       ((new_color & foreground_mask) >> fg_bitOffset)) {
4700     new_color ^= FOREGROUND_INTENSITY;  // invert intensity
4701   }
4702   return new_color;
4703 }
4704 
4705 #else
4706 
4707 // Returns the ANSI color code for the given color. GTestColor::kDefault is
4708 // an invalid input.
GetAnsiColorCode(GTestColor color)4709 static const char* GetAnsiColorCode(GTestColor color) {
4710   switch (color) {
4711     case GTestColor::kRed:
4712       return "1";
4713     case GTestColor::kGreen:
4714       return "2";
4715     case GTestColor::kYellow:
4716       return "3";
4717     default:
4718       return nullptr;
4719   }
4720 }
4721 
4722 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4723 
4724 // Returns true if and only if Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)4725 bool ShouldUseColor(bool stdout_is_tty) {
4726   const char* const gtest_color = GTEST_FLAG(color).c_str();
4727 
4728   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4729 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
4730     // On Windows the TERM variable is usually not set, but the
4731     // console there does support colors.
4732     return stdout_is_tty;
4733 #else
4734     // On non-Windows platforms, we rely on the TERM variable.
4735     const char* const term = posix::GetEnv("TERM");
4736     const bool term_supports_color =
4737         String::CStringEquals(term, "xterm") ||
4738         String::CStringEquals(term, "xterm-color") ||
4739         String::CStringEquals(term, "xterm-256color") ||
4740         String::CStringEquals(term, "screen") ||
4741         String::CStringEquals(term, "screen-256color") ||
4742         String::CStringEquals(term, "tmux") ||
4743         String::CStringEquals(term, "tmux-256color") ||
4744         String::CStringEquals(term, "rxvt-unicode") ||
4745         String::CStringEquals(term, "rxvt-unicode-256color") ||
4746         String::CStringEquals(term, "linux") ||
4747         String::CStringEquals(term, "cygwin");
4748     return stdout_is_tty && term_supports_color;
4749 #endif  // GTEST_OS_WINDOWS
4750   }
4751 
4752   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4753       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4754       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4755       String::CStringEquals(gtest_color, "1");
4756   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
4757   // value is neither one of these nor "auto", we treat it as "no" to
4758   // be conservative.
4759 }
4760 
4761 // Helpers for printing colored strings to stdout. Note that on Windows, we
4762 // cannot simply emit special characters and have the terminal change colors.
4763 // This routine must actually emit the characters rather than return a string
4764 // that would be colored when printed, as can be done on Linux.
4765 
4766 GTEST_ATTRIBUTE_PRINTF_(2, 3)
ColoredPrintf(GTestColor color,const char * fmt,...)4767 static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
4768   va_list args;
4769   va_start(args, fmt);
4770 
4771 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
4772     GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
4773   const bool use_color = AlwaysFalse();
4774 #else
4775   static const bool in_color_mode =
4776       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4777   const bool use_color = in_color_mode && (color != GTestColor::kDefault);
4778 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
4779 
4780   if (!use_color) {
4781     vprintf(fmt, args);
4782     va_end(args);
4783     return;
4784   }
4785 
4786 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4787     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4788   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4789 
4790   // Gets the current text color.
4791   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4792   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4793   const WORD old_color_attrs = buffer_info.wAttributes;
4794   const WORD new_color = GetNewColor(color, old_color_attrs);
4795 
4796   // We need to flush the stream buffers into the console before each
4797   // SetConsoleTextAttribute call lest it affect the text that is already
4798   // printed but has not yet reached the console.
4799   fflush(stdout);
4800   SetConsoleTextAttribute(stdout_handle, new_color);
4801 
4802   vprintf(fmt, args);
4803 
4804   fflush(stdout);
4805   // Restores the text color.
4806   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4807 #else
4808   printf("\033[0;3%sm", GetAnsiColorCode(color));
4809   vprintf(fmt, args);
4810   printf("\033[m");  // Resets the terminal to default.
4811 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4812   va_end(args);
4813 }
4814 
4815 // Text printed in Google Test's text output and --gtest_list_tests
4816 // output to label the type parameter and value parameter for a test.
4817 static const char kTypeParamLabel[] = "TypeParam";
4818 static const char kValueParamLabel[] = "GetParam()";
4819 
PrintFullTestCommentIfPresent(const TestInfo & test_info)4820 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4821   const char* const type_param = test_info.type_param();
4822   const char* const value_param = test_info.value_param();
4823 
4824   if (type_param != nullptr || value_param != nullptr) {
4825     printf(", where ");
4826     if (type_param != nullptr) {
4827       printf("%s = %s", kTypeParamLabel, type_param);
4828       if (value_param != nullptr) printf(" and ");
4829     }
4830     if (value_param != nullptr) {
4831       printf("%s = %s", kValueParamLabel, value_param);
4832     }
4833   }
4834 }
4835 
4836 // This class implements the TestEventListener interface.
4837 //
4838 // Class PrettyUnitTestResultPrinter is copyable.
4839 class PrettyUnitTestResultPrinter : public TestEventListener {
4840  public:
PrettyUnitTestResultPrinter()4841   PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_suite,const char * test)4842   static void PrintTestName(const char* test_suite, const char* test) {
4843     printf("%s.%s", test_suite, test);
4844   }
4845 
4846   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)4847   void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
4848   void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4849   void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
OnEnvironmentsSetUpEnd(const UnitTest &)4850   void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
4851 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4852   void OnTestCaseStart(const TestCase& test_case) override;
4853 #else
4854   void OnTestSuiteStart(const TestSuite& test_suite) override;
4855 #endif  // OnTestCaseStart
4856 
4857   void OnTestStart(const TestInfo& test_info) override;
4858 
4859   void OnTestPartResult(const TestPartResult& result) override;
4860   void OnTestEnd(const TestInfo& test_info) override;
4861 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4862   void OnTestCaseEnd(const TestCase& test_case) override;
4863 #else
4864   void OnTestSuiteEnd(const TestSuite& test_suite) override;
4865 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4866 
4867   void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
OnEnvironmentsTearDownEnd(const UnitTest &)4868   void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
4869   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
OnTestProgramEnd(const UnitTest &)4870   void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
4871 
4872  private:
4873   static void PrintFailedTests(const UnitTest& unit_test);
4874   static void PrintFailedTestSuites(const UnitTest& unit_test);
4875   static void PrintSkippedTests(const UnitTest& unit_test);
4876 };
4877 
4878   // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)4879 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4880     const UnitTest& unit_test, int iteration) {
4881   if (GTEST_FLAG(repeat) != 1)
4882     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4883 
4884   const char* const filter = GTEST_FLAG(filter).c_str();
4885 
4886   // Prints the filter if it's not *.  This reminds the user that some
4887   // tests may be skipped.
4888   if (!String::CStringEquals(filter, kUniversalFilter)) {
4889     ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
4890                   filter);
4891   }
4892 
4893   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4894     const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4895     ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
4896                   static_cast<int>(shard_index) + 1,
4897                   internal::posix::GetEnv(kTestTotalShards));
4898   }
4899 
4900   if (GTEST_FLAG(shuffle)) {
4901     ColoredPrintf(GTestColor::kYellow,
4902                   "Note: Randomizing tests' orders with a seed of %d .\n",
4903                   unit_test.random_seed());
4904   }
4905 
4906   ColoredPrintf(GTestColor::kGreen, "[==========] ");
4907   printf("Running %s from %s.\n",
4908          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4909          FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4910   fflush(stdout);
4911 }
4912 
OnEnvironmentsSetUpStart(const UnitTest &)4913 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4914     const UnitTest& /*unit_test*/) {
4915   ColoredPrintf(GTestColor::kGreen, "[----------] ");
4916   printf("Global test environment set-up.\n");
4917   fflush(stdout);
4918 }
4919 
4920 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseStart(const TestCase & test_case)4921 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4922   const std::string counts =
4923       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4924   ColoredPrintf(GTestColor::kGreen, "[----------] ");
4925   printf("%s from %s", counts.c_str(), test_case.name());
4926   if (test_case.type_param() == nullptr) {
4927     printf("\n");
4928   } else {
4929     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4930   }
4931   fflush(stdout);
4932 }
4933 #else
OnTestSuiteStart(const TestSuite & test_suite)4934 void PrettyUnitTestResultPrinter::OnTestSuiteStart(
4935     const TestSuite& test_suite) {
4936   const std::string counts =
4937       FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
4938   ColoredPrintf(GTestColor::kGreen, "[----------] ");
4939   printf("%s from %s", counts.c_str(), test_suite.name());
4940   if (test_suite.type_param() == nullptr) {
4941     printf("\n");
4942   } else {
4943     printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
4944   }
4945   fflush(stdout);
4946 }
4947 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4948 
OnTestStart(const TestInfo & test_info)4949 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4950   ColoredPrintf(GTestColor::kGreen, "[ RUN      ] ");
4951   PrintTestName(test_info.test_suite_name(), test_info.name());
4952   printf("\n");
4953   fflush(stdout);
4954 }
4955 
4956 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)4957 void PrettyUnitTestResultPrinter::OnTestPartResult(
4958     const TestPartResult& result) {
4959   switch (result.type()) {
4960     // If the test part succeeded, we don't need to do anything.
4961     case TestPartResult::kSuccess:
4962       return;
4963     default:
4964       // Print failure message from the assertion
4965       // (e.g. expected this and got that).
4966       PrintTestPartResult(result);
4967       fflush(stdout);
4968   }
4969 }
4970 
OnTestEnd(const TestInfo & test_info)4971 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4972   if (test_info.result()->Passed()) {
4973     ColoredPrintf(GTestColor::kGreen, "[       OK ] ");
4974   } else if (test_info.result()->Skipped()) {
4975     ColoredPrintf(GTestColor::kGreen, "[  SKIPPED ] ");
4976   } else {
4977     ColoredPrintf(GTestColor::kRed, "[  FAILED  ] ");
4978   }
4979   PrintTestName(test_info.test_suite_name(), test_info.name());
4980   if (test_info.result()->Failed())
4981     PrintFullTestCommentIfPresent(test_info);
4982 
4983   if (GTEST_FLAG(print_time)) {
4984     printf(" (%s ms)\n", internal::StreamableToString(
4985            test_info.result()->elapsed_time()).c_str());
4986   } else {
4987     printf("\n");
4988   }
4989   fflush(stdout);
4990 }
4991 
4992 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseEnd(const TestCase & test_case)4993 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4994   if (!GTEST_FLAG(print_time)) return;
4995 
4996   const std::string counts =
4997       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4998   ColoredPrintf(GTestColor::kGreen, "[----------] ");
4999   printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
5000          internal::StreamableToString(test_case.elapsed_time()).c_str());
5001   fflush(stdout);
5002 }
5003 #else
OnTestSuiteEnd(const TestSuite & test_suite)5004 void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
5005   if (!GTEST_FLAG(print_time)) return;
5006 
5007   const std::string counts =
5008       FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
5009   ColoredPrintf(GTestColor::kGreen, "[----------] ");
5010   printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
5011          internal::StreamableToString(test_suite.elapsed_time()).c_str());
5012   fflush(stdout);
5013 }
5014 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5015 
OnEnvironmentsTearDownStart(const UnitTest &)5016 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
5017     const UnitTest& /*unit_test*/) {
5018   ColoredPrintf(GTestColor::kGreen, "[----------] ");
5019   printf("Global test environment tear-down\n");
5020   fflush(stdout);
5021 }
5022 
5023 // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)5024 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
5025   const int failed_test_count = unit_test.failed_test_count();
5026   ColoredPrintf(GTestColor::kRed, "[  FAILED  ] ");
5027   printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
5028 
5029   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5030     const TestSuite& test_suite = *unit_test.GetTestSuite(i);
5031     if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
5032       continue;
5033     }
5034     for (int j = 0; j < test_suite.total_test_count(); ++j) {
5035       const TestInfo& test_info = *test_suite.GetTestInfo(j);
5036       if (!test_info.should_run() || !test_info.result()->Failed()) {
5037         continue;
5038       }
5039       ColoredPrintf(GTestColor::kRed, "[  FAILED  ] ");
5040       printf("%s.%s", test_suite.name(), test_info.name());
5041       PrintFullTestCommentIfPresent(test_info);
5042       printf("\n");
5043     }
5044   }
5045   printf("\n%2d FAILED %s\n", failed_test_count,
5046          failed_test_count == 1 ? "TEST" : "TESTS");
5047 }
5048 
5049 // Internal helper for printing the list of test suite failures not covered by
5050 // PrintFailedTests.
PrintFailedTestSuites(const UnitTest & unit_test)5051 void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
5052     const UnitTest& unit_test) {
5053   int suite_failure_count = 0;
5054   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5055     const TestSuite& test_suite = *unit_test.GetTestSuite(i);
5056     if (!test_suite.should_run()) {
5057       continue;
5058     }
5059     if (test_suite.ad_hoc_test_result().Failed()) {
5060       ColoredPrintf(GTestColor::kRed, "[  FAILED  ] ");
5061       printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
5062       ++suite_failure_count;
5063     }
5064   }
5065   if (suite_failure_count > 0) {
5066     printf("\n%2d FAILED TEST %s\n", suite_failure_count,
5067            suite_failure_count == 1 ? "SUITE" : "SUITES");
5068   }
5069 }
5070 
5071 // Internal helper for printing the list of skipped tests.
PrintSkippedTests(const UnitTest & unit_test)5072 void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
5073   const int skipped_test_count = unit_test.skipped_test_count();
5074   if (skipped_test_count == 0) {
5075     return;
5076   }
5077 
5078   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5079     const TestSuite& test_suite = *unit_test.GetTestSuite(i);
5080     if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
5081       continue;
5082     }
5083     for (int j = 0; j < test_suite.total_test_count(); ++j) {
5084       const TestInfo& test_info = *test_suite.GetTestInfo(j);
5085       if (!test_info.should_run() || !test_info.result()->Skipped()) {
5086         continue;
5087       }
5088       ColoredPrintf(GTestColor::kGreen, "[  SKIPPED ] ");
5089       printf("%s.%s", test_suite.name(), test_info.name());
5090       printf("\n");
5091     }
5092   }
5093 }
5094 
OnTestIterationEnd(const UnitTest & unit_test,int)5095 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5096                                                      int /*iteration*/) {
5097   ColoredPrintf(GTestColor::kGreen, "[==========] ");
5098   printf("%s from %s ran.",
5099          FormatTestCount(unit_test.test_to_run_count()).c_str(),
5100          FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
5101   if (GTEST_FLAG(print_time)) {
5102     printf(" (%s ms total)",
5103            internal::StreamableToString(unit_test.elapsed_time()).c_str());
5104   }
5105   printf("\n");
5106   ColoredPrintf(GTestColor::kGreen, "[  PASSED  ] ");
5107   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
5108 
5109   const int skipped_test_count = unit_test.skipped_test_count();
5110   if (skipped_test_count > 0) {
5111     ColoredPrintf(GTestColor::kGreen, "[  SKIPPED ] ");
5112     printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
5113     PrintSkippedTests(unit_test);
5114   }
5115 
5116   if (!unit_test.Passed()) {
5117     PrintFailedTests(unit_test);
5118     PrintFailedTestSuites(unit_test);
5119   }
5120 
5121   int num_disabled = unit_test.reportable_disabled_test_count();
5122   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
5123     if (unit_test.Passed()) {
5124       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
5125     }
5126     ColoredPrintf(GTestColor::kYellow, "  YOU HAVE %d DISABLED %s\n\n",
5127                   num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
5128   }
5129   // Ensure that Google Test output is printed before, e.g., heapchecker output.
5130   fflush(stdout);
5131 }
5132 
5133 // End PrettyUnitTestResultPrinter
5134 
5135 // This class implements the TestEventListener interface.
5136 //
5137 // Class BriefUnitTestResultPrinter is copyable.
5138 class BriefUnitTestResultPrinter : public TestEventListener {
5139  public:
BriefUnitTestResultPrinter()5140   BriefUnitTestResultPrinter() {}
PrintTestName(const char * test_suite,const char * test)5141   static void PrintTestName(const char* test_suite, const char* test) {
5142     printf("%s.%s", test_suite, test);
5143   }
5144 
5145   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)5146   void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
OnTestIterationStart(const UnitTest &,int)5147   void OnTestIterationStart(const UnitTest& /*unit_test*/,
5148                             int /*iteration*/) override {}
OnEnvironmentsSetUpStart(const UnitTest &)5149   void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
OnEnvironmentsSetUpEnd(const UnitTest &)5150   void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
5151 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseStart(const TestCase &)5152   void OnTestCaseStart(const TestCase& /*test_case*/) override {}
5153 #else
OnTestSuiteStart(const TestSuite &)5154   void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
5155 #endif  // OnTestCaseStart
5156 
OnTestStart(const TestInfo &)5157   void OnTestStart(const TestInfo& /*test_info*/) override {}
5158 
5159   void OnTestPartResult(const TestPartResult& result) override;
5160   void OnTestEnd(const TestInfo& test_info) override;
5161 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseEnd(const TestCase &)5162   void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
5163 #else
OnTestSuiteEnd(const TestSuite &)5164   void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
5165 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5166 
OnEnvironmentsTearDownStart(const UnitTest &)5167   void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
OnEnvironmentsTearDownEnd(const UnitTest &)5168   void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
5169   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
OnTestProgramEnd(const UnitTest &)5170   void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
5171 };
5172 
5173 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)5174 void BriefUnitTestResultPrinter::OnTestPartResult(
5175     const TestPartResult& result) {
5176   switch (result.type()) {
5177     // If the test part succeeded, we don't need to do anything.
5178     case TestPartResult::kSuccess:
5179       return;
5180     default:
5181       // Print failure message from the assertion
5182       // (e.g. expected this and got that).
5183       PrintTestPartResult(result);
5184       fflush(stdout);
5185   }
5186 }
5187 
OnTestEnd(const TestInfo & test_info)5188 void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
5189   if (test_info.result()->Failed()) {
5190     ColoredPrintf(GTestColor::kRed, "[  FAILED  ] ");
5191     PrintTestName(test_info.test_suite_name(), test_info.name());
5192     PrintFullTestCommentIfPresent(test_info);
5193 
5194     if (GTEST_FLAG(print_time)) {
5195       printf(" (%s ms)\n",
5196              internal::StreamableToString(test_info.result()->elapsed_time())
5197                  .c_str());
5198     } else {
5199       printf("\n");
5200     }
5201     fflush(stdout);
5202   }
5203 }
5204 
OnTestIterationEnd(const UnitTest & unit_test,int)5205 void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5206                                                     int /*iteration*/) {
5207   ColoredPrintf(GTestColor::kGreen, "[==========] ");
5208   printf("%s from %s ran.",
5209          FormatTestCount(unit_test.test_to_run_count()).c_str(),
5210          FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
5211   if (GTEST_FLAG(print_time)) {
5212     printf(" (%s ms total)",
5213            internal::StreamableToString(unit_test.elapsed_time()).c_str());
5214   }
5215   printf("\n");
5216   ColoredPrintf(GTestColor::kGreen, "[  PASSED  ] ");
5217   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
5218 
5219   const int skipped_test_count = unit_test.skipped_test_count();
5220   if (skipped_test_count > 0) {
5221     ColoredPrintf(GTestColor::kGreen, "[  SKIPPED ] ");
5222     printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
5223   }
5224 
5225   int num_disabled = unit_test.reportable_disabled_test_count();
5226   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
5227     if (unit_test.Passed()) {
5228       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
5229     }
5230     ColoredPrintf(GTestColor::kYellow, "  YOU HAVE %d DISABLED %s\n\n",
5231                   num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
5232   }
5233   // Ensure that Google Test output is printed before, e.g., heapchecker output.
5234   fflush(stdout);
5235 }
5236 
5237 // End BriefUnitTestResultPrinter
5238 
5239 // class TestEventRepeater
5240 //
5241 // This class forwards events to other event listeners.
5242 class TestEventRepeater : public TestEventListener {
5243  public:
TestEventRepeater()5244   TestEventRepeater() : forwarding_enabled_(true) {}
5245   ~TestEventRepeater() override;
5246   void Append(TestEventListener *listener);
5247   TestEventListener* Release(TestEventListener* listener);
5248 
5249   // Controls whether events will be forwarded to listeners_. Set to false
5250   // in death test child processes.
forwarding_enabled() const5251   bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)5252   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
5253 
5254   void OnTestProgramStart(const UnitTest& unit_test) override;
5255   void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
5256   void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
5257   void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
5258 //  Legacy API is deprecated but still available
5259 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5260   void OnTestCaseStart(const TestSuite& parameter) override;
5261 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5262   void OnTestSuiteStart(const TestSuite& parameter) override;
5263   void OnTestStart(const TestInfo& test_info) override;
5264   void OnTestPartResult(const TestPartResult& result) override;
5265   void OnTestEnd(const TestInfo& test_info) override;
5266 //  Legacy API is deprecated but still available
5267 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5268   void OnTestCaseEnd(const TestCase& parameter) override;
5269 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5270   void OnTestSuiteEnd(const TestSuite& parameter) override;
5271   void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
5272   void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
5273   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5274   void OnTestProgramEnd(const UnitTest& unit_test) override;
5275 
5276  private:
5277   // Controls whether events will be forwarded to listeners_. Set to false
5278   // in death test child processes.
5279   bool forwarding_enabled_;
5280   // The list of listeners that receive events.
5281   std::vector<TestEventListener*> listeners_;
5282 
5283   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
5284 };
5285 
~TestEventRepeater()5286 TestEventRepeater::~TestEventRepeater() {
5287   ForEach(listeners_, Delete<TestEventListener>);
5288 }
5289 
Append(TestEventListener * listener)5290 void TestEventRepeater::Append(TestEventListener *listener) {
5291   listeners_.push_back(listener);
5292 }
5293 
Release(TestEventListener * listener)5294 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
5295   for (size_t i = 0; i < listeners_.size(); ++i) {
5296     if (listeners_[i] == listener) {
5297       listeners_.erase(listeners_.begin() + static_cast<int>(i));
5298       return listener;
5299     }
5300   }
5301 
5302   return nullptr;
5303 }
5304 
5305 // Since most methods are very similar, use macros to reduce boilerplate.
5306 // This defines a member that forwards the call to all listeners.
5307 #define GTEST_REPEATER_METHOD_(Name, Type) \
5308 void TestEventRepeater::Name(const Type& parameter) { \
5309   if (forwarding_enabled_) { \
5310     for (size_t i = 0; i < listeners_.size(); i++) { \
5311       listeners_[i]->Name(parameter); \
5312     } \
5313   } \
5314 }
5315 // This defines a member that forwards the call to all listeners in reverse
5316 // order.
5317 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)      \
5318   void TestEventRepeater::Name(const Type& parameter) { \
5319     if (forwarding_enabled_) {                          \
5320       for (size_t i = listeners_.size(); i != 0; i--) { \
5321         listeners_[i - 1]->Name(parameter);             \
5322       }                                                 \
5323     }                                                   \
5324   }
5325 
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)5326 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
5327 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
5328 //  Legacy API is deprecated but still available
5329 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5330 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
5331 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5332 GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
5333 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
5334 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
5335 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
5336 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
5337 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
5338 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
5339 //  Legacy API is deprecated but still available
5340 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5341 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
5342 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5343 GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
5344 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
5345 
5346 #undef GTEST_REPEATER_METHOD_
5347 #undef GTEST_REVERSE_REPEATER_METHOD_
5348 
5349 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
5350                                              int iteration) {
5351   if (forwarding_enabled_) {
5352     for (size_t i = 0; i < listeners_.size(); i++) {
5353       listeners_[i]->OnTestIterationStart(unit_test, iteration);
5354     }
5355   }
5356 }
5357 
OnTestIterationEnd(const UnitTest & unit_test,int iteration)5358 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
5359                                            int iteration) {
5360   if (forwarding_enabled_) {
5361     for (size_t i = listeners_.size(); i > 0; i--) {
5362       listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
5363     }
5364   }
5365 }
5366 
5367 // End TestEventRepeater
5368 
5369 // This class generates an XML output file.
5370 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
5371  public:
5372   explicit XmlUnitTestResultPrinter(const char* output_file);
5373 
5374   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5375   void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
5376 
5377   // Prints an XML summary of all unit tests.
5378   static void PrintXmlTestsList(std::ostream* stream,
5379                                 const std::vector<TestSuite*>& test_suites);
5380 
5381  private:
5382   // Is c a whitespace character that is normalized to a space character
5383   // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)5384   static bool IsNormalizableWhitespace(char c) {
5385     return c == 0x9 || c == 0xA || c == 0xD;
5386   }
5387 
5388   // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)5389   static bool IsValidXmlCharacter(char c) {
5390     return IsNormalizableWhitespace(c) || c >= 0x20;
5391   }
5392 
5393   // Returns an XML-escaped copy of the input string str.  If
5394   // is_attribute is true, the text is meant to appear as an attribute
5395   // value, and normalizable whitespace is preserved by replacing it
5396   // with character references.
5397   static std::string EscapeXml(const std::string& str, bool is_attribute);
5398 
5399   // Returns the given string with all characters invalid in XML removed.
5400   static std::string RemoveInvalidXmlCharacters(const std::string& str);
5401 
5402   // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)5403   static std::string EscapeXmlAttribute(const std::string& str) {
5404     return EscapeXml(str, true);
5405   }
5406 
5407   // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)5408   static std::string EscapeXmlText(const char* str) {
5409     return EscapeXml(str, false);
5410   }
5411 
5412   // Verifies that the given attribute belongs to the given element and
5413   // streams the attribute as XML.
5414   static void OutputXmlAttribute(std::ostream* stream,
5415                                  const std::string& element_name,
5416                                  const std::string& name,
5417                                  const std::string& value);
5418 
5419   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5420   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
5421 
5422   // Streams a test suite XML stanza containing the given test result.
5423   //
5424   // Requires: result.Failed()
5425   static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
5426                                               const TestResult& result);
5427 
5428   // Streams an XML representation of a TestResult object.
5429   static void OutputXmlTestResult(::std::ostream* stream,
5430                                   const TestResult& result);
5431 
5432   // Streams an XML representation of a TestInfo object.
5433   static void OutputXmlTestInfo(::std::ostream* stream,
5434                                 const char* test_suite_name,
5435                                 const TestInfo& test_info);
5436 
5437   // Prints an XML representation of a TestSuite object
5438   static void PrintXmlTestSuite(::std::ostream* stream,
5439                                 const TestSuite& test_suite);
5440 
5441   // Prints an XML summary of unit_test to output stream out.
5442   static void PrintXmlUnitTest(::std::ostream* stream,
5443                                const UnitTest& unit_test);
5444 
5445   // Produces a string representing the test properties in a result as space
5446   // delimited XML attributes based on the property key="value" pairs.
5447   // When the std::string is not empty, it includes a space at the beginning,
5448   // to delimit this attribute from prior attributes.
5449   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
5450 
5451   // Streams an XML representation of the test properties of a TestResult
5452   // object.
5453   static void OutputXmlTestProperties(std::ostream* stream,
5454                                       const TestResult& result);
5455 
5456   // The output file.
5457   const std::string output_file_;
5458 
5459   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
5460 };
5461 
5462 // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)5463 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
5464     : output_file_(output_file) {
5465   if (output_file_.empty()) {
5466     GTEST_LOG_(FATAL) << "XML output file may not be null";
5467   }
5468 }
5469 
5470 // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)5471 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5472                                                   int /*iteration*/) {
5473   FILE* xmlout = OpenFileForWriting(output_file_);
5474   std::stringstream stream;
5475   PrintXmlUnitTest(&stream, unit_test);
5476   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5477   fclose(xmlout);
5478 }
5479 
ListTestsMatchingFilter(const std::vector<TestSuite * > & test_suites)5480 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
5481     const std::vector<TestSuite*>& test_suites) {
5482   FILE* xmlout = OpenFileForWriting(output_file_);
5483   std::stringstream stream;
5484   PrintXmlTestsList(&stream, test_suites);
5485   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5486   fclose(xmlout);
5487 }
5488 
5489 // Returns an XML-escaped copy of the input string str.  If is_attribute
5490 // is true, the text is meant to appear as an attribute value, and
5491 // normalizable whitespace is preserved by replacing it with character
5492 // references.
5493 //
5494 // Invalid XML characters in str, if any, are stripped from the output.
5495 // It is expected that most, if not all, of the text processed by this
5496 // module will consist of ordinary English text.
5497 // If this module is ever modified to produce version 1.1 XML output,
5498 // most invalid characters can be retained using character references.
EscapeXml(const std::string & str,bool is_attribute)5499 std::string XmlUnitTestResultPrinter::EscapeXml(
5500     const std::string& str, bool is_attribute) {
5501   Message m;
5502 
5503   for (size_t i = 0; i < str.size(); ++i) {
5504     const char ch = str[i];
5505     switch (ch) {
5506       case '<':
5507         m << "&lt;";
5508         break;
5509       case '>':
5510         m << "&gt;";
5511         break;
5512       case '&':
5513         m << "&amp;";
5514         break;
5515       case '\'':
5516         if (is_attribute)
5517           m << "&apos;";
5518         else
5519           m << '\'';
5520         break;
5521       case '"':
5522         if (is_attribute)
5523           m << "&quot;";
5524         else
5525           m << '"';
5526         break;
5527       default:
5528         if (IsValidXmlCharacter(ch)) {
5529           if (is_attribute && IsNormalizableWhitespace(ch))
5530             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5531               << ";";
5532           else
5533             m << ch;
5534         }
5535         break;
5536     }
5537   }
5538 
5539   return m.GetString();
5540 }
5541 
5542 // Returns the given string with all characters invalid in XML removed.
5543 // Currently invalid characters are dropped from the string. An
5544 // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)5545 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5546     const std::string& str) {
5547   std::string output;
5548   output.reserve(str.size());
5549   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5550     if (IsValidXmlCharacter(*it))
5551       output.push_back(*it);
5552 
5553   return output;
5554 }
5555 
5556 // The following routines generate an XML representation of a UnitTest
5557 // object.
5558 // GOOGLETEST_CM0009 DO NOT DELETE
5559 //
5560 // This is how Google Test concepts map to the DTD:
5561 //
5562 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
5563 //   <testsuite name="testcase-name">  <-- corresponds to a TestSuite object
5564 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
5565 //       <failure message="...">...</failure>
5566 //       <failure message="...">...</failure>
5567 //       <failure message="...">...</failure>
5568 //                                     <-- individual assertion failures
5569 //     </testcase>
5570 //   </testsuite>
5571 // </testsuites>
5572 
5573 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)5574 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5575   ::std::stringstream ss;
5576   ss << (static_cast<double>(ms) * 1e-3);
5577   return ss.str();
5578 }
5579 
PortableLocaltime(time_t seconds,struct tm * out)5580 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5581 #if defined(_MSC_VER)
5582   return localtime_s(out, &seconds) == 0;
5583 #elif defined(__MINGW32__) || defined(__MINGW64__)
5584   // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5585   // Windows' localtime(), which has a thread-local tm buffer.
5586   struct tm* tm_ptr = localtime(&seconds);  // NOLINT
5587   if (tm_ptr == nullptr) return false;
5588   *out = *tm_ptr;
5589   return true;
5590 #elif defined(__STDC_LIB_EXT1__)
5591   // Uses localtime_s when available as localtime_r is only available from
5592   // C23 standard.
5593   return localtime_s(&seconds, out) != nullptr;
5594 #else
5595   return localtime_r(&seconds, out) != nullptr;
5596 #endif
5597 }
5598 
5599 // Converts the given epoch time in milliseconds to a date string in the ISO
5600 // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)5601 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5602   struct tm time_struct;
5603   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5604     return "";
5605   // YYYY-MM-DDThh:mm:ss.sss
5606   return StreamableToString(time_struct.tm_year + 1900) + "-" +
5607       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5608       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5609       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5610       String::FormatIntWidth2(time_struct.tm_min) + ":" +
5611       String::FormatIntWidth2(time_struct.tm_sec) + "." +
5612       String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
5613 }
5614 
5615 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)5616 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5617                                                      const char* data) {
5618   const char* segment = data;
5619   *stream << "<![CDATA[";
5620   for (;;) {
5621     const char* const next_segment = strstr(segment, "]]>");
5622     if (next_segment != nullptr) {
5623       stream->write(
5624           segment, static_cast<std::streamsize>(next_segment - segment));
5625       *stream << "]]>]]&gt;<![CDATA[";
5626       segment = next_segment + strlen("]]>");
5627     } else {
5628       *stream << segment;
5629       break;
5630     }
5631   }
5632   *stream << "]]>";
5633 }
5634 
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)5635 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5636     std::ostream* stream,
5637     const std::string& element_name,
5638     const std::string& name,
5639     const std::string& value) {
5640   const std::vector<std::string>& allowed_names =
5641       GetReservedOutputAttributesForElement(element_name);
5642 
5643   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5644                    allowed_names.end())
5645       << "Attribute " << name << " is not allowed for element <" << element_name
5646       << ">.";
5647 
5648   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5649 }
5650 
5651 // Streams a test suite XML stanza containing the given test result.
OutputXmlTestSuiteForTestResult(::std::ostream * stream,const TestResult & result)5652 void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
5653     ::std::ostream* stream, const TestResult& result) {
5654   // Output the boilerplate for a minimal test suite with one test.
5655   *stream << "  <testsuite";
5656   OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
5657   OutputXmlAttribute(stream, "testsuite", "tests", "1");
5658   OutputXmlAttribute(stream, "testsuite", "failures", "1");
5659   OutputXmlAttribute(stream, "testsuite", "disabled", "0");
5660   OutputXmlAttribute(stream, "testsuite", "skipped", "0");
5661   OutputXmlAttribute(stream, "testsuite", "errors", "0");
5662   OutputXmlAttribute(stream, "testsuite", "time",
5663                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
5664   OutputXmlAttribute(
5665       stream, "testsuite", "timestamp",
5666       FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
5667   *stream << ">";
5668 
5669   // Output the boilerplate for a minimal test case with a single test.
5670   *stream << "    <testcase";
5671   OutputXmlAttribute(stream, "testcase", "name", "");
5672   OutputXmlAttribute(stream, "testcase", "status", "run");
5673   OutputXmlAttribute(stream, "testcase", "result", "completed");
5674   OutputXmlAttribute(stream, "testcase", "classname", "");
5675   OutputXmlAttribute(stream, "testcase", "time",
5676                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
5677   OutputXmlAttribute(
5678       stream, "testcase", "timestamp",
5679       FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
5680 
5681   // Output the actual test result.
5682   OutputXmlTestResult(stream, result);
5683 
5684   // Complete the test suite.
5685   *stream << "  </testsuite>\n";
5686 }
5687 
5688 // Prints an XML representation of a TestInfo object.
OutputXmlTestInfo(::std::ostream * stream,const char * test_suite_name,const TestInfo & test_info)5689 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5690                                                  const char* test_suite_name,
5691                                                  const TestInfo& test_info) {
5692   const TestResult& result = *test_info.result();
5693   const std::string kTestsuite = "testcase";
5694 
5695   if (test_info.is_in_another_shard()) {
5696     return;
5697   }
5698 
5699   *stream << "    <testcase";
5700   OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
5701 
5702   if (test_info.value_param() != nullptr) {
5703     OutputXmlAttribute(stream, kTestsuite, "value_param",
5704                        test_info.value_param());
5705   }
5706   if (test_info.type_param() != nullptr) {
5707     OutputXmlAttribute(stream, kTestsuite, "type_param",
5708                        test_info.type_param());
5709   }
5710   if (GTEST_FLAG(list_tests)) {
5711     OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
5712     OutputXmlAttribute(stream, kTestsuite, "line",
5713                        StreamableToString(test_info.line()));
5714     *stream << " />\n";
5715     return;
5716   }
5717 
5718   OutputXmlAttribute(stream, kTestsuite, "status",
5719                      test_info.should_run() ? "run" : "notrun");
5720   OutputXmlAttribute(stream, kTestsuite, "result",
5721                      test_info.should_run()
5722                          ? (result.Skipped() ? "skipped" : "completed")
5723                          : "suppressed");
5724   OutputXmlAttribute(stream, kTestsuite, "time",
5725                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
5726   OutputXmlAttribute(
5727       stream, kTestsuite, "timestamp",
5728       FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
5729   OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
5730 
5731   OutputXmlTestResult(stream, result);
5732 }
5733 
OutputXmlTestResult(::std::ostream * stream,const TestResult & result)5734 void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
5735                                                    const TestResult& result) {
5736   int failures = 0;
5737   int skips = 0;
5738   for (int i = 0; i < result.total_part_count(); ++i) {
5739     const TestPartResult& part = result.GetTestPartResult(i);
5740     if (part.failed()) {
5741       if (++failures == 1 && skips == 0) {
5742         *stream << ">\n";
5743       }
5744       const std::string location =
5745           internal::FormatCompilerIndependentFileLocation(part.file_name(),
5746                                                           part.line_number());
5747       const std::string summary = location + "\n" + part.summary();
5748       *stream << "      <failure message=\""
5749               << EscapeXmlAttribute(summary)
5750               << "\" type=\"\">";
5751       const std::string detail = location + "\n" + part.message();
5752       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5753       *stream << "</failure>\n";
5754     } else if (part.skipped()) {
5755       if (++skips == 1 && failures == 0) {
5756         *stream << ">\n";
5757       }
5758       const std::string location =
5759           internal::FormatCompilerIndependentFileLocation(part.file_name(),
5760                                                           part.line_number());
5761       const std::string summary = location + "\n" + part.summary();
5762       *stream << "      <skipped message=\""
5763               << EscapeXmlAttribute(summary.c_str()) << "\">";
5764       const std::string detail = location + "\n" + part.message();
5765       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5766       *stream << "</skipped>\n";
5767     }
5768   }
5769 
5770   if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
5771     *stream << " />\n";
5772   } else {
5773     if (failures == 0 && skips == 0) {
5774       *stream << ">\n";
5775     }
5776     OutputXmlTestProperties(stream, result);
5777     *stream << "    </testcase>\n";
5778   }
5779 }
5780 
5781 // Prints an XML representation of a TestSuite object
PrintXmlTestSuite(std::ostream * stream,const TestSuite & test_suite)5782 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
5783                                                  const TestSuite& test_suite) {
5784   const std::string kTestsuite = "testsuite";
5785   *stream << "  <" << kTestsuite;
5786   OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
5787   OutputXmlAttribute(stream, kTestsuite, "tests",
5788                      StreamableToString(test_suite.reportable_test_count()));
5789   if (!GTEST_FLAG(list_tests)) {
5790     OutputXmlAttribute(stream, kTestsuite, "failures",
5791                        StreamableToString(test_suite.failed_test_count()));
5792     OutputXmlAttribute(
5793         stream, kTestsuite, "disabled",
5794         StreamableToString(test_suite.reportable_disabled_test_count()));
5795     OutputXmlAttribute(stream, kTestsuite, "skipped",
5796                        StreamableToString(test_suite.skipped_test_count()));
5797 
5798     OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5799 
5800     OutputXmlAttribute(stream, kTestsuite, "time",
5801                        FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
5802     OutputXmlAttribute(
5803         stream, kTestsuite, "timestamp",
5804         FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
5805     *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
5806   }
5807   *stream << ">\n";
5808   for (int i = 0; i < test_suite.total_test_count(); ++i) {
5809     if (test_suite.GetTestInfo(i)->is_reportable())
5810       OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5811   }
5812   *stream << "  </" << kTestsuite << ">\n";
5813 }
5814 
5815 // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)5816 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5817                                                 const UnitTest& unit_test) {
5818   const std::string kTestsuites = "testsuites";
5819 
5820   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5821   *stream << "<" << kTestsuites;
5822 
5823   OutputXmlAttribute(stream, kTestsuites, "tests",
5824                      StreamableToString(unit_test.reportable_test_count()));
5825   OutputXmlAttribute(stream, kTestsuites, "failures",
5826                      StreamableToString(unit_test.failed_test_count()));
5827   OutputXmlAttribute(
5828       stream, kTestsuites, "disabled",
5829       StreamableToString(unit_test.reportable_disabled_test_count()));
5830   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5831   OutputXmlAttribute(stream, kTestsuites, "time",
5832                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5833   OutputXmlAttribute(
5834       stream, kTestsuites, "timestamp",
5835       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5836 
5837   if (GTEST_FLAG(shuffle)) {
5838     OutputXmlAttribute(stream, kTestsuites, "random_seed",
5839                        StreamableToString(unit_test.random_seed()));
5840   }
5841   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5842 
5843   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5844   *stream << ">\n";
5845 
5846   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5847     if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
5848       PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
5849   }
5850 
5851   // If there was a test failure outside of one of the test suites (like in a
5852   // test environment) include that in the output.
5853   if (unit_test.ad_hoc_test_result().Failed()) {
5854     OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
5855   }
5856 
5857   *stream << "</" << kTestsuites << ">\n";
5858 }
5859 
PrintXmlTestsList(std::ostream * stream,const std::vector<TestSuite * > & test_suites)5860 void XmlUnitTestResultPrinter::PrintXmlTestsList(
5861     std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5862   const std::string kTestsuites = "testsuites";
5863 
5864   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5865   *stream << "<" << kTestsuites;
5866 
5867   int total_tests = 0;
5868   for (auto test_suite : test_suites) {
5869     total_tests += test_suite->total_test_count();
5870   }
5871   OutputXmlAttribute(stream, kTestsuites, "tests",
5872                      StreamableToString(total_tests));
5873   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5874   *stream << ">\n";
5875 
5876   for (auto test_suite : test_suites) {
5877     PrintXmlTestSuite(stream, *test_suite);
5878   }
5879   *stream << "</" << kTestsuites << ">\n";
5880 }
5881 
5882 // Produces a string representing the test properties in a result as space
5883 // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)5884 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5885     const TestResult& result) {
5886   Message attributes;
5887   for (int i = 0; i < result.test_property_count(); ++i) {
5888     const TestProperty& property = result.GetTestProperty(i);
5889     attributes << " " << property.key() << "="
5890         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5891   }
5892   return attributes.GetString();
5893 }
5894 
OutputXmlTestProperties(std::ostream * stream,const TestResult & result)5895 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5896     std::ostream* stream, const TestResult& result) {
5897   const std::string kProperties = "properties";
5898   const std::string kProperty = "property";
5899 
5900   if (result.test_property_count() <= 0) {
5901     return;
5902   }
5903 
5904   *stream << "<" << kProperties << ">\n";
5905   for (int i = 0; i < result.test_property_count(); ++i) {
5906     const TestProperty& property = result.GetTestProperty(i);
5907     *stream << "<" << kProperty;
5908     *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
5909     *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
5910     *stream << "/>\n";
5911   }
5912   *stream << "</" << kProperties << ">\n";
5913 }
5914 
5915 // End XmlUnitTestResultPrinter
5916 
5917 // This class generates an JSON output file.
5918 class JsonUnitTestResultPrinter : public EmptyTestEventListener {
5919  public:
5920   explicit JsonUnitTestResultPrinter(const char* output_file);
5921 
5922   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5923 
5924   // Prints an JSON summary of all unit tests.
5925   static void PrintJsonTestList(::std::ostream* stream,
5926                                 const std::vector<TestSuite*>& test_suites);
5927 
5928  private:
5929   // Returns an JSON-escaped copy of the input string str.
5930   static std::string EscapeJson(const std::string& str);
5931 
5932   //// Verifies that the given attribute belongs to the given element and
5933   //// streams the attribute as JSON.
5934   static void OutputJsonKey(std::ostream* stream,
5935                             const std::string& element_name,
5936                             const std::string& name,
5937                             const std::string& value,
5938                             const std::string& indent,
5939                             bool comma = true);
5940   static void OutputJsonKey(std::ostream* stream,
5941                             const std::string& element_name,
5942                             const std::string& name,
5943                             int value,
5944                             const std::string& indent,
5945                             bool comma = true);
5946 
5947   // Streams a test suite JSON stanza containing the given test result.
5948   //
5949   // Requires: result.Failed()
5950   static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
5951                                                const TestResult& result);
5952 
5953   // Streams a JSON representation of a TestResult object.
5954   static void OutputJsonTestResult(::std::ostream* stream,
5955                                    const TestResult& result);
5956 
5957   // Streams a JSON representation of a TestInfo object.
5958   static void OutputJsonTestInfo(::std::ostream* stream,
5959                                  const char* test_suite_name,
5960                                  const TestInfo& test_info);
5961 
5962   // Prints a JSON representation of a TestSuite object
5963   static void PrintJsonTestSuite(::std::ostream* stream,
5964                                  const TestSuite& test_suite);
5965 
5966   // Prints a JSON summary of unit_test to output stream out.
5967   static void PrintJsonUnitTest(::std::ostream* stream,
5968                                 const UnitTest& unit_test);
5969 
5970   // Produces a string representing the test properties in a result as
5971   // a JSON dictionary.
5972   static std::string TestPropertiesAsJson(const TestResult& result,
5973                                           const std::string& indent);
5974 
5975   // The output file.
5976   const std::string output_file_;
5977 
5978   GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
5979 };
5980 
5981 // Creates a new JsonUnitTestResultPrinter.
JsonUnitTestResultPrinter(const char * output_file)5982 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
5983     : output_file_(output_file) {
5984   if (output_file_.empty()) {
5985     GTEST_LOG_(FATAL) << "JSON output file may not be null";
5986   }
5987 }
5988 
OnTestIterationEnd(const UnitTest & unit_test,int)5989 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5990                                                   int /*iteration*/) {
5991   FILE* jsonout = OpenFileForWriting(output_file_);
5992   std::stringstream stream;
5993   PrintJsonUnitTest(&stream, unit_test);
5994   fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
5995   fclose(jsonout);
5996 }
5997 
5998 // Returns an JSON-escaped copy of the input string str.
EscapeJson(const std::string & str)5999 std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
6000   Message m;
6001 
6002   for (size_t i = 0; i < str.size(); ++i) {
6003     const char ch = str[i];
6004     switch (ch) {
6005       case '\\':
6006       case '"':
6007       case '/':
6008         m << '\\' << ch;
6009         break;
6010       case '\b':
6011         m << "\\b";
6012         break;
6013       case '\t':
6014         m << "\\t";
6015         break;
6016       case '\n':
6017         m << "\\n";
6018         break;
6019       case '\f':
6020         m << "\\f";
6021         break;
6022       case '\r':
6023         m << "\\r";
6024         break;
6025       default:
6026         if (ch < ' ') {
6027           m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
6028         } else {
6029           m << ch;
6030         }
6031         break;
6032     }
6033   }
6034 
6035   return m.GetString();
6036 }
6037 
6038 // The following routines generate an JSON representation of a UnitTest
6039 // object.
6040 
6041 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsDuration(TimeInMillis ms)6042 static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
6043   ::std::stringstream ss;
6044   ss << (static_cast<double>(ms) * 1e-3) << "s";
6045   return ss.str();
6046 }
6047 
6048 // Converts the given epoch time in milliseconds to a date string in the
6049 // RFC3339 format, without the timezone information.
FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms)6050 static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
6051   struct tm time_struct;
6052   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
6053     return "";
6054   // YYYY-MM-DDThh:mm:ss
6055   return StreamableToString(time_struct.tm_year + 1900) + "-" +
6056       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
6057       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
6058       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
6059       String::FormatIntWidth2(time_struct.tm_min) + ":" +
6060       String::FormatIntWidth2(time_struct.tm_sec) + "Z";
6061 }
6062 
Indent(size_t width)6063 static inline std::string Indent(size_t width) {
6064   return std::string(width, ' ');
6065 }
6066 
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value,const std::string & indent,bool comma)6067 void JsonUnitTestResultPrinter::OutputJsonKey(
6068     std::ostream* stream,
6069     const std::string& element_name,
6070     const std::string& name,
6071     const std::string& value,
6072     const std::string& indent,
6073     bool comma) {
6074   const std::vector<std::string>& allowed_names =
6075       GetReservedOutputAttributesForElement(element_name);
6076 
6077   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
6078                    allowed_names.end())
6079       << "Key \"" << name << "\" is not allowed for value \"" << element_name
6080       << "\".";
6081 
6082   *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
6083   if (comma)
6084     *stream << ",\n";
6085 }
6086 
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,int value,const std::string & indent,bool comma)6087 void JsonUnitTestResultPrinter::OutputJsonKey(
6088     std::ostream* stream,
6089     const std::string& element_name,
6090     const std::string& name,
6091     int value,
6092     const std::string& indent,
6093     bool comma) {
6094   const std::vector<std::string>& allowed_names =
6095       GetReservedOutputAttributesForElement(element_name);
6096 
6097   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
6098                    allowed_names.end())
6099       << "Key \"" << name << "\" is not allowed for value \"" << element_name
6100       << "\".";
6101 
6102   *stream << indent << "\"" << name << "\": " << StreamableToString(value);
6103   if (comma)
6104     *stream << ",\n";
6105 }
6106 
6107 // Streams a test suite JSON stanza containing the given test result.
OutputJsonTestSuiteForTestResult(::std::ostream * stream,const TestResult & result)6108 void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
6109     ::std::ostream* stream, const TestResult& result) {
6110   // Output the boilerplate for a new test suite.
6111   *stream << Indent(4) << "{\n";
6112   OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
6113   OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
6114   if (!GTEST_FLAG(list_tests)) {
6115     OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
6116     OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
6117     OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
6118     OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
6119     OutputJsonKey(stream, "testsuite", "time",
6120                   FormatTimeInMillisAsDuration(result.elapsed_time()),
6121                   Indent(6));
6122     OutputJsonKey(stream, "testsuite", "timestamp",
6123                   FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
6124                   Indent(6));
6125   }
6126   *stream << Indent(6) << "\"testsuite\": [\n";
6127 
6128   // Output the boilerplate for a new test case.
6129   *stream << Indent(8) << "{\n";
6130   OutputJsonKey(stream, "testcase", "name", "", Indent(10));
6131   OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
6132   OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
6133   OutputJsonKey(stream, "testcase", "timestamp",
6134                 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
6135                 Indent(10));
6136   OutputJsonKey(stream, "testcase", "time",
6137                 FormatTimeInMillisAsDuration(result.elapsed_time()),
6138                 Indent(10));
6139   OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
6140   *stream << TestPropertiesAsJson(result, Indent(10));
6141 
6142   // Output the actual test result.
6143   OutputJsonTestResult(stream, result);
6144 
6145   // Finish the test suite.
6146   *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
6147 }
6148 
6149 // Prints a JSON representation of a TestInfo object.
OutputJsonTestInfo(::std::ostream * stream,const char * test_suite_name,const TestInfo & test_info)6150 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
6151                                                    const char* test_suite_name,
6152                                                    const TestInfo& test_info) {
6153   const TestResult& result = *test_info.result();
6154   const std::string kTestsuite = "testcase";
6155   const std::string kIndent = Indent(10);
6156 
6157   *stream << Indent(8) << "{\n";
6158   OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
6159 
6160   if (test_info.value_param() != nullptr) {
6161     OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
6162                   kIndent);
6163   }
6164   if (test_info.type_param() != nullptr) {
6165     OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
6166                   kIndent);
6167   }
6168   if (GTEST_FLAG(list_tests)) {
6169     OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
6170     OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
6171     *stream << "\n" << Indent(8) << "}";
6172     return;
6173   }
6174 
6175   OutputJsonKey(stream, kTestsuite, "status",
6176                 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
6177   OutputJsonKey(stream, kTestsuite, "result",
6178                 test_info.should_run()
6179                     ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
6180                     : "SUPPRESSED",
6181                 kIndent);
6182   OutputJsonKey(stream, kTestsuite, "timestamp",
6183                 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
6184                 kIndent);
6185   OutputJsonKey(stream, kTestsuite, "time",
6186                 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
6187   OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
6188                 false);
6189   *stream << TestPropertiesAsJson(result, kIndent);
6190 
6191   OutputJsonTestResult(stream, result);
6192 }
6193 
OutputJsonTestResult(::std::ostream * stream,const TestResult & result)6194 void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
6195                                                      const TestResult& result) {
6196   const std::string kIndent = Indent(10);
6197 
6198   int failures = 0;
6199   for (int i = 0; i < result.total_part_count(); ++i) {
6200     const TestPartResult& part = result.GetTestPartResult(i);
6201     if (part.failed()) {
6202       *stream << ",\n";
6203       if (++failures == 1) {
6204         *stream << kIndent << "\"" << "failures" << "\": [\n";
6205       }
6206       const std::string location =
6207           internal::FormatCompilerIndependentFileLocation(part.file_name(),
6208                                                           part.line_number());
6209       const std::string message = EscapeJson(location + "\n" + part.message());
6210       *stream << kIndent << "  {\n"
6211               << kIndent << "    \"failure\": \"" << message << "\",\n"
6212               << kIndent << "    \"type\": \"\"\n"
6213               << kIndent << "  }";
6214     }
6215   }
6216 
6217   if (failures > 0)
6218     *stream << "\n" << kIndent << "]";
6219   *stream << "\n" << Indent(8) << "}";
6220 }
6221 
6222 // Prints an JSON representation of a TestSuite object
PrintJsonTestSuite(std::ostream * stream,const TestSuite & test_suite)6223 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
6224     std::ostream* stream, const TestSuite& test_suite) {
6225   const std::string kTestsuite = "testsuite";
6226   const std::string kIndent = Indent(6);
6227 
6228   *stream << Indent(4) << "{\n";
6229   OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
6230   OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
6231                 kIndent);
6232   if (!GTEST_FLAG(list_tests)) {
6233     OutputJsonKey(stream, kTestsuite, "failures",
6234                   test_suite.failed_test_count(), kIndent);
6235     OutputJsonKey(stream, kTestsuite, "disabled",
6236                   test_suite.reportable_disabled_test_count(), kIndent);
6237     OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
6238     OutputJsonKey(
6239         stream, kTestsuite, "timestamp",
6240         FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
6241         kIndent);
6242     OutputJsonKey(stream, kTestsuite, "time",
6243                   FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
6244                   kIndent, false);
6245     *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
6246             << ",\n";
6247   }
6248 
6249   *stream << kIndent << "\"" << kTestsuite << "\": [\n";
6250 
6251   bool comma = false;
6252   for (int i = 0; i < test_suite.total_test_count(); ++i) {
6253     if (test_suite.GetTestInfo(i)->is_reportable()) {
6254       if (comma) {
6255         *stream << ",\n";
6256       } else {
6257         comma = true;
6258       }
6259       OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
6260     }
6261   }
6262   *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
6263 }
6264 
6265 // Prints a JSON summary of unit_test to output stream out.
PrintJsonUnitTest(std::ostream * stream,const UnitTest & unit_test)6266 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
6267                                                   const UnitTest& unit_test) {
6268   const std::string kTestsuites = "testsuites";
6269   const std::string kIndent = Indent(2);
6270   *stream << "{\n";
6271 
6272   OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
6273                 kIndent);
6274   OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
6275                 kIndent);
6276   OutputJsonKey(stream, kTestsuites, "disabled",
6277                 unit_test.reportable_disabled_test_count(), kIndent);
6278   OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
6279   if (GTEST_FLAG(shuffle)) {
6280     OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
6281                   kIndent);
6282   }
6283   OutputJsonKey(stream, kTestsuites, "timestamp",
6284                 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
6285                 kIndent);
6286   OutputJsonKey(stream, kTestsuites, "time",
6287                 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
6288                 false);
6289 
6290   *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
6291           << ",\n";
6292 
6293   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
6294   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
6295 
6296   bool comma = false;
6297   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
6298     if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
6299       if (comma) {
6300         *stream << ",\n";
6301       } else {
6302         comma = true;
6303       }
6304       PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
6305     }
6306   }
6307 
6308   // If there was a test failure outside of one of the test suites (like in a
6309   // test environment) include that in the output.
6310   if (unit_test.ad_hoc_test_result().Failed()) {
6311     OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
6312   }
6313 
6314   *stream << "\n" << kIndent << "]\n" << "}\n";
6315 }
6316 
PrintJsonTestList(std::ostream * stream,const std::vector<TestSuite * > & test_suites)6317 void JsonUnitTestResultPrinter::PrintJsonTestList(
6318     std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
6319   const std::string kTestsuites = "testsuites";
6320   const std::string kIndent = Indent(2);
6321   *stream << "{\n";
6322   int total_tests = 0;
6323   for (auto test_suite : test_suites) {
6324     total_tests += test_suite->total_test_count();
6325   }
6326   OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
6327 
6328   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
6329   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
6330 
6331   for (size_t i = 0; i < test_suites.size(); ++i) {
6332     if (i != 0) {
6333       *stream << ",\n";
6334     }
6335     PrintJsonTestSuite(stream, *test_suites[i]);
6336   }
6337 
6338   *stream << "\n"
6339           << kIndent << "]\n"
6340           << "}\n";
6341 }
6342 // Produces a string representing the test properties in a result as
6343 // a JSON dictionary.
TestPropertiesAsJson(const TestResult & result,const std::string & indent)6344 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
6345     const TestResult& result, const std::string& indent) {
6346   Message attributes;
6347   for (int i = 0; i < result.test_property_count(); ++i) {
6348     const TestProperty& property = result.GetTestProperty(i);
6349     attributes << ",\n" << indent << "\"" << property.key() << "\": "
6350                << "\"" << EscapeJson(property.value()) << "\"";
6351   }
6352   return attributes.GetString();
6353 }
6354 
6355 // End JsonUnitTestResultPrinter
6356 
6357 #if GTEST_CAN_STREAM_RESULTS_
6358 
6359 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
6360 // replaces them by "%xx" where xx is their hexadecimal value. For
6361 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
6362 // in both time and space -- important as the input str may contain an
6363 // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)6364 std::string StreamingListener::UrlEncode(const char* str) {
6365   std::string result;
6366   result.reserve(strlen(str) + 1);
6367   for (char ch = *str; ch != '\0'; ch = *++str) {
6368     switch (ch) {
6369       case '%':
6370       case '=':
6371       case '&':
6372       case '\n':
6373         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
6374         break;
6375       default:
6376         result.push_back(ch);
6377         break;
6378     }
6379   }
6380   return result;
6381 }
6382 
MakeConnection()6383 void StreamingListener::SocketWriter::MakeConnection() {
6384   GTEST_CHECK_(sockfd_ == -1)
6385       << "MakeConnection() can't be called when there is already a connection.";
6386 
6387   addrinfo hints;
6388   memset(&hints, 0, sizeof(hints));
6389   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
6390   hints.ai_socktype = SOCK_STREAM;
6391   addrinfo* servinfo = nullptr;
6392 
6393   // Use the getaddrinfo() to get a linked list of IP addresses for
6394   // the given host name.
6395   const int error_num = getaddrinfo(
6396       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
6397   if (error_num != 0) {
6398     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
6399                         << gai_strerror(error_num);
6400   }
6401 
6402   // Loop through all the results and connect to the first we can.
6403   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
6404        cur_addr = cur_addr->ai_next) {
6405     sockfd_ = socket(
6406         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
6407     if (sockfd_ != -1) {
6408       // Connect the client socket to the server socket.
6409       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
6410         close(sockfd_);
6411         sockfd_ = -1;
6412       }
6413     }
6414   }
6415 
6416   freeaddrinfo(servinfo);  // all done with this structure
6417 
6418   if (sockfd_ == -1) {
6419     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
6420                         << host_name_ << ":" << port_num_;
6421   }
6422 }
6423 
6424 // End of class Streaming Listener
6425 #endif  // GTEST_CAN_STREAM_RESULTS__
6426 
6427 // class OsStackTraceGetter
6428 
6429 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
6430     "... " GTEST_NAME_ " internal frames ...";
6431 
CurrentStackTrace(int max_depth,int skip_count)6432 std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
6433     GTEST_LOCK_EXCLUDED_(mutex_) {
6434 #if GTEST_HAS_ABSL
6435   std::string result;
6436 
6437   if (max_depth <= 0) {
6438     return result;
6439   }
6440 
6441   max_depth = std::min(max_depth, kMaxStackTraceDepth);
6442 
6443   std::vector<void*> raw_stack(max_depth);
6444   // Skips the frames requested by the caller, plus this function.
6445   const int raw_stack_size =
6446       absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
6447 
6448   void* caller_frame = nullptr;
6449   {
6450     MutexLock lock(&mutex_);
6451     caller_frame = caller_frame_;
6452   }
6453 
6454   for (int i = 0; i < raw_stack_size; ++i) {
6455     if (raw_stack[i] == caller_frame &&
6456         !GTEST_FLAG(show_internal_stack_frames)) {
6457       // Add a marker to the trace and stop adding frames.
6458       absl::StrAppend(&result, kElidedFramesMarker, "\n");
6459       break;
6460     }
6461 
6462     char tmp[1024];
6463     const char* symbol = "(unknown)";
6464     if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
6465       symbol = tmp;
6466     }
6467 
6468     char line[1024];
6469     snprintf(line, sizeof(line), "  %p: %s\n", raw_stack[i], symbol);
6470     result += line;
6471   }
6472 
6473   return result;
6474 
6475 #else  // !GTEST_HAS_ABSL
6476   static_cast<void>(max_depth);
6477   static_cast<void>(skip_count);
6478   return "";
6479 #endif  // GTEST_HAS_ABSL
6480 }
6481 
UponLeavingGTest()6482 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
6483 #if GTEST_HAS_ABSL
6484   void* caller_frame = nullptr;
6485   if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
6486     caller_frame = nullptr;
6487   }
6488 
6489   MutexLock lock(&mutex_);
6490   caller_frame_ = caller_frame;
6491 #endif  // GTEST_HAS_ABSL
6492 }
6493 
6494 // A helper class that creates the premature-exit file in its
6495 // constructor and deletes the file in its destructor.
6496 class ScopedPrematureExitFile {
6497  public:
ScopedPrematureExitFile(const char * premature_exit_filepath)6498   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
6499       : premature_exit_filepath_(premature_exit_filepath ?
6500                                  premature_exit_filepath : "") {
6501     // If a path to the premature-exit file is specified...
6502     if (!premature_exit_filepath_.empty()) {
6503       // create the file with a single "0" character in it.  I/O
6504       // errors are ignored as there's nothing better we can do and we
6505       // don't want to fail the test because of this.
6506       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
6507       fwrite("0", 1, 1, pfile);
6508       fclose(pfile);
6509     }
6510   }
6511 
~ScopedPrematureExitFile()6512   ~ScopedPrematureExitFile() {
6513 #if !defined GTEST_OS_ESP8266
6514     if (!premature_exit_filepath_.empty()) {
6515       int retval = remove(premature_exit_filepath_.c_str());
6516       if (retval) {
6517         GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
6518                           << premature_exit_filepath_ << "\" with error "
6519                           << retval;
6520       }
6521     }
6522 #endif
6523   }
6524 
6525  private:
6526   const std::string premature_exit_filepath_;
6527 
6528   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
6529 };
6530 
6531 }  // namespace internal
6532 
6533 // class TestEventListeners
6534 
TestEventListeners()6535 TestEventListeners::TestEventListeners()
6536     : repeater_(new internal::TestEventRepeater()),
6537       default_result_printer_(nullptr),
6538       default_xml_generator_(nullptr) {}
6539 
~TestEventListeners()6540 TestEventListeners::~TestEventListeners() { delete repeater_; }
6541 
6542 // Returns the standard listener responsible for the default console
6543 // output.  Can be removed from the listeners list to shut down default
6544 // console output.  Note that removing this object from the listener list
6545 // with Release transfers its ownership to the user.
Append(TestEventListener * listener)6546 void TestEventListeners::Append(TestEventListener* listener) {
6547   repeater_->Append(listener);
6548 }
6549 
6550 // Removes the given event listener from the list and returns it.  It then
6551 // becomes the caller's responsibility to delete the listener. Returns
6552 // NULL if the listener is not found in the list.
Release(TestEventListener * listener)6553 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
6554   if (listener == default_result_printer_)
6555     default_result_printer_ = nullptr;
6556   else if (listener == default_xml_generator_)
6557     default_xml_generator_ = nullptr;
6558   return repeater_->Release(listener);
6559 }
6560 
6561 // Returns repeater that broadcasts the TestEventListener events to all
6562 // subscribers.
repeater()6563 TestEventListener* TestEventListeners::repeater() { return repeater_; }
6564 
6565 // Sets the default_result_printer attribute to the provided listener.
6566 // The listener is also added to the listener list and previous
6567 // default_result_printer is removed from it and deleted. The listener can
6568 // also be NULL in which case it will not be added to the list. Does
6569 // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)6570 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
6571   if (default_result_printer_ != listener) {
6572     // It is an error to pass this method a listener that is already in the
6573     // list.
6574     delete Release(default_result_printer_);
6575     default_result_printer_ = listener;
6576     if (listener != nullptr) Append(listener);
6577   }
6578 }
6579 
6580 // Sets the default_xml_generator attribute to the provided listener.  The
6581 // listener is also added to the listener list and previous
6582 // default_xml_generator is removed from it and deleted. The listener can
6583 // also be NULL in which case it will not be added to the list. Does
6584 // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)6585 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
6586   if (default_xml_generator_ != listener) {
6587     // It is an error to pass this method a listener that is already in the
6588     // list.
6589     delete Release(default_xml_generator_);
6590     default_xml_generator_ = listener;
6591     if (listener != nullptr) Append(listener);
6592   }
6593 }
6594 
6595 // Controls whether events will be forwarded by the repeater to the
6596 // listeners in the list.
EventForwardingEnabled() const6597 bool TestEventListeners::EventForwardingEnabled() const {
6598   return repeater_->forwarding_enabled();
6599 }
6600 
SuppressEventForwarding()6601 void TestEventListeners::SuppressEventForwarding() {
6602   repeater_->set_forwarding_enabled(false);
6603 }
6604 
6605 // class UnitTest
6606 
6607 // Gets the singleton UnitTest object.  The first time this method is
6608 // called, a UnitTest object is constructed and returned.  Consecutive
6609 // calls will return the same object.
6610 //
6611 // We don't protect this under mutex_ as a user is not supposed to
6612 // call this before main() starts, from which point on the return
6613 // value will never change.
GetInstance()6614 UnitTest* UnitTest::GetInstance() {
6615   // CodeGear C++Builder insists on a public destructor for the
6616   // default implementation.  Use this implementation to keep good OO
6617   // design with private destructor.
6618 
6619 #if defined(__BORLANDC__)
6620   static UnitTest* const instance = new UnitTest;
6621   return instance;
6622 #else
6623   static UnitTest instance;
6624   return &instance;
6625 #endif  // defined(__BORLANDC__)
6626 }
6627 
6628 // Gets the number of successful test suites.
successful_test_suite_count() const6629 int UnitTest::successful_test_suite_count() const {
6630   return impl()->successful_test_suite_count();
6631 }
6632 
6633 // Gets the number of failed test suites.
failed_test_suite_count() const6634 int UnitTest::failed_test_suite_count() const {
6635   return impl()->failed_test_suite_count();
6636 }
6637 
6638 // Gets the number of all test suites.
total_test_suite_count() const6639 int UnitTest::total_test_suite_count() const {
6640   return impl()->total_test_suite_count();
6641 }
6642 
6643 // Gets the number of all test suites that contain at least one test
6644 // that should run.
test_suite_to_run_count() const6645 int UnitTest::test_suite_to_run_count() const {
6646   return impl()->test_suite_to_run_count();
6647 }
6648 
6649 //  Legacy API is deprecated but still available
6650 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
successful_test_case_count() const6651 int UnitTest::successful_test_case_count() const {
6652   return impl()->successful_test_suite_count();
6653 }
failed_test_case_count() const6654 int UnitTest::failed_test_case_count() const {
6655   return impl()->failed_test_suite_count();
6656 }
total_test_case_count() const6657 int UnitTest::total_test_case_count() const {
6658   return impl()->total_test_suite_count();
6659 }
test_case_to_run_count() const6660 int UnitTest::test_case_to_run_count() const {
6661   return impl()->test_suite_to_run_count();
6662 }
6663 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6664 
6665 // Gets the number of successful tests.
successful_test_count() const6666 int UnitTest::successful_test_count() const {
6667   return impl()->successful_test_count();
6668 }
6669 
6670 // Gets the number of skipped tests.
skipped_test_count() const6671 int UnitTest::skipped_test_count() const {
6672   return impl()->skipped_test_count();
6673 }
6674 
6675 // Gets the number of failed tests.
failed_test_count() const6676 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
6677 
6678 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const6679 int UnitTest::reportable_disabled_test_count() const {
6680   return impl()->reportable_disabled_test_count();
6681 }
6682 
6683 // Gets the number of disabled tests.
disabled_test_count() const6684 int UnitTest::disabled_test_count() const {
6685   return impl()->disabled_test_count();
6686 }
6687 
6688 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const6689 int UnitTest::reportable_test_count() const {
6690   return impl()->reportable_test_count();
6691 }
6692 
6693 // Gets the number of all tests.
total_test_count() const6694 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
6695 
6696 // Gets the number of tests that should run.
test_to_run_count() const6697 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
6698 
6699 // Gets the time of the test program start, in ms from the start of the
6700 // UNIX epoch.
start_timestamp() const6701 internal::TimeInMillis UnitTest::start_timestamp() const {
6702     return impl()->start_timestamp();
6703 }
6704 
6705 // Gets the elapsed time, in milliseconds.
elapsed_time() const6706 internal::TimeInMillis UnitTest::elapsed_time() const {
6707   return impl()->elapsed_time();
6708 }
6709 
6710 // Returns true if and only if the unit test passed (i.e. all test suites
6711 // passed).
Passed() const6712 bool UnitTest::Passed() const { return impl()->Passed(); }
6713 
6714 // Returns true if and only if the unit test failed (i.e. some test suite
6715 // failed or something outside of all tests failed).
Failed() const6716 bool UnitTest::Failed() const { return impl()->Failed(); }
6717 
6718 // Gets the i-th test suite among all the test suites. i can range from 0 to
6719 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetTestSuite(int i) const6720 const TestSuite* UnitTest::GetTestSuite(int i) const {
6721   return impl()->GetTestSuite(i);
6722 }
6723 
6724 //  Legacy API is deprecated but still available
6725 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(int i) const6726 const TestCase* UnitTest::GetTestCase(int i) const {
6727   return impl()->GetTestCase(i);
6728 }
6729 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6730 
6731 // Returns the TestResult containing information on test failures and
6732 // properties logged outside of individual test suites.
ad_hoc_test_result() const6733 const TestResult& UnitTest::ad_hoc_test_result() const {
6734   return *impl()->ad_hoc_test_result();
6735 }
6736 
6737 // Gets the i-th test suite among all the test suites. i can range from 0 to
6738 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetMutableTestSuite(int i)6739 TestSuite* UnitTest::GetMutableTestSuite(int i) {
6740   return impl()->GetMutableSuiteCase(i);
6741 }
6742 
6743 // Returns the list of event listeners that can be used to track events
6744 // inside Google Test.
listeners()6745 TestEventListeners& UnitTest::listeners() {
6746   return *impl()->listeners();
6747 }
6748 
6749 // Registers and returns a global test environment.  When a test
6750 // program is run, all global test environments will be set-up in the
6751 // order they were registered.  After all tests in the program have
6752 // finished, all global test environments will be torn-down in the
6753 // *reverse* order they were registered.
6754 //
6755 // The UnitTest object takes ownership of the given environment.
6756 //
6757 // We don't protect this under mutex_, as we only support calling it
6758 // from the main thread.
AddEnvironment(Environment * env)6759 Environment* UnitTest::AddEnvironment(Environment* env) {
6760   if (env == nullptr) {
6761     return nullptr;
6762   }
6763 
6764   impl_->environments().push_back(env);
6765   return env;
6766 }
6767 
6768 // Adds a TestPartResult to the current TestResult object.  All Google Test
6769 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
6770 // this to report their results.  The user code should use the
6771 // assertion macros instead of calling this directly.
AddTestPartResult(TestPartResult::Type result_type,const char * file_name,int line_number,const std::string & message,const std::string & os_stack_trace)6772 void UnitTest::AddTestPartResult(
6773     TestPartResult::Type result_type,
6774     const char* file_name,
6775     int line_number,
6776     const std::string& message,
6777     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
6778   Message msg;
6779   msg << message;
6780 
6781   internal::MutexLock lock(&mutex_);
6782   if (impl_->gtest_trace_stack().size() > 0) {
6783     msg << "\n" << GTEST_NAME_ << " trace:";
6784 
6785     for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
6786       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6787       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
6788           << " " << trace.message;
6789     }
6790   }
6791 
6792   if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
6793     msg << internal::kStackTraceMarker << os_stack_trace;
6794   }
6795 
6796   const TestPartResult result = TestPartResult(
6797       result_type, file_name, line_number, msg.GetString().c_str());
6798   impl_->GetTestPartResultReporterForCurrentThread()->
6799       ReportTestPartResult(result);
6800 
6801   if (result_type != TestPartResult::kSuccess &&
6802       result_type != TestPartResult::kSkip) {
6803     // gtest_break_on_failure takes precedence over
6804     // gtest_throw_on_failure.  This allows a user to set the latter
6805     // in the code (perhaps in order to use Google Test assertions
6806     // with another testing framework) and specify the former on the
6807     // command line for debugging.
6808     if (GTEST_FLAG(break_on_failure)) {
6809 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6810       // Using DebugBreak on Windows allows gtest to still break into a debugger
6811       // when a failure happens and both the --gtest_break_on_failure and
6812       // the --gtest_catch_exceptions flags are specified.
6813       DebugBreak();
6814 #elif (!defined(__native_client__)) &&            \
6815     ((defined(__clang__) || defined(__GNUC__)) && \
6816      (defined(__x86_64__) || defined(__i386__)))
6817       // with clang/gcc we can achieve the same effect on x86 by invoking int3
6818       asm("int3");
6819 #else
6820       // Dereference nullptr through a volatile pointer to prevent the compiler
6821       // from removing. We use this rather than abort() or __builtin_trap() for
6822       // portability: some debuggers don't correctly trap abort().
6823       *static_cast<volatile int*>(nullptr) = 1;
6824 #endif  // GTEST_OS_WINDOWS
6825     } else if (GTEST_FLAG(throw_on_failure)) {
6826 #if GTEST_HAS_EXCEPTIONS
6827       throw internal::GoogleTestFailureException(result);
6828 #else
6829       // We cannot call abort() as it generates a pop-up in debug mode
6830       // that cannot be suppressed in VC 7.1 or below.
6831       exit(1);
6832 #endif
6833     }
6834   }
6835 }
6836 
6837 // Adds a TestProperty to the current TestResult object when invoked from
6838 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
6839 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
6840 // when invoked elsewhere.  If the result already contains a property with
6841 // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)6842 void UnitTest::RecordProperty(const std::string& key,
6843                               const std::string& value) {
6844   impl_->RecordProperty(TestProperty(key, value));
6845 }
6846 
6847 // Runs all tests in this UnitTest object and prints the result.
6848 // Returns 0 if successful, or 1 otherwise.
6849 //
6850 // We don't protect this under mutex_, as we only support calling it
6851 // from the main thread.
Run()6852 int UnitTest::Run() {
6853   const bool in_death_test_child_process =
6854       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
6855 
6856   // Google Test implements this protocol for catching that a test
6857   // program exits before returning control to Google Test:
6858   //
6859   //   1. Upon start, Google Test creates a file whose absolute path
6860   //      is specified by the environment variable
6861   //      TEST_PREMATURE_EXIT_FILE.
6862   //   2. When Google Test has finished its work, it deletes the file.
6863   //
6864   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
6865   // running a Google-Test-based test program and check the existence
6866   // of the file at the end of the test execution to see if it has
6867   // exited prematurely.
6868 
6869   // If we are in the child process of a death test, don't
6870   // create/delete the premature exit file, as doing so is unnecessary
6871   // and will confuse the parent process.  Otherwise, create/delete
6872   // the file upon entering/leaving this function.  If the program
6873   // somehow exits before this function has a chance to return, the
6874   // premature-exit file will be left undeleted, causing a test runner
6875   // that understands the premature-exit-file protocol to report the
6876   // test as having failed.
6877   const internal::ScopedPrematureExitFile premature_exit_file(
6878       in_death_test_child_process
6879           ? nullptr
6880           : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
6881 
6882   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
6883   // used for the duration of the program.
6884   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
6885 
6886 #if GTEST_OS_WINDOWS
6887   // Either the user wants Google Test to catch exceptions thrown by the
6888   // tests or this is executing in the context of death test child
6889   // process. In either case the user does not want to see pop-up dialogs
6890   // about crashes - they are expected.
6891   if (impl()->catch_exceptions() || in_death_test_child_process) {
6892 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6893     // SetErrorMode doesn't exist on CE.
6894     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6895                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6896 # endif  // !GTEST_OS_WINDOWS_MOBILE
6897 
6898 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
6899     // Death test children can be terminated with _abort().  On Windows,
6900     // _abort() can show a dialog with a warning message.  This forces the
6901     // abort message to go to stderr instead.
6902     _set_error_mode(_OUT_TO_STDERR);
6903 # endif
6904 
6905 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
6906     // In the debug version, Visual Studio pops up a separate dialog
6907     // offering a choice to debug the aborted program. We need to suppress
6908     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
6909     // executed. Google Test will notify the user of any unexpected
6910     // failure via stderr.
6911     if (!GTEST_FLAG(break_on_failure))
6912       _set_abort_behavior(
6913           0x0,                                    // Clear the following flags:
6914           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
6915 
6916     // In debug mode, the Windows CRT can crash with an assertion over invalid
6917     // input (e.g. passing an invalid file descriptor).  The default handling
6918     // for these assertions is to pop up a dialog and wait for user input.
6919     // Instead ask the CRT to dump such assertions to stderr non-interactively.
6920     if (!IsDebuggerPresent()) {
6921       (void)_CrtSetReportMode(_CRT_ASSERT,
6922                               _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
6923       (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
6924     }
6925 # endif
6926   }
6927 #endif  // GTEST_OS_WINDOWS
6928 
6929   return internal::HandleExceptionsInMethodIfSupported(
6930       impl(),
6931       &internal::UnitTestImpl::RunAllTests,
6932       "auxiliary test code (environments or event listeners)") ? 0 : 1;
6933 }
6934 
6935 // Returns the working directory when the first TEST() or TEST_F() was
6936 // executed.
original_working_dir() const6937 const char* UnitTest::original_working_dir() const {
6938   return impl_->original_working_dir_.c_str();
6939 }
6940 
6941 // Returns the TestSuite object for the test that's currently running,
6942 // or NULL if no test is running.
current_test_suite() const6943 const TestSuite* UnitTest::current_test_suite() const
6944     GTEST_LOCK_EXCLUDED_(mutex_) {
6945   internal::MutexLock lock(&mutex_);
6946   return impl_->current_test_suite();
6947 }
6948 
6949 // Legacy API is still available but deprecated
6950 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
current_test_case() const6951 const TestCase* UnitTest::current_test_case() const
6952     GTEST_LOCK_EXCLUDED_(mutex_) {
6953   internal::MutexLock lock(&mutex_);
6954   return impl_->current_test_suite();
6955 }
6956 #endif
6957 
6958 // Returns the TestInfo object for the test that's currently running,
6959 // or NULL if no test is running.
current_test_info() const6960 const TestInfo* UnitTest::current_test_info() const
6961     GTEST_LOCK_EXCLUDED_(mutex_) {
6962   internal::MutexLock lock(&mutex_);
6963   return impl_->current_test_info();
6964 }
6965 
6966 // Returns the random seed used at the start of the current test run.
random_seed() const6967 int UnitTest::random_seed() const { return impl_->random_seed(); }
6968 
6969 // Returns ParameterizedTestSuiteRegistry object used to keep track of
6970 // value-parameterized tests and instantiate and register them.
6971 internal::ParameterizedTestSuiteRegistry&
parameterized_test_registry()6972 UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
6973   return impl_->parameterized_test_registry();
6974 }
6975 
6976 // Creates an empty UnitTest.
UnitTest()6977 UnitTest::UnitTest() {
6978   impl_ = new internal::UnitTestImpl(this);
6979 }
6980 
6981 // Destructor of UnitTest.
~UnitTest()6982 UnitTest::~UnitTest() {
6983   delete impl_;
6984 }
6985 
6986 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
6987 // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)6988 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
6989     GTEST_LOCK_EXCLUDED_(mutex_) {
6990   internal::MutexLock lock(&mutex_);
6991   impl_->gtest_trace_stack().push_back(trace);
6992 }
6993 
6994 // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()6995 void UnitTest::PopGTestTrace()
6996     GTEST_LOCK_EXCLUDED_(mutex_) {
6997   internal::MutexLock lock(&mutex_);
6998   impl_->gtest_trace_stack().pop_back();
6999 }
7000 
7001 namespace internal {
7002 
UnitTestImpl(UnitTest * parent)7003 UnitTestImpl::UnitTestImpl(UnitTest* parent)
7004     : parent_(parent),
7005       GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
7006           default_global_test_part_result_reporter_(this),
7007       default_per_thread_test_part_result_reporter_(this),
7008       GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
7009           &default_global_test_part_result_reporter_),
7010       per_thread_test_part_result_reporter_(
7011           &default_per_thread_test_part_result_reporter_),
7012       parameterized_test_registry_(),
7013       parameterized_tests_registered_(false),
7014       last_death_test_suite_(-1),
7015       current_test_suite_(nullptr),
7016       current_test_info_(nullptr),
7017       ad_hoc_test_result_(),
7018       os_stack_trace_getter_(nullptr),
7019       post_flag_parse_init_performed_(false),
7020       random_seed_(0),  // Will be overridden by the flag before first use.
7021       random_(0),       // Will be reseeded before first use.
7022       start_timestamp_(0),
7023       elapsed_time_(0),
7024 #if GTEST_HAS_DEATH_TEST
7025       death_test_factory_(new DefaultDeathTestFactory),
7026 #endif
7027       // Will be overridden by the flag before first use.
7028       catch_exceptions_(false) {
7029   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
7030 }
7031 
~UnitTestImpl()7032 UnitTestImpl::~UnitTestImpl() {
7033   // Deletes every TestSuite.
7034   ForEach(test_suites_, internal::Delete<TestSuite>);
7035 
7036   // Deletes every Environment.
7037   ForEach(environments_, internal::Delete<Environment>);
7038 
7039   delete os_stack_trace_getter_;
7040 }
7041 
7042 // Adds a TestProperty to the current TestResult object when invoked in a
7043 // context of a test, to current test suite's ad_hoc_test_result when invoke
7044 // from SetUpTestSuite/TearDownTestSuite, or to the global property set
7045 // otherwise.  If the result already contains a property with the same key,
7046 // the value will be updated.
RecordProperty(const TestProperty & test_property)7047 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
7048   std::string xml_element;
7049   TestResult* test_result;  // TestResult appropriate for property recording.
7050 
7051   if (current_test_info_ != nullptr) {
7052     xml_element = "testcase";
7053     test_result = &(current_test_info_->result_);
7054   } else if (current_test_suite_ != nullptr) {
7055     xml_element = "testsuite";
7056     test_result = &(current_test_suite_->ad_hoc_test_result_);
7057   } else {
7058     xml_element = "testsuites";
7059     test_result = &ad_hoc_test_result_;
7060   }
7061   test_result->RecordProperty(xml_element, test_property);
7062 }
7063 
7064 #if GTEST_HAS_DEATH_TEST
7065 // Disables event forwarding if the control is currently in a death test
7066 // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()7067 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
7068   if (internal_run_death_test_flag_.get() != nullptr)
7069     listeners()->SuppressEventForwarding();
7070 }
7071 #endif  // GTEST_HAS_DEATH_TEST
7072 
7073 // Initializes event listeners performing XML output as specified by
7074 // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()7075 void UnitTestImpl::ConfigureXmlOutput() {
7076   const std::string& output_format = UnitTestOptions::GetOutputFormat();
7077   if (output_format == "xml") {
7078     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
7079         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
7080   } else if (output_format == "json") {
7081     listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
7082         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
7083   } else if (output_format != "") {
7084     GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
7085                         << output_format << "\" ignored.";
7086   }
7087 }
7088 
7089 #if GTEST_CAN_STREAM_RESULTS_
7090 // Initializes event listeners for streaming test results in string form.
7091 // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()7092 void UnitTestImpl::ConfigureStreamingOutput() {
7093   const std::string& target = GTEST_FLAG(stream_result_to);
7094   if (!target.empty()) {
7095     const size_t pos = target.find(':');
7096     if (pos != std::string::npos) {
7097       listeners()->Append(new StreamingListener(target.substr(0, pos),
7098                                                 target.substr(pos+1)));
7099     } else {
7100       GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
7101                           << "\" ignored.";
7102     }
7103   }
7104 }
7105 #endif  // GTEST_CAN_STREAM_RESULTS_
7106 
7107 // Performs initialization dependent upon flag values obtained in
7108 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
7109 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
7110 // this function is also called from RunAllTests.  Since this function can be
7111 // called more than once, it has to be idempotent.
PostFlagParsingInit()7112 void UnitTestImpl::PostFlagParsingInit() {
7113   // Ensures that this function does not execute more than once.
7114   if (!post_flag_parse_init_performed_) {
7115     post_flag_parse_init_performed_ = true;
7116 
7117 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
7118     // Register to send notifications about key process state changes.
7119     listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
7120 #endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
7121 
7122 #if GTEST_HAS_DEATH_TEST
7123     InitDeathTestSubprocessControlInfo();
7124     SuppressTestEventsIfInSubprocess();
7125 #endif  // GTEST_HAS_DEATH_TEST
7126 
7127     // Registers parameterized tests. This makes parameterized tests
7128     // available to the UnitTest reflection API without running
7129     // RUN_ALL_TESTS.
7130     RegisterParameterizedTests();
7131 
7132     // Configures listeners for XML output. This makes it possible for users
7133     // to shut down the default XML output before invoking RUN_ALL_TESTS.
7134     ConfigureXmlOutput();
7135 
7136     if (GTEST_FLAG(brief)) {
7137       listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
7138     }
7139 
7140 #if GTEST_CAN_STREAM_RESULTS_
7141     // Configures listeners for streaming test results to the specified server.
7142     ConfigureStreamingOutput();
7143 #endif  // GTEST_CAN_STREAM_RESULTS_
7144 
7145 #if GTEST_HAS_ABSL
7146     if (GTEST_FLAG(install_failure_signal_handler)) {
7147       absl::FailureSignalHandlerOptions options;
7148       absl::InstallFailureSignalHandler(options);
7149     }
7150 #endif  // GTEST_HAS_ABSL
7151   }
7152 }
7153 
7154 // A predicate that checks the name of a TestSuite against a known
7155 // value.
7156 //
7157 // This is used for implementation of the UnitTest class only.  We put
7158 // it in the anonymous namespace to prevent polluting the outer
7159 // namespace.
7160 //
7161 // TestSuiteNameIs is copyable.
7162 class TestSuiteNameIs {
7163  public:
7164   // Constructor.
TestSuiteNameIs(const std::string & name)7165   explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
7166 
7167   // Returns true if and only if the name of test_suite matches name_.
operator ()(const TestSuite * test_suite) const7168   bool operator()(const TestSuite* test_suite) const {
7169     return test_suite != nullptr &&
7170            strcmp(test_suite->name(), name_.c_str()) == 0;
7171   }
7172 
7173  private:
7174   std::string name_;
7175 };
7176 
7177 // Finds and returns a TestSuite with the given name.  If one doesn't
7178 // exist, creates one and returns it.  It's the CALLER'S
7179 // RESPONSIBILITY to ensure that this function is only called WHEN THE
7180 // TESTS ARE NOT SHUFFLED.
7181 //
7182 // Arguments:
7183 //
7184 //   test_suite_name: name of the test suite
7185 //   type_param:      the name of the test suite's type parameter, or NULL if
7186 //                    this is not a typed or a type-parameterized test suite.
7187 //   set_up_tc:       pointer to the function that sets up the test suite
7188 //   tear_down_tc:    pointer to the function that tears down the test suite
GetTestSuite(const char * test_suite_name,const char * type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)7189 TestSuite* UnitTestImpl::GetTestSuite(
7190     const char* test_suite_name, const char* type_param,
7191     internal::SetUpTestSuiteFunc set_up_tc,
7192     internal::TearDownTestSuiteFunc tear_down_tc) {
7193   // Can we find a TestSuite with the given name?
7194   const auto test_suite =
7195       std::find_if(test_suites_.rbegin(), test_suites_.rend(),
7196                    TestSuiteNameIs(test_suite_name));
7197 
7198   if (test_suite != test_suites_.rend()) return *test_suite;
7199 
7200   // No.  Let's create one.
7201   auto* const new_test_suite =
7202       new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
7203 
7204   // Is this a death test suite?
7205   if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
7206                                                kDeathTestSuiteFilter)) {
7207     // Yes.  Inserts the test suite after the last death test suite
7208     // defined so far.  This only works when the test suites haven't
7209     // been shuffled.  Otherwise we may end up running a death test
7210     // after a non-death test.
7211     ++last_death_test_suite_;
7212     test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
7213                         new_test_suite);
7214   } else {
7215     // No.  Appends to the end of the list.
7216     test_suites_.push_back(new_test_suite);
7217   }
7218 
7219   test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
7220   return new_test_suite;
7221 }
7222 
7223 // Helpers for setting up / tearing down the given environment.  They
7224 // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)7225 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)7226 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
7227 
7228 // Runs all tests in this UnitTest object, prints the result, and
7229 // returns true if all tests are successful.  If any exception is
7230 // thrown during a test, the test is considered to be failed, but the
7231 // rest of the tests will still be run.
7232 //
7233 // When parameterized tests are enabled, it expands and registers
7234 // parameterized tests first in RegisterParameterizedTests().
7235 // All other functions called from RunAllTests() may safely assume that
7236 // parameterized tests are ready to be counted and run.
RunAllTests()7237 bool UnitTestImpl::RunAllTests() {
7238   // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
7239   // called.
7240   const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
7241 
7242   // Do not run any test if the --help flag was specified.
7243   if (g_help_flag)
7244     return true;
7245 
7246   // Repeats the call to the post-flag parsing initialization in case the
7247   // user didn't call InitGoogleTest.
7248   PostFlagParsingInit();
7249 
7250   // Even if sharding is not on, test runners may want to use the
7251   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
7252   // protocol.
7253   internal::WriteToShardStatusFileIfNeeded();
7254 
7255   // True if and only if we are in a subprocess for running a thread-safe-style
7256   // death test.
7257   bool in_subprocess_for_death_test = false;
7258 
7259 #if GTEST_HAS_DEATH_TEST
7260   in_subprocess_for_death_test =
7261       (internal_run_death_test_flag_.get() != nullptr);
7262 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
7263   if (in_subprocess_for_death_test) {
7264     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
7265   }
7266 # endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
7267 #endif  // GTEST_HAS_DEATH_TEST
7268 
7269   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
7270                                         in_subprocess_for_death_test);
7271 
7272   // Compares the full test names with the filter to decide which
7273   // tests to run.
7274   const bool has_tests_to_run = FilterTests(should_shard
7275                                               ? HONOR_SHARDING_PROTOCOL
7276                                               : IGNORE_SHARDING_PROTOCOL) > 0;
7277 
7278   // Lists the tests and exits if the --gtest_list_tests flag was specified.
7279   if (GTEST_FLAG(list_tests)) {
7280     // This must be called *after* FilterTests() has been called.
7281     ListTestsMatchingFilter();
7282     return true;
7283   }
7284 
7285   random_seed_ = GTEST_FLAG(shuffle) ?
7286       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
7287 
7288   // True if and only if at least one test has failed.
7289   bool failed = false;
7290 
7291   TestEventListener* repeater = listeners()->repeater();
7292 
7293   start_timestamp_ = GetTimeInMillis();
7294   repeater->OnTestProgramStart(*parent_);
7295 
7296   // How many times to repeat the tests?  We don't want to repeat them
7297   // when we are inside the subprocess of a death test.
7298   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
7299   // Repeats forever if the repeat count is negative.
7300   const bool gtest_repeat_forever = repeat < 0;
7301   for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
7302     // We want to preserve failures generated by ad-hoc test
7303     // assertions executed before RUN_ALL_TESTS().
7304     ClearNonAdHocTestResult();
7305 
7306     Timer timer;
7307 
7308     // Shuffles test suites and tests if requested.
7309     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
7310       random()->Reseed(static_cast<uint32_t>(random_seed_));
7311       // This should be done before calling OnTestIterationStart(),
7312       // such that a test event listener can see the actual test order
7313       // in the event.
7314       ShuffleTests();
7315     }
7316 
7317     // Tells the unit test event listeners that the tests are about to start.
7318     repeater->OnTestIterationStart(*parent_, i);
7319 
7320     // Runs each test suite if there is at least one test to run.
7321     if (has_tests_to_run) {
7322       // Sets up all environments beforehand.
7323       repeater->OnEnvironmentsSetUpStart(*parent_);
7324       ForEach(environments_, SetUpEnvironment);
7325       repeater->OnEnvironmentsSetUpEnd(*parent_);
7326 
7327       // Runs the tests only if there was no fatal failure or skip triggered
7328       // during global set-up.
7329       if (Test::IsSkipped()) {
7330         // Emit diagnostics when global set-up calls skip, as it will not be
7331         // emitted by default.
7332         TestResult& test_result =
7333             *internal::GetUnitTestImpl()->current_test_result();
7334         for (int j = 0; j < test_result.total_part_count(); ++j) {
7335           const TestPartResult& test_part_result =
7336               test_result.GetTestPartResult(j);
7337           if (test_part_result.type() == TestPartResult::kSkip) {
7338             const std::string& result = test_part_result.message();
7339             printf("%s\n", result.c_str());
7340           }
7341         }
7342         fflush(stdout);
7343       } else if (!Test::HasFatalFailure()) {
7344         for (int test_index = 0; test_index < total_test_suite_count();
7345              test_index++) {
7346           GetMutableSuiteCase(test_index)->Run();
7347           if (GTEST_FLAG(fail_fast) &&
7348               GetMutableSuiteCase(test_index)->Failed()) {
7349             for (int j = test_index + 1; j < total_test_suite_count(); j++) {
7350               GetMutableSuiteCase(j)->Skip();
7351             }
7352             break;
7353           }
7354         }
7355       } else if (Test::HasFatalFailure()) {
7356         // If there was a fatal failure during the global setup then we know we
7357         // aren't going to run any tests. Explicitly mark all of the tests as
7358         // skipped to make this obvious in the output.
7359         for (int test_index = 0; test_index < total_test_suite_count();
7360              test_index++) {
7361           GetMutableSuiteCase(test_index)->Skip();
7362         }
7363       }
7364 
7365       // Tears down all environments in reverse order afterwards.
7366       repeater->OnEnvironmentsTearDownStart(*parent_);
7367       std::for_each(environments_.rbegin(), environments_.rend(),
7368                     TearDownEnvironment);
7369       repeater->OnEnvironmentsTearDownEnd(*parent_);
7370     }
7371 
7372     elapsed_time_ = timer.Elapsed();
7373 
7374     // Tells the unit test event listener that the tests have just finished.
7375     repeater->OnTestIterationEnd(*parent_, i);
7376 
7377     // Gets the result and clears it.
7378     if (!Passed()) {
7379       failed = true;
7380     }
7381 
7382     // Restores the original test order after the iteration.  This
7383     // allows the user to quickly repro a failure that happens in the
7384     // N-th iteration without repeating the first (N - 1) iterations.
7385     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
7386     // case the user somehow changes the value of the flag somewhere
7387     // (it's always safe to unshuffle the tests).
7388     UnshuffleTests();
7389 
7390     if (GTEST_FLAG(shuffle)) {
7391       // Picks a new random seed for each iteration.
7392       random_seed_ = GetNextRandomSeed(random_seed_);
7393     }
7394   }
7395 
7396   repeater->OnTestProgramEnd(*parent_);
7397 
7398   if (!gtest_is_initialized_before_run_all_tests) {
7399     ColoredPrintf(
7400         GTestColor::kRed,
7401         "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
7402         "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
7403         "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
7404         " will start to enforce the valid usage. "
7405         "Please fix it ASAP, or IT WILL START TO FAIL.\n");  // NOLINT
7406 #if GTEST_FOR_GOOGLE_
7407     ColoredPrintf(GTestColor::kRed,
7408                   "For more details, see http://wiki/Main/ValidGUnitMain.\n");
7409 #endif  // GTEST_FOR_GOOGLE_
7410   }
7411 
7412   return !failed;
7413 }
7414 
7415 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
7416 // if the variable is present. If a file already exists at this location, this
7417 // function will write over it. If the variable is present, but the file cannot
7418 // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()7419 void WriteToShardStatusFileIfNeeded() {
7420   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
7421   if (test_shard_file != nullptr) {
7422     FILE* const file = posix::FOpen(test_shard_file, "w");
7423     if (file == nullptr) {
7424       ColoredPrintf(GTestColor::kRed,
7425                     "Could not write to the test shard status file \"%s\" "
7426                     "specified by the %s environment variable.\n",
7427                     test_shard_file, kTestShardStatusFile);
7428       fflush(stdout);
7429       exit(EXIT_FAILURE);
7430     }
7431     fclose(file);
7432   }
7433 }
7434 
7435 // Checks whether sharding is enabled by examining the relevant
7436 // environment variable values. If the variables are present,
7437 // but inconsistent (i.e., shard_index >= total_shards), prints
7438 // an error and exits. If in_subprocess_for_death_test, sharding is
7439 // disabled because it must only be applied to the original test
7440 // process. Otherwise, we could filter out death tests we intended to execute.
ShouldShard(const char * total_shards_env,const char * shard_index_env,bool in_subprocess_for_death_test)7441 bool ShouldShard(const char* total_shards_env,
7442                  const char* shard_index_env,
7443                  bool in_subprocess_for_death_test) {
7444   if (in_subprocess_for_death_test) {
7445     return false;
7446   }
7447 
7448   const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
7449   const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
7450 
7451   if (total_shards == -1 && shard_index == -1) {
7452     return false;
7453   } else if (total_shards == -1 && shard_index != -1) {
7454     const Message msg = Message()
7455       << "Invalid environment variables: you have "
7456       << kTestShardIndex << " = " << shard_index
7457       << ", but have left " << kTestTotalShards << " unset.\n";
7458     ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
7459     fflush(stdout);
7460     exit(EXIT_FAILURE);
7461   } else if (total_shards != -1 && shard_index == -1) {
7462     const Message msg = Message()
7463       << "Invalid environment variables: you have "
7464       << kTestTotalShards << " = " << total_shards
7465       << ", but have left " << kTestShardIndex << " unset.\n";
7466     ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
7467     fflush(stdout);
7468     exit(EXIT_FAILURE);
7469   } else if (shard_index < 0 || shard_index >= total_shards) {
7470     const Message msg = Message()
7471       << "Invalid environment variables: we require 0 <= "
7472       << kTestShardIndex << " < " << kTestTotalShards
7473       << ", but you have " << kTestShardIndex << "=" << shard_index
7474       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
7475     ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
7476     fflush(stdout);
7477     exit(EXIT_FAILURE);
7478   }
7479 
7480   return total_shards > 1;
7481 }
7482 
7483 // Parses the environment variable var as an Int32. If it is unset,
7484 // returns default_val. If it is not an Int32, prints an error
7485 // and aborts.
Int32FromEnvOrDie(const char * var,int32_t default_val)7486 int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
7487   const char* str_val = posix::GetEnv(var);
7488   if (str_val == nullptr) {
7489     return default_val;
7490   }
7491 
7492   int32_t result;
7493   if (!ParseInt32(Message() << "The value of environment variable " << var,
7494                   str_val, &result)) {
7495     exit(EXIT_FAILURE);
7496   }
7497   return result;
7498 }
7499 
7500 // Given the total number of shards, the shard index, and the test id,
7501 // returns true if and only if the test should be run on this shard. The test id
7502 // is some arbitrary but unique non-negative integer assigned to each test
7503 // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)7504 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
7505   return (test_id % total_shards) == shard_index;
7506 }
7507 
7508 // Compares the name of each test with the user-specified filter to
7509 // decide whether the test should be run, then records the result in
7510 // each TestSuite and TestInfo object.
7511 // If shard_tests == true, further filters tests based on sharding
7512 // variables in the environment - see
7513 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
7514 // . Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)7515 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
7516   const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
7517       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
7518   const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
7519       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
7520 
7521   // num_runnable_tests are the number of tests that will
7522   // run across all shards (i.e., match filter and are not disabled).
7523   // num_selected_tests are the number of tests to be run on
7524   // this shard.
7525   int num_runnable_tests = 0;
7526   int num_selected_tests = 0;
7527   for (auto* test_suite : test_suites_) {
7528     const std::string& test_suite_name = test_suite->name();
7529     test_suite->set_should_run(false);
7530 
7531     for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
7532       TestInfo* const test_info = test_suite->test_info_list()[j];
7533       const std::string test_name(test_info->name());
7534       // A test is disabled if test suite name or test name matches
7535       // kDisableTestFilter.
7536       const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
7537                                    test_suite_name, kDisableTestFilter) ||
7538                                internal::UnitTestOptions::MatchesFilter(
7539                                    test_name, kDisableTestFilter);
7540       test_info->is_disabled_ = is_disabled;
7541 
7542       const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
7543           test_suite_name, test_name);
7544       test_info->matches_filter_ = matches_filter;
7545 
7546       const bool is_runnable =
7547           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
7548           matches_filter;
7549 
7550       const bool is_in_another_shard =
7551           shard_tests != IGNORE_SHARDING_PROTOCOL &&
7552           !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
7553       test_info->is_in_another_shard_ = is_in_another_shard;
7554       const bool is_selected = is_runnable && !is_in_another_shard;
7555 
7556       num_runnable_tests += is_runnable;
7557       num_selected_tests += is_selected;
7558 
7559       test_info->should_run_ = is_selected;
7560       test_suite->set_should_run(test_suite->should_run() || is_selected);
7561     }
7562   }
7563   return num_selected_tests;
7564 }
7565 
7566 // Prints the given C-string on a single line by replacing all '\n'
7567 // characters with string "\\n".  If the output takes more than
7568 // max_length characters, only prints the first max_length characters
7569 // and "...".
PrintOnOneLine(const char * str,int max_length)7570 static void PrintOnOneLine(const char* str, int max_length) {
7571   if (str != nullptr) {
7572     for (int i = 0; *str != '\0'; ++str) {
7573       if (i >= max_length) {
7574         printf("...");
7575         break;
7576       }
7577       if (*str == '\n') {
7578         printf("\\n");
7579         i += 2;
7580       } else {
7581         printf("%c", *str);
7582         ++i;
7583       }
7584     }
7585   }
7586 }
7587 
7588 // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()7589 void UnitTestImpl::ListTestsMatchingFilter() {
7590   // Print at most this many characters for each type/value parameter.
7591   const int kMaxParamLength = 250;
7592 
7593   for (auto* test_suite : test_suites_) {
7594     bool printed_test_suite_name = false;
7595 
7596     for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
7597       const TestInfo* const test_info = test_suite->test_info_list()[j];
7598       if (test_info->matches_filter_) {
7599         if (!printed_test_suite_name) {
7600           printed_test_suite_name = true;
7601           printf("%s.", test_suite->name());
7602           if (test_suite->type_param() != nullptr) {
7603             printf("  # %s = ", kTypeParamLabel);
7604             // We print the type parameter on a single line to make
7605             // the output easy to parse by a program.
7606             PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
7607           }
7608           printf("\n");
7609         }
7610         printf("  %s", test_info->name());
7611         if (test_info->value_param() != nullptr) {
7612           printf("  # %s = ", kValueParamLabel);
7613           // We print the value parameter on a single line to make the
7614           // output easy to parse by a program.
7615           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
7616         }
7617         printf("\n");
7618       }
7619     }
7620   }
7621   fflush(stdout);
7622   const std::string& output_format = UnitTestOptions::GetOutputFormat();
7623   if (output_format == "xml" || output_format == "json") {
7624     FILE* fileout = OpenFileForWriting(
7625         UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
7626     std::stringstream stream;
7627     if (output_format == "xml") {
7628       XmlUnitTestResultPrinter(
7629           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
7630           .PrintXmlTestsList(&stream, test_suites_);
7631     } else if (output_format == "json") {
7632       JsonUnitTestResultPrinter(
7633           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
7634           .PrintJsonTestList(&stream, test_suites_);
7635     }
7636     fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
7637     fclose(fileout);
7638   }
7639 }
7640 
7641 // Sets the OS stack trace getter.
7642 //
7643 // Does nothing if the input and the current OS stack trace getter are
7644 // the same; otherwise, deletes the old getter and makes the input the
7645 // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)7646 void UnitTestImpl::set_os_stack_trace_getter(
7647     OsStackTraceGetterInterface* getter) {
7648   if (os_stack_trace_getter_ != getter) {
7649     delete os_stack_trace_getter_;
7650     os_stack_trace_getter_ = getter;
7651   }
7652 }
7653 
7654 // Returns the current OS stack trace getter if it is not NULL;
7655 // otherwise, creates an OsStackTraceGetter, makes it the current
7656 // getter, and returns it.
os_stack_trace_getter()7657 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
7658   if (os_stack_trace_getter_ == nullptr) {
7659 #ifdef GTEST_OS_STACK_TRACE_GETTER_
7660     os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
7661 #else
7662     os_stack_trace_getter_ = new OsStackTraceGetter;
7663 #endif  // GTEST_OS_STACK_TRACE_GETTER_
7664   }
7665 
7666   return os_stack_trace_getter_;
7667 }
7668 
7669 // Returns the most specific TestResult currently running.
current_test_result()7670 TestResult* UnitTestImpl::current_test_result() {
7671   if (current_test_info_ != nullptr) {
7672     return &current_test_info_->result_;
7673   }
7674   if (current_test_suite_ != nullptr) {
7675     return &current_test_suite_->ad_hoc_test_result_;
7676   }
7677   return &ad_hoc_test_result_;
7678 }
7679 
7680 // Shuffles all test suites, and the tests within each test suite,
7681 // making sure that death tests are still run first.
ShuffleTests()7682 void UnitTestImpl::ShuffleTests() {
7683   // Shuffles the death test suites.
7684   ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
7685 
7686   // Shuffles the non-death test suites.
7687   ShuffleRange(random(), last_death_test_suite_ + 1,
7688                static_cast<int>(test_suites_.size()), &test_suite_indices_);
7689 
7690   // Shuffles the tests inside each test suite.
7691   for (auto& test_suite : test_suites_) {
7692     test_suite->ShuffleTests(random());
7693   }
7694 }
7695 
7696 // Restores the test suites and tests to their order before the first shuffle.
UnshuffleTests()7697 void UnitTestImpl::UnshuffleTests() {
7698   for (size_t i = 0; i < test_suites_.size(); i++) {
7699     // Unshuffles the tests in each test suite.
7700     test_suites_[i]->UnshuffleTests();
7701     // Resets the index of each test suite.
7702     test_suite_indices_[i] = static_cast<int>(i);
7703   }
7704 }
7705 
7706 // Returns the current OS stack trace as an std::string.
7707 //
7708 // The maximum number of stack frames to be included is specified by
7709 // the gtest_stack_trace_depth flag.  The skip_count parameter
7710 // specifies the number of top frames to be skipped, which doesn't
7711 // count against the number of frames to be included.
7712 //
7713 // For example, if Foo() calls Bar(), which in turn calls
7714 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
7715 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)7716 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
7717                                             int skip_count) {
7718   // We pass skip_count + 1 to skip this wrapper function in addition
7719   // to what the user really wants to skip.
7720   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
7721 }
7722 
7723 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
7724 // suppress unreachable code warnings.
7725 namespace {
7726 class ClassUniqueToAlwaysTrue {};
7727 }
7728 
IsTrue(bool condition)7729 bool IsTrue(bool condition) { return condition; }
7730 
AlwaysTrue()7731 bool AlwaysTrue() {
7732 #if GTEST_HAS_EXCEPTIONS
7733   // This condition is always false so AlwaysTrue() never actually throws,
7734   // but it makes the compiler think that it may throw.
7735   if (IsTrue(false))
7736     throw ClassUniqueToAlwaysTrue();
7737 #endif  // GTEST_HAS_EXCEPTIONS
7738   return true;
7739 }
7740 
7741 // If *pstr starts with the given prefix, modifies *pstr to be right
7742 // past the prefix and returns true; otherwise leaves *pstr unchanged
7743 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)7744 bool SkipPrefix(const char* prefix, const char** pstr) {
7745   const size_t prefix_len = strlen(prefix);
7746   if (strncmp(*pstr, prefix, prefix_len) == 0) {
7747     *pstr += prefix_len;
7748     return true;
7749   }
7750   return false;
7751 }
7752 
7753 // Parses a string as a command line flag.  The string should have
7754 // the format "--flag=value".  When def_optional is true, the "=value"
7755 // part can be omitted.
7756 //
7757 // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)7758 static const char* ParseFlagValue(const char* str, const char* flag,
7759                                   bool def_optional) {
7760   // str and flag must not be NULL.
7761   if (str == nullptr || flag == nullptr) return nullptr;
7762 
7763   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
7764   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
7765   const size_t flag_len = flag_str.length();
7766   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
7767 
7768   // Skips the flag name.
7769   const char* flag_end = str + flag_len;
7770 
7771   // When def_optional is true, it's OK to not have a "=value" part.
7772   if (def_optional && (flag_end[0] == '\0')) {
7773     return flag_end;
7774   }
7775 
7776   // If def_optional is true and there are more characters after the
7777   // flag name, or if def_optional is false, there must be a '=' after
7778   // the flag name.
7779   if (flag_end[0] != '=') return nullptr;
7780 
7781   // Returns the string after "=".
7782   return flag_end + 1;
7783 }
7784 
7785 // Parses a string for a bool flag, in the form of either
7786 // "--flag=value" or "--flag".
7787 //
7788 // In the former case, the value is taken as true as long as it does
7789 // not start with '0', 'f', or 'F'.
7790 //
7791 // In the latter case, the value is taken as true.
7792 //
7793 // On success, stores the value of the flag in *value, and returns
7794 // true.  On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)7795 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
7796   // Gets the value of the flag as a string.
7797   const char* const value_str = ParseFlagValue(str, flag, true);
7798 
7799   // Aborts if the parsing failed.
7800   if (value_str == nullptr) return false;
7801 
7802   // Converts the string value to a bool.
7803   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
7804   return true;
7805 }
7806 
7807 // Parses a string for an int32_t flag, in the form of "--flag=value".
7808 //
7809 // On success, stores the value of the flag in *value, and returns
7810 // true.  On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,int32_t * value)7811 bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {
7812   // Gets the value of the flag as a string.
7813   const char* const value_str = ParseFlagValue(str, flag, false);
7814 
7815   // Aborts if the parsing failed.
7816   if (value_str == nullptr) return false;
7817 
7818   // Sets *value to the value of the flag.
7819   return ParseInt32(Message() << "The value of flag --" << flag,
7820                     value_str, value);
7821 }
7822 
7823 // Parses a string for a string flag, in the form of "--flag=value".
7824 //
7825 // On success, stores the value of the flag in *value, and returns
7826 // true.  On failure, returns false without changing *value.
7827 template <typename String>
ParseStringFlag(const char * str,const char * flag,String * value)7828 static bool ParseStringFlag(const char* str, const char* flag, String* value) {
7829   // Gets the value of the flag as a string.
7830   const char* const value_str = ParseFlagValue(str, flag, false);
7831 
7832   // Aborts if the parsing failed.
7833   if (value_str == nullptr) return false;
7834 
7835   // Sets *value to the value of the flag.
7836   *value = value_str;
7837   return true;
7838 }
7839 
7840 // Determines whether a string has a prefix that Google Test uses for its
7841 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
7842 // If Google Test detects that a command line flag has its prefix but is not
7843 // recognized, it will print its help message. Flags starting with
7844 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
7845 // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)7846 static bool HasGoogleTestFlagPrefix(const char* str) {
7847   return (SkipPrefix("--", &str) ||
7848           SkipPrefix("-", &str) ||
7849           SkipPrefix("/", &str)) &&
7850          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
7851          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
7852           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
7853 }
7854 
7855 // Prints a string containing code-encoded text.  The following escape
7856 // sequences can be used in the string to control the text color:
7857 //
7858 //   @@    prints a single '@' character.
7859 //   @R    changes the color to red.
7860 //   @G    changes the color to green.
7861 //   @Y    changes the color to yellow.
7862 //   @D    changes to the default terminal text color.
7863 //
PrintColorEncoded(const char * str)7864 static void PrintColorEncoded(const char* str) {
7865   GTestColor color = GTestColor::kDefault;  // The current color.
7866 
7867   // Conceptually, we split the string into segments divided by escape
7868   // sequences.  Then we print one segment at a time.  At the end of
7869   // each iteration, the str pointer advances to the beginning of the
7870   // next segment.
7871   for (;;) {
7872     const char* p = strchr(str, '@');
7873     if (p == nullptr) {
7874       ColoredPrintf(color, "%s", str);
7875       return;
7876     }
7877 
7878     ColoredPrintf(color, "%s", std::string(str, p).c_str());
7879 
7880     const char ch = p[1];
7881     str = p + 2;
7882     if (ch == '@') {
7883       ColoredPrintf(color, "@");
7884     } else if (ch == 'D') {
7885       color = GTestColor::kDefault;
7886     } else if (ch == 'R') {
7887       color = GTestColor::kRed;
7888     } else if (ch == 'G') {
7889       color = GTestColor::kGreen;
7890     } else if (ch == 'Y') {
7891       color = GTestColor::kYellow;
7892     } else {
7893       --str;
7894     }
7895   }
7896 }
7897 
7898 static const char kColorEncodedHelpMessage[] =
7899     "This program contains tests written using " GTEST_NAME_
7900     ". You can use the\n"
7901     "following command line flags to control its behavior:\n"
7902     "\n"
7903     "Test Selection:\n"
7904     "  @G--" GTEST_FLAG_PREFIX_
7905     "list_tests@D\n"
7906     "      List the names of all tests instead of running them. The name of\n"
7907     "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
7908     "  @G--" GTEST_FLAG_PREFIX_
7909     "filter=@YPOSITIVE_PATTERNS"
7910     "[@G-@YNEGATIVE_PATTERNS]@D\n"
7911     "      Run only the tests whose name matches one of the positive patterns "
7912     "but\n"
7913     "      none of the negative patterns. '?' matches any single character; "
7914     "'*'\n"
7915     "      matches any substring; ':' separates two patterns.\n"
7916     "  @G--" GTEST_FLAG_PREFIX_
7917     "also_run_disabled_tests@D\n"
7918     "      Run all disabled tests too.\n"
7919     "\n"
7920     "Test Execution:\n"
7921     "  @G--" GTEST_FLAG_PREFIX_
7922     "repeat=@Y[COUNT]@D\n"
7923     "      Run the tests repeatedly; use a negative count to repeat forever.\n"
7924     "  @G--" GTEST_FLAG_PREFIX_
7925     "shuffle@D\n"
7926     "      Randomize tests' orders on every iteration.\n"
7927     "  @G--" GTEST_FLAG_PREFIX_
7928     "random_seed=@Y[NUMBER]@D\n"
7929     "      Random number seed to use for shuffling test orders (between 1 and\n"
7930     "      99999, or 0 to use a seed based on the current time).\n"
7931     "\n"
7932     "Test Output:\n"
7933     "  @G--" GTEST_FLAG_PREFIX_
7934     "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
7935     "      Enable/disable colored output. The default is @Gauto@D.\n"
7936     "  @G--" GTEST_FLAG_PREFIX_
7937     "brief=1@D\n"
7938     "      Only print test failures.\n"
7939     "  @G--" GTEST_FLAG_PREFIX_
7940     "print_time=0@D\n"
7941     "      Don't print the elapsed time of each test.\n"
7942     "  @G--" GTEST_FLAG_PREFIX_
7943     "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
7944     "@Y|@G:@YFILE_PATH]@D\n"
7945     "      Generate a JSON or XML report in the given directory or with the "
7946     "given\n"
7947     "      file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
7948 # if GTEST_CAN_STREAM_RESULTS_
7949     "  @G--" GTEST_FLAG_PREFIX_
7950     "stream_result_to=@YHOST@G:@YPORT@D\n"
7951     "      Stream test results to the given server.\n"
7952 # endif  // GTEST_CAN_STREAM_RESULTS_
7953     "\n"
7954     "Assertion Behavior:\n"
7955 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7956     "  @G--" GTEST_FLAG_PREFIX_
7957     "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
7958     "      Set the default death test style.\n"
7959 # endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7960     "  @G--" GTEST_FLAG_PREFIX_
7961     "break_on_failure@D\n"
7962     "      Turn assertion failures into debugger break-points.\n"
7963     "  @G--" GTEST_FLAG_PREFIX_
7964     "throw_on_failure@D\n"
7965     "      Turn assertion failures into C++ exceptions for use by an external\n"
7966     "      test framework.\n"
7967     "  @G--" GTEST_FLAG_PREFIX_
7968     "catch_exceptions=0@D\n"
7969     "      Do not report exceptions as test failures. Instead, allow them\n"
7970     "      to crash the program or throw a pop-up (on Windows).\n"
7971     "\n"
7972     "Except for @G--" GTEST_FLAG_PREFIX_
7973     "list_tests@D, you can alternatively set "
7974     "the corresponding\n"
7975     "environment variable of a flag (all letters in upper-case). For example, "
7976     "to\n"
7977     "disable colored text output, you can either specify "
7978     "@G--" GTEST_FLAG_PREFIX_
7979     "color=no@D or set\n"
7980     "the @G" GTEST_FLAG_PREFIX_UPPER_
7981     "COLOR@D environment variable to @Gno@D.\n"
7982     "\n"
7983     "For more information, please read the " GTEST_NAME_
7984     " documentation at\n"
7985     "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
7986     "\n"
7987     "(not one in your own code or tests), please report it to\n"
7988     "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
7989 
ParseGoogleTestFlag(const char * const arg)7990 static bool ParseGoogleTestFlag(const char* const arg) {
7991   return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7992                        &GTEST_FLAG(also_run_disabled_tests)) ||
7993          ParseBoolFlag(arg, kBreakOnFailureFlag,
7994                        &GTEST_FLAG(break_on_failure)) ||
7995          ParseBoolFlag(arg, kCatchExceptionsFlag,
7996                        &GTEST_FLAG(catch_exceptions)) ||
7997          ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
7998          ParseStringFlag(arg, kDeathTestStyleFlag,
7999                          &GTEST_FLAG(death_test_style)) ||
8000          ParseBoolFlag(arg, kDeathTestUseFork,
8001                        &GTEST_FLAG(death_test_use_fork)) ||
8002          ParseBoolFlag(arg, kFailFast, &GTEST_FLAG(fail_fast)) ||
8003          ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
8004          ParseStringFlag(arg, kInternalRunDeathTestFlag,
8005                          &GTEST_FLAG(internal_run_death_test)) ||
8006          ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
8007          ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
8008          ParseBoolFlag(arg, kBriefFlag, &GTEST_FLAG(brief)) ||
8009          ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
8010          ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
8011          ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
8012          ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
8013          ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
8014          ParseInt32Flag(arg, kStackTraceDepthFlag,
8015                         &GTEST_FLAG(stack_trace_depth)) ||
8016          ParseStringFlag(arg, kStreamResultToFlag,
8017                          &GTEST_FLAG(stream_result_to)) ||
8018          ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure));
8019 }
8020 
8021 #if GTEST_USE_OWN_FLAGFILE_FLAG_
LoadFlagsFromFile(const std::string & path)8022 static void LoadFlagsFromFile(const std::string& path) {
8023   FILE* flagfile = posix::FOpen(path.c_str(), "r");
8024   if (!flagfile) {
8025     GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
8026                       << "\"";
8027   }
8028   std::string contents(ReadEntireFile(flagfile));
8029   posix::FClose(flagfile);
8030   std::vector<std::string> lines;
8031   SplitString(contents, '\n', &lines);
8032   for (size_t i = 0; i < lines.size(); ++i) {
8033     if (lines[i].empty())
8034       continue;
8035     if (!ParseGoogleTestFlag(lines[i].c_str()))
8036       g_help_flag = true;
8037   }
8038 }
8039 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
8040 
8041 // Parses the command line for Google Test flags, without initializing
8042 // other parts of Google Test.  The type parameter CharType can be
8043 // instantiated to either char or wchar_t.
8044 template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)8045 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
8046   for (int i = 1; i < *argc; i++) {
8047     const std::string arg_string = StreamableToString(argv[i]);
8048     const char* const arg = arg_string.c_str();
8049 
8050     using internal::ParseBoolFlag;
8051     using internal::ParseInt32Flag;
8052     using internal::ParseStringFlag;
8053 
8054     bool remove_flag = false;
8055     if (ParseGoogleTestFlag(arg)) {
8056       remove_flag = true;
8057 #if GTEST_USE_OWN_FLAGFILE_FLAG_
8058     } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
8059       LoadFlagsFromFile(GTEST_FLAG(flagfile));
8060       remove_flag = true;
8061 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
8062     } else if (arg_string == "--help" || arg_string == "-h" ||
8063                arg_string == "-?" || arg_string == "/?" ||
8064                HasGoogleTestFlagPrefix(arg)) {
8065       // Both help flag and unrecognized Google Test flags (excluding
8066       // internal ones) trigger help display.
8067       g_help_flag = true;
8068     }
8069 
8070     if (remove_flag) {
8071       // Shift the remainder of the argv list left by one.  Note
8072       // that argv has (*argc + 1) elements, the last one always being
8073       // NULL.  The following loop moves the trailing NULL element as
8074       // well.
8075       for (int j = i; j != *argc; j++) {
8076         argv[j] = argv[j + 1];
8077       }
8078 
8079       // Decrements the argument count.
8080       (*argc)--;
8081 
8082       // We also need to decrement the iterator as we just removed
8083       // an element.
8084       i--;
8085     }
8086   }
8087 
8088   if (g_help_flag) {
8089     // We print the help here instead of in RUN_ALL_TESTS(), as the
8090     // latter may not be called at all if the user is using Google
8091     // Test with another testing framework.
8092     PrintColorEncoded(kColorEncodedHelpMessage);
8093   }
8094 }
8095 
8096 // Parses the command line for Google Test flags, without initializing
8097 // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)8098 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
8099   ParseGoogleTestFlagsOnlyImpl(argc, argv);
8100 
8101   // Fix the value of *_NSGetArgc() on macOS, but if and only if
8102   // *_NSGetArgv() == argv
8103   // Only applicable to char** version of argv
8104 #if GTEST_OS_MAC
8105 #ifndef GTEST_OS_IOS
8106   if (*_NSGetArgv() == argv) {
8107     *_NSGetArgc() = *argc;
8108   }
8109 #endif
8110 #endif
8111 }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)8112 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
8113   ParseGoogleTestFlagsOnlyImpl(argc, argv);
8114 }
8115 
8116 // The internal implementation of InitGoogleTest().
8117 //
8118 // The type parameter CharType can be instantiated to either char or
8119 // wchar_t.
8120 template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)8121 void InitGoogleTestImpl(int* argc, CharType** argv) {
8122   // We don't want to run the initialization code twice.
8123   if (GTestIsInitialized()) return;
8124 
8125   if (*argc <= 0) return;
8126 
8127   g_argvs.clear();
8128   for (int i = 0; i != *argc; i++) {
8129     g_argvs.push_back(StreamableToString(argv[i]));
8130   }
8131 
8132 #if GTEST_HAS_ABSL
8133   absl::InitializeSymbolizer(g_argvs[0].c_str());
8134 #endif  // GTEST_HAS_ABSL
8135 
8136   ParseGoogleTestFlagsOnly(argc, argv);
8137   GetUnitTestImpl()->PostFlagParsingInit();
8138 }
8139 
8140 }  // namespace internal
8141 
8142 // Initializes Google Test.  This must be called before calling
8143 // RUN_ALL_TESTS().  In particular, it parses a command line for the
8144 // flags that Google Test recognizes.  Whenever a Google Test flag is
8145 // seen, it is removed from argv, and *argc is decremented.
8146 //
8147 // No value is returned.  Instead, the Google Test flag variables are
8148 // updated.
8149 //
8150 // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)8151 void InitGoogleTest(int* argc, char** argv) {
8152 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8153   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
8154 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8155   internal::InitGoogleTestImpl(argc, argv);
8156 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8157 }
8158 
8159 // This overloaded version can be used in Windows programs compiled in
8160 // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)8161 void InitGoogleTest(int* argc, wchar_t** argv) {
8162 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8163   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
8164 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8165   internal::InitGoogleTestImpl(argc, argv);
8166 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8167 }
8168 
8169 // This overloaded version can be used on Arduino/embedded platforms where
8170 // there is no argc/argv.
InitGoogleTest()8171 void InitGoogleTest() {
8172   // Since Arduino doesn't have a command line, fake out the argc/argv arguments
8173   int argc = 1;
8174   const auto arg0 = "dummy";
8175   char* argv0 = const_cast<char*>(arg0);
8176   char** argv = &argv0;
8177 
8178 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8179   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
8180 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8181   internal::InitGoogleTestImpl(&argc, argv);
8182 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
8183 }
8184 
TempDir()8185 std::string TempDir() {
8186 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
8187   return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
8188 #elif GTEST_OS_WINDOWS_MOBILE
8189   return "\\temp\\";
8190 #elif GTEST_OS_WINDOWS
8191   const char* temp_dir = internal::posix::GetEnv("TEMP");
8192   if (temp_dir == nullptr || temp_dir[0] == '\0') {
8193     return "\\temp\\";
8194   } else if (temp_dir[strlen(temp_dir) - 1] == '\\') {
8195     return temp_dir;
8196   } else {
8197     return std::string(temp_dir) + "\\";
8198   }
8199 #elif GTEST_OS_LINUX_ANDROID
8200   const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
8201   if (temp_dir == nullptr || temp_dir[0] == '\0') {
8202     return "/data/local/tmp/";
8203   } else {
8204     return temp_dir;
8205   }
8206 #elif GTEST_OS_LINUX
8207   const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
8208   if (temp_dir == nullptr || temp_dir[0] == '\0') {
8209     return "/tmp/";
8210   } else {
8211     return temp_dir;
8212   }
8213 #else
8214   return "/tmp/";
8215 #endif  // GTEST_OS_WINDOWS_MOBILE
8216 }
8217 
8218 // Class ScopedTrace
8219 
8220 // Pushes the given source file location and message onto a per-thread
8221 // trace stack maintained by Google Test.
PushTrace(const char * file,int line,std::string message)8222 void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
8223   internal::TraceInfo trace;
8224   trace.file = file;
8225   trace.line = line;
8226   trace.message.swap(message);
8227 
8228   UnitTest::GetInstance()->PushGTestTrace(trace);
8229 }
8230 
8231 // Pops the info pushed by the c'tor.
~ScopedTrace()8232 ScopedTrace::~ScopedTrace()
8233     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
8234   UnitTest::GetInstance()->PopGTestTrace();
8235 }
8236 
8237 }  // namespace testing
8238 // Copyright 2005, Google Inc.
8239 // All rights reserved.
8240 //
8241 // Redistribution and use in source and binary forms, with or without
8242 // modification, are permitted provided that the following conditions are
8243 // met:
8244 //
8245 //     * Redistributions of source code must retain the above copyright
8246 // notice, this list of conditions and the following disclaimer.
8247 //     * Redistributions in binary form must reproduce the above
8248 // copyright notice, this list of conditions and the following disclaimer
8249 // in the documentation and/or other materials provided with the
8250 // distribution.
8251 //     * Neither the name of Google Inc. nor the names of its
8252 // contributors may be used to endorse or promote products derived from
8253 // this software without specific prior written permission.
8254 //
8255 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8256 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8257 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8258 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8259 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8260 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8261 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8262 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8263 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8264 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8265 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8266 
8267 //
8268 // This file implements death tests.
8269 
8270 
8271 #include <functional>
8272 #include <utility>
8273 
8274 
8275 #if GTEST_HAS_DEATH_TEST
8276 
8277 # if GTEST_OS_MAC
8278 #  include <crt_externs.h>
8279 # endif  // GTEST_OS_MAC
8280 
8281 # include <errno.h>
8282 # include <fcntl.h>
8283 # include <limits.h>
8284 
8285 # if GTEST_OS_LINUX
8286 #  include <signal.h>
8287 # endif  // GTEST_OS_LINUX
8288 
8289 # include <stdarg.h>
8290 
8291 # if GTEST_OS_WINDOWS
8292 #  include <windows.h>
8293 # else
8294 #  include <sys/mman.h>
8295 #  include <sys/wait.h>
8296 # endif  // GTEST_OS_WINDOWS
8297 
8298 # if GTEST_OS_QNX
8299 #  include <spawn.h>
8300 # endif  // GTEST_OS_QNX
8301 
8302 # if GTEST_OS_FUCHSIA
8303 #  include <lib/fdio/fd.h>
8304 #  include <lib/fdio/io.h>
8305 #  include <lib/fdio/spawn.h>
8306 #  include <lib/zx/channel.h>
8307 #  include <lib/zx/port.h>
8308 #  include <lib/zx/process.h>
8309 #  include <lib/zx/socket.h>
8310 #  include <zircon/processargs.h>
8311 #  include <zircon/syscalls.h>
8312 #  include <zircon/syscalls/policy.h>
8313 #  include <zircon/syscalls/port.h>
8314 # endif  // GTEST_OS_FUCHSIA
8315 
8316 #endif  // GTEST_HAS_DEATH_TEST
8317 
8318 
8319 namespace testing {
8320 
8321 // Constants.
8322 
8323 // The default death test style.
8324 //
8325 // This is defined in internal/gtest-port.h as "fast", but can be overridden by
8326 // a definition in internal/custom/gtest-port.h. The recommended value, which is
8327 // used internally at Google, is "threadsafe".
8328 static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
8329 
8330 GTEST_DEFINE_string_(
8331     death_test_style,
8332     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
8333     "Indicates how to run a death test in a forked child process: "
8334     "\"threadsafe\" (child process re-executes the test binary "
8335     "from the beginning, running only the specific death test) or "
8336     "\"fast\" (child process runs the death test immediately "
8337     "after forking).");
8338 
8339 GTEST_DEFINE_bool_(
8340     death_test_use_fork,
8341     internal::BoolFromGTestEnv("death_test_use_fork", false),
8342     "Instructs to use fork()/_exit() instead of clone() in death tests. "
8343     "Ignored and always uses fork() on POSIX systems where clone() is not "
8344     "implemented. Useful when running under valgrind or similar tools if "
8345     "those do not support clone(). Valgrind 3.3.1 will just fail if "
8346     "it sees an unsupported combination of clone() flags. "
8347     "It is not recommended to use this flag w/o valgrind though it will "
8348     "work in 99% of the cases. Once valgrind is fixed, this flag will "
8349     "most likely be removed.");
8350 
8351 namespace internal {
8352 GTEST_DEFINE_string_(
8353     internal_run_death_test, "",
8354     "Indicates the file, line number, temporal index of "
8355     "the single death test to run, and a file descriptor to "
8356     "which a success code may be sent, all separated by "
8357     "the '|' characters.  This flag is specified if and only if the "
8358     "current process is a sub-process launched for running a thread-safe "
8359     "death test.  FOR INTERNAL USE ONLY.");
8360 }  // namespace internal
8361 
8362 #if GTEST_HAS_DEATH_TEST
8363 
8364 namespace internal {
8365 
8366 // Valid only for fast death tests. Indicates the code is running in the
8367 // child process of a fast style death test.
8368 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8369 static bool g_in_fast_death_test_child = false;
8370 # endif
8371 
8372 // Returns a Boolean value indicating whether the caller is currently
8373 // executing in the context of the death test child process.  Tools such as
8374 // Valgrind heap checkers may need this to modify their behavior in death
8375 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
8376 // implementation of death tests.  User code MUST NOT use it.
InDeathTestChild()8377 bool InDeathTestChild() {
8378 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8379 
8380   // On Windows and Fuchsia, death tests are thread-safe regardless of the value
8381   // of the death_test_style flag.
8382   return !GTEST_FLAG(internal_run_death_test).empty();
8383 
8384 # else
8385 
8386   if (GTEST_FLAG(death_test_style) == "threadsafe")
8387     return !GTEST_FLAG(internal_run_death_test).empty();
8388   else
8389     return g_in_fast_death_test_child;
8390 #endif
8391 }
8392 
8393 }  // namespace internal
8394 
8395 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)8396 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
8397 }
8398 
8399 // ExitedWithCode function-call operator.
operator ()(int exit_status) const8400 bool ExitedWithCode::operator()(int exit_status) const {
8401 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8402 
8403   return exit_status == exit_code_;
8404 
8405 # else
8406 
8407   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
8408 
8409 # endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8410 }
8411 
8412 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8413 // KilledBySignal constructor.
KilledBySignal(int signum)8414 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
8415 }
8416 
8417 // KilledBySignal function-call operator.
operator ()(int exit_status) const8418 bool KilledBySignal::operator()(int exit_status) const {
8419 #  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
8420   {
8421     bool result;
8422     if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
8423       return result;
8424     }
8425   }
8426 #  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
8427   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
8428 }
8429 # endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8430 
8431 namespace internal {
8432 
8433 // Utilities needed for death tests.
8434 
8435 // Generates a textual description of a given exit code, in the format
8436 // specified by wait(2).
ExitSummary(int exit_code)8437 static std::string ExitSummary(int exit_code) {
8438   Message m;
8439 
8440 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8441 
8442   m << "Exited with exit status " << exit_code;
8443 
8444 # else
8445 
8446   if (WIFEXITED(exit_code)) {
8447     m << "Exited with exit status " << WEXITSTATUS(exit_code);
8448   } else if (WIFSIGNALED(exit_code)) {
8449     m << "Terminated by signal " << WTERMSIG(exit_code);
8450   }
8451 #  ifdef WCOREDUMP
8452   if (WCOREDUMP(exit_code)) {
8453     m << " (core dumped)";
8454   }
8455 #  endif
8456 # endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
8457 
8458   return m.GetString();
8459 }
8460 
8461 // Returns true if exit_status describes a process that was terminated
8462 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)8463 bool ExitedUnsuccessfully(int exit_status) {
8464   return !ExitedWithCode(0)(exit_status);
8465 }
8466 
8467 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8468 // Generates a textual failure message when a death test finds more than
8469 // one thread running, or cannot determine the number of threads, prior
8470 // to executing the given statement.  It is the responsibility of the
8471 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)8472 static std::string DeathTestThreadWarning(size_t thread_count) {
8473   Message msg;
8474   msg << "Death tests use fork(), which is unsafe particularly"
8475       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
8476   if (thread_count == 0) {
8477     msg << "couldn't detect the number of threads.";
8478   } else {
8479     msg << "detected " << thread_count << " threads.";
8480   }
8481   msg << " See "
8482          "https://github.com/google/googletest/blob/master/docs/"
8483          "advanced.md#death-tests-and-threads"
8484       << " for more explanation and suggested solutions, especially if"
8485       << " this is the last message you see before your test times out.";
8486   return msg.GetString();
8487 }
8488 # endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
8489 
8490 // Flag characters for reporting a death test that did not die.
8491 static const char kDeathTestLived = 'L';
8492 static const char kDeathTestReturned = 'R';
8493 static const char kDeathTestThrew = 'T';
8494 static const char kDeathTestInternalError = 'I';
8495 
8496 #if GTEST_OS_FUCHSIA
8497 
8498 // File descriptor used for the pipe in the child process.
8499 static const int kFuchsiaReadPipeFd = 3;
8500 
8501 #endif
8502 
8503 // An enumeration describing all of the possible ways that a death test can
8504 // conclude.  DIED means that the process died while executing the test
8505 // code; LIVED means that process lived beyond the end of the test code;
8506 // RETURNED means that the test statement attempted to execute a return
8507 // statement, which is not allowed; THREW means that the test statement
8508 // returned control by throwing an exception.  IN_PROGRESS means the test
8509 // has not yet concluded.
8510 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
8511 
8512 // Routine for aborting the program which is safe to call from an
8513 // exec-style death test child process, in which case the error
8514 // message is propagated back to the parent process.  Otherwise, the
8515 // message is simply printed to stderr.  In either case, the program
8516 // then exits with status 1.
DeathTestAbort(const std::string & message)8517 static void DeathTestAbort(const std::string& message) {
8518   // On a POSIX system, this function may be called from a threadsafe-style
8519   // death test child process, which operates on a very small stack.  Use
8520   // the heap for any additional non-minuscule memory requirements.
8521   const InternalRunDeathTestFlag* const flag =
8522       GetUnitTestImpl()->internal_run_death_test_flag();
8523   if (flag != nullptr) {
8524     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
8525     fputc(kDeathTestInternalError, parent);
8526     fprintf(parent, "%s", message.c_str());
8527     fflush(parent);
8528     _exit(1);
8529   } else {
8530     fprintf(stderr, "%s", message.c_str());
8531     fflush(stderr);
8532     posix::Abort();
8533   }
8534 }
8535 
8536 // A replacement for CHECK that calls DeathTestAbort if the assertion
8537 // fails.
8538 # define GTEST_DEATH_TEST_CHECK_(expression) \
8539   do { \
8540     if (!::testing::internal::IsTrue(expression)) { \
8541       DeathTestAbort( \
8542           ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
8543           + ::testing::internal::StreamableToString(__LINE__) + ": " \
8544           + #expression); \
8545     } \
8546   } while (::testing::internal::AlwaysFalse())
8547 
8548 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
8549 // evaluating any system call that fulfills two conditions: it must return
8550 // -1 on failure, and set errno to EINTR when it is interrupted and
8551 // should be tried again.  The macro expands to a loop that repeatedly
8552 // evaluates the expression as long as it evaluates to -1 and sets
8553 // errno to EINTR.  If the expression evaluates to -1 but errno is
8554 // something other than EINTR, DeathTestAbort is called.
8555 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
8556   do { \
8557     int gtest_retval; \
8558     do { \
8559       gtest_retval = (expression); \
8560     } while (gtest_retval == -1 && errno == EINTR); \
8561     if (gtest_retval == -1) { \
8562       DeathTestAbort( \
8563           ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
8564           + ::testing::internal::StreamableToString(__LINE__) + ": " \
8565           + #expression + " != -1"); \
8566     } \
8567   } while (::testing::internal::AlwaysFalse())
8568 
8569 // Returns the message describing the last system error in errno.
GetLastErrnoDescription()8570 std::string GetLastErrnoDescription() {
8571     return errno == 0 ? "" : posix::StrError(errno);
8572 }
8573 
8574 // This is called from a death test parent process to read a failure
8575 // message from the death test child process and log it with the FATAL
8576 // severity. On Windows, the message is read from a pipe handle. On other
8577 // platforms, it is read from a file descriptor.
FailFromInternalError(int fd)8578 static void FailFromInternalError(int fd) {
8579   Message error;
8580   char buffer[256];
8581   int num_read;
8582 
8583   do {
8584     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
8585       buffer[num_read] = '\0';
8586       error << buffer;
8587     }
8588   } while (num_read == -1 && errno == EINTR);
8589 
8590   if (num_read == 0) {
8591     GTEST_LOG_(FATAL) << error.GetString();
8592   } else {
8593     const int last_error = errno;
8594     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
8595                       << GetLastErrnoDescription() << " [" << last_error << "]";
8596   }
8597 }
8598 
8599 // Death test constructor.  Increments the running death test count
8600 // for the current test.
DeathTest()8601 DeathTest::DeathTest() {
8602   TestInfo* const info = GetUnitTestImpl()->current_test_info();
8603   if (info == nullptr) {
8604     DeathTestAbort("Cannot run a death test outside of a TEST or "
8605                    "TEST_F construct");
8606   }
8607 }
8608 
8609 // Creates and returns a death test by dispatching to the current
8610 // death test factory.
Create(const char * statement,Matcher<const std::string &> matcher,const char * file,int line,DeathTest ** test)8611 bool DeathTest::Create(const char* statement,
8612                        Matcher<const std::string&> matcher, const char* file,
8613                        int line, DeathTest** test) {
8614   return GetUnitTestImpl()->death_test_factory()->Create(
8615       statement, std::move(matcher), file, line, test);
8616 }
8617 
LastMessage()8618 const char* DeathTest::LastMessage() {
8619   return last_death_test_message_.c_str();
8620 }
8621 
set_last_death_test_message(const std::string & message)8622 void DeathTest::set_last_death_test_message(const std::string& message) {
8623   last_death_test_message_ = message;
8624 }
8625 
8626 std::string DeathTest::last_death_test_message_;
8627 
8628 // Provides cross platform implementation for some death functionality.
8629 class DeathTestImpl : public DeathTest {
8630  protected:
DeathTestImpl(const char * a_statement,Matcher<const std::string &> matcher)8631   DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
8632       : statement_(a_statement),
8633         matcher_(std::move(matcher)),
8634         spawned_(false),
8635         status_(-1),
8636         outcome_(IN_PROGRESS),
8637         read_fd_(-1),
8638         write_fd_(-1) {}
8639 
8640   // read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl()8641   ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
8642 
8643   void Abort(AbortReason reason) override;
8644   bool Passed(bool status_ok) override;
8645 
statement() const8646   const char* statement() const { return statement_; }
spawned() const8647   bool spawned() const { return spawned_; }
set_spawned(bool is_spawned)8648   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
status() const8649   int status() const { return status_; }
set_status(int a_status)8650   void set_status(int a_status) { status_ = a_status; }
outcome() const8651   DeathTestOutcome outcome() const { return outcome_; }
set_outcome(DeathTestOutcome an_outcome)8652   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
read_fd() const8653   int read_fd() const { return read_fd_; }
set_read_fd(int fd)8654   void set_read_fd(int fd) { read_fd_ = fd; }
write_fd() const8655   int write_fd() const { return write_fd_; }
set_write_fd(int fd)8656   void set_write_fd(int fd) { write_fd_ = fd; }
8657 
8658   // Called in the parent process only. Reads the result code of the death
8659   // test child process via a pipe, interprets it to set the outcome_
8660   // member, and closes read_fd_.  Outputs diagnostics and terminates in
8661   // case of unexpected codes.
8662   void ReadAndInterpretStatusByte();
8663 
8664   // Returns stderr output from the child process.
8665   virtual std::string GetErrorLogs();
8666 
8667  private:
8668   // The textual content of the code this object is testing.  This class
8669   // doesn't own this string and should not attempt to delete it.
8670   const char* const statement_;
8671   // A matcher that's expected to match the stderr output by the child process.
8672   Matcher<const std::string&> matcher_;
8673   // True if the death test child process has been successfully spawned.
8674   bool spawned_;
8675   // The exit status of the child process.
8676   int status_;
8677   // How the death test concluded.
8678   DeathTestOutcome outcome_;
8679   // Descriptor to the read end of the pipe to the child process.  It is
8680   // always -1 in the child process.  The child keeps its write end of the
8681   // pipe in write_fd_.
8682   int read_fd_;
8683   // Descriptor to the child's write end of the pipe to the parent process.
8684   // It is always -1 in the parent process.  The parent keeps its end of the
8685   // pipe in read_fd_.
8686   int write_fd_;
8687 };
8688 
8689 // Called in the parent process only. Reads the result code of the death
8690 // test child process via a pipe, interprets it to set the outcome_
8691 // member, and closes read_fd_.  Outputs diagnostics and terminates in
8692 // case of unexpected codes.
ReadAndInterpretStatusByte()8693 void DeathTestImpl::ReadAndInterpretStatusByte() {
8694   char flag;
8695   int bytes_read;
8696 
8697   // The read() here blocks until data is available (signifying the
8698   // failure of the death test) or until the pipe is closed (signifying
8699   // its success), so it's okay to call this in the parent before
8700   // the child process has exited.
8701   do {
8702     bytes_read = posix::Read(read_fd(), &flag, 1);
8703   } while (bytes_read == -1 && errno == EINTR);
8704 
8705   if (bytes_read == 0) {
8706     set_outcome(DIED);
8707   } else if (bytes_read == 1) {
8708     switch (flag) {
8709       case kDeathTestReturned:
8710         set_outcome(RETURNED);
8711         break;
8712       case kDeathTestThrew:
8713         set_outcome(THREW);
8714         break;
8715       case kDeathTestLived:
8716         set_outcome(LIVED);
8717         break;
8718       case kDeathTestInternalError:
8719         FailFromInternalError(read_fd());  // Does not return.
8720         break;
8721       default:
8722         GTEST_LOG_(FATAL) << "Death test child process reported "
8723                           << "unexpected status byte ("
8724                           << static_cast<unsigned int>(flag) << ")";
8725     }
8726   } else {
8727     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
8728                       << GetLastErrnoDescription();
8729   }
8730   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
8731   set_read_fd(-1);
8732 }
8733 
GetErrorLogs()8734 std::string DeathTestImpl::GetErrorLogs() {
8735   return GetCapturedStderr();
8736 }
8737 
8738 // Signals that the death test code which should have exited, didn't.
8739 // Should be called only in a death test child process.
8740 // Writes a status byte to the child's status file descriptor, then
8741 // calls _exit(1).
Abort(AbortReason reason)8742 void DeathTestImpl::Abort(AbortReason reason) {
8743   // The parent process considers the death test to be a failure if
8744   // it finds any data in our pipe.  So, here we write a single flag byte
8745   // to the pipe, then exit.
8746   const char status_ch =
8747       reason == TEST_DID_NOT_DIE ? kDeathTestLived :
8748       reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
8749 
8750   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
8751   // We are leaking the descriptor here because on some platforms (i.e.,
8752   // when built as Windows DLL), destructors of global objects will still
8753   // run after calling _exit(). On such systems, write_fd_ will be
8754   // indirectly closed from the destructor of UnitTestImpl, causing double
8755   // close if it is also closed here. On debug configurations, double close
8756   // may assert. As there are no in-process buffers to flush here, we are
8757   // relying on the OS to close the descriptor after the process terminates
8758   // when the destructors are not run.
8759   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
8760 }
8761 
8762 // Returns an indented copy of stderr output for a death test.
8763 // This makes distinguishing death test output lines from regular log lines
8764 // much easier.
FormatDeathTestOutput(const::std::string & output)8765 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
8766   ::std::string ret;
8767   for (size_t at = 0; ; ) {
8768     const size_t line_end = output.find('\n', at);
8769     ret += "[  DEATH   ] ";
8770     if (line_end == ::std::string::npos) {
8771       ret += output.substr(at);
8772       break;
8773     }
8774     ret += output.substr(at, line_end + 1 - at);
8775     at = line_end + 1;
8776   }
8777   return ret;
8778 }
8779 
8780 // Assesses the success or failure of a death test, using both private
8781 // members which have previously been set, and one argument:
8782 //
8783 // Private data members:
8784 //   outcome:  An enumeration describing how the death test
8785 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
8786 //             fails in the latter three cases.
8787 //   status:   The exit status of the child process. On *nix, it is in the
8788 //             in the format specified by wait(2). On Windows, this is the
8789 //             value supplied to the ExitProcess() API or a numeric code
8790 //             of the exception that terminated the program.
8791 //   matcher_: A matcher that's expected to match the stderr output by the child
8792 //             process.
8793 //
8794 // Argument:
8795 //   status_ok: true if exit_status is acceptable in the context of
8796 //              this particular death test, which fails if it is false
8797 //
8798 // Returns true if and only if all of the above conditions are met.  Otherwise,
8799 // the first failing condition, in the order given above, is the one that is
8800 // reported. Also sets the last death test message string.
Passed(bool status_ok)8801 bool DeathTestImpl::Passed(bool status_ok) {
8802   if (!spawned())
8803     return false;
8804 
8805   const std::string error_message = GetErrorLogs();
8806 
8807   bool success = false;
8808   Message buffer;
8809 
8810   buffer << "Death test: " << statement() << "\n";
8811   switch (outcome()) {
8812     case LIVED:
8813       buffer << "    Result: failed to die.\n"
8814              << " Error msg:\n" << FormatDeathTestOutput(error_message);
8815       break;
8816     case THREW:
8817       buffer << "    Result: threw an exception.\n"
8818              << " Error msg:\n" << FormatDeathTestOutput(error_message);
8819       break;
8820     case RETURNED:
8821       buffer << "    Result: illegal return in test statement.\n"
8822              << " Error msg:\n" << FormatDeathTestOutput(error_message);
8823       break;
8824     case DIED:
8825       if (status_ok) {
8826         if (matcher_.Matches(error_message)) {
8827           success = true;
8828         } else {
8829           std::ostringstream stream;
8830           matcher_.DescribeTo(&stream);
8831           buffer << "    Result: died but not with expected error.\n"
8832                  << "  Expected: " << stream.str() << "\n"
8833                  << "Actual msg:\n"
8834                  << FormatDeathTestOutput(error_message);
8835         }
8836       } else {
8837         buffer << "    Result: died but not with expected exit code:\n"
8838                << "            " << ExitSummary(status()) << "\n"
8839                << "Actual msg:\n" << FormatDeathTestOutput(error_message);
8840       }
8841       break;
8842     case IN_PROGRESS:
8843     default:
8844       GTEST_LOG_(FATAL)
8845           << "DeathTest::Passed somehow called before conclusion of test";
8846   }
8847 
8848   DeathTest::set_last_death_test_message(buffer.GetString());
8849   return success;
8850 }
8851 
8852 # if GTEST_OS_WINDOWS
8853 // WindowsDeathTest implements death tests on Windows. Due to the
8854 // specifics of starting new processes on Windows, death tests there are
8855 // always threadsafe, and Google Test considers the
8856 // --gtest_death_test_style=fast setting to be equivalent to
8857 // --gtest_death_test_style=threadsafe there.
8858 //
8859 // A few implementation notes:  Like the Linux version, the Windows
8860 // implementation uses pipes for child-to-parent communication. But due to
8861 // the specifics of pipes on Windows, some extra steps are required:
8862 //
8863 // 1. The parent creates a communication pipe and stores handles to both
8864 //    ends of it.
8865 // 2. The parent starts the child and provides it with the information
8866 //    necessary to acquire the handle to the write end of the pipe.
8867 // 3. The child acquires the write end of the pipe and signals the parent
8868 //    using a Windows event.
8869 // 4. Now the parent can release the write end of the pipe on its side. If
8870 //    this is done before step 3, the object's reference count goes down to
8871 //    0 and it is destroyed, preventing the child from acquiring it. The
8872 //    parent now has to release it, or read operations on the read end of
8873 //    the pipe will not return when the child terminates.
8874 // 5. The parent reads child's output through the pipe (outcome code and
8875 //    any possible error messages) from the pipe, and its stderr and then
8876 //    determines whether to fail the test.
8877 //
8878 // Note: to distinguish Win32 API calls from the local method and function
8879 // calls, the former are explicitly resolved in the global namespace.
8880 //
8881 class WindowsDeathTest : public DeathTestImpl {
8882  public:
WindowsDeathTest(const char * a_statement,Matcher<const std::string &> matcher,const char * file,int line)8883   WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8884                    const char* file, int line)
8885       : DeathTestImpl(a_statement, std::move(matcher)),
8886         file_(file),
8887         line_(line) {}
8888 
8889   // All of these virtual functions are inherited from DeathTest.
8890   virtual int Wait();
8891   virtual TestRole AssumeRole();
8892 
8893  private:
8894   // The name of the file in which the death test is located.
8895   const char* const file_;
8896   // The line number on which the death test is located.
8897   const int line_;
8898   // Handle to the write end of the pipe to the child process.
8899   AutoHandle write_handle_;
8900   // Child process handle.
8901   AutoHandle child_handle_;
8902   // Event the child process uses to signal the parent that it has
8903   // acquired the handle to the write end of the pipe. After seeing this
8904   // event the parent can release its own handles to make sure its
8905   // ReadFile() calls return when the child terminates.
8906   AutoHandle event_handle_;
8907 };
8908 
8909 // Waits for the child in a death test to exit, returning its exit
8910 // status, or 0 if no child process exists.  As a side effect, sets the
8911 // outcome data member.
Wait()8912 int WindowsDeathTest::Wait() {
8913   if (!spawned())
8914     return 0;
8915 
8916   // Wait until the child either signals that it has acquired the write end
8917   // of the pipe or it dies.
8918   const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8919   switch (::WaitForMultipleObjects(2,
8920                                    wait_handles,
8921                                    FALSE,  // Waits for any of the handles.
8922                                    INFINITE)) {
8923     case WAIT_OBJECT_0:
8924     case WAIT_OBJECT_0 + 1:
8925       break;
8926     default:
8927       GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
8928   }
8929 
8930   // The child has acquired the write end of the pipe or exited.
8931   // We release the handle on our side and continue.
8932   write_handle_.Reset();
8933   event_handle_.Reset();
8934 
8935   ReadAndInterpretStatusByte();
8936 
8937   // Waits for the child process to exit if it haven't already. This
8938   // returns immediately if the child has already exited, regardless of
8939   // whether previous calls to WaitForMultipleObjects synchronized on this
8940   // handle or not.
8941   GTEST_DEATH_TEST_CHECK_(
8942       WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8943                                              INFINITE));
8944   DWORD status_code;
8945   GTEST_DEATH_TEST_CHECK_(
8946       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8947   child_handle_.Reset();
8948   set_status(static_cast<int>(status_code));
8949   return status();
8950 }
8951 
8952 // The AssumeRole process for a Windows death test.  It creates a child
8953 // process with the same executable as the current process to run the
8954 // death test.  The child process is given the --gtest_filter and
8955 // --gtest_internal_run_death_test flags such that it knows to run the
8956 // current death test only.
AssumeRole()8957 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8958   const UnitTestImpl* const impl = GetUnitTestImpl();
8959   const InternalRunDeathTestFlag* const flag =
8960       impl->internal_run_death_test_flag();
8961   const TestInfo* const info = impl->current_test_info();
8962   const int death_test_index = info->result()->death_test_count();
8963 
8964   if (flag != nullptr) {
8965     // ParseInternalRunDeathTestFlag() has performed all the necessary
8966     // processing.
8967     set_write_fd(flag->write_fd());
8968     return EXECUTE_TEST;
8969   }
8970 
8971   // WindowsDeathTest uses an anonymous pipe to communicate results of
8972   // a death test.
8973   SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
8974                                                  nullptr, TRUE};
8975   HANDLE read_handle, write_handle;
8976   GTEST_DEATH_TEST_CHECK_(
8977       ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8978                    0)  // Default buffer size.
8979       != FALSE);
8980   set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8981                                 O_RDONLY));
8982   write_handle_.Reset(write_handle);
8983   event_handle_.Reset(::CreateEvent(
8984       &handles_are_inheritable,
8985       TRUE,       // The event will automatically reset to non-signaled state.
8986       FALSE,      // The initial state is non-signalled.
8987       nullptr));  // The even is unnamed.
8988   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
8989   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8990                                   kFilterFlag + "=" + info->test_suite_name() +
8991                                   "." + info->name();
8992   const std::string internal_flag =
8993       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
8994       "=" + file_ + "|" + StreamableToString(line_) + "|" +
8995       StreamableToString(death_test_index) + "|" +
8996       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
8997       // size_t has the same width as pointers on both 32-bit and 64-bit
8998       // Windows platforms.
8999       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
9000       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
9001       "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
9002 
9003   char executable_path[_MAX_PATH + 1];  // NOLINT
9004   GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
9005                                                                 executable_path,
9006                                                                 _MAX_PATH));
9007 
9008   std::string command_line =
9009       std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
9010       internal_flag + "\"";
9011 
9012   DeathTest::set_last_death_test_message("");
9013 
9014   CaptureStderr();
9015   // Flush the log buffers since the log streams are shared with the child.
9016   FlushInfoLog();
9017 
9018   // The child process will share the standard handles with the parent.
9019   STARTUPINFOA startup_info;
9020   memset(&startup_info, 0, sizeof(STARTUPINFO));
9021   startup_info.dwFlags = STARTF_USESTDHANDLES;
9022   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
9023   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
9024   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
9025 
9026   PROCESS_INFORMATION process_info;
9027   GTEST_DEATH_TEST_CHECK_(
9028       ::CreateProcessA(
9029           executable_path, const_cast<char*>(command_line.c_str()),
9030           nullptr,  // Retuned process handle is not inheritable.
9031           nullptr,  // Retuned thread handle is not inheritable.
9032           TRUE,  // Child inherits all inheritable handles (for write_handle_).
9033           0x0,   // Default creation flags.
9034           nullptr,  // Inherit the parent's environment.
9035           UnitTest::GetInstance()->original_working_dir(), &startup_info,
9036           &process_info) != FALSE);
9037   child_handle_.Reset(process_info.hProcess);
9038   ::CloseHandle(process_info.hThread);
9039   set_spawned(true);
9040   return OVERSEE_TEST;
9041 }
9042 
9043 # elif GTEST_OS_FUCHSIA
9044 
9045 class FuchsiaDeathTest : public DeathTestImpl {
9046  public:
FuchsiaDeathTest(const char * a_statement,Matcher<const std::string &> matcher,const char * file,int line)9047   FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
9048                    const char* file, int line)
9049       : DeathTestImpl(a_statement, std::move(matcher)),
9050         file_(file),
9051         line_(line) {}
9052 
9053   // All of these virtual functions are inherited from DeathTest.
9054   int Wait() override;
9055   TestRole AssumeRole() override;
9056   std::string GetErrorLogs() override;
9057 
9058  private:
9059   // The name of the file in which the death test is located.
9060   const char* const file_;
9061   // The line number on which the death test is located.
9062   const int line_;
9063   // The stderr data captured by the child process.
9064   std::string captured_stderr_;
9065 
9066   zx::process child_process_;
9067   zx::channel exception_channel_;
9068   zx::socket stderr_socket_;
9069 };
9070 
9071 // Utility class for accumulating command-line arguments.
9072 class Arguments {
9073  public:
Arguments()9074   Arguments() { args_.push_back(nullptr); }
9075 
~Arguments()9076   ~Arguments() {
9077     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
9078          ++i) {
9079       free(*i);
9080     }
9081   }
AddArgument(const char * argument)9082   void AddArgument(const char* argument) {
9083     args_.insert(args_.end() - 1, posix::StrDup(argument));
9084   }
9085 
9086   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)9087   void AddArguments(const ::std::vector<Str>& arguments) {
9088     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
9089          i != arguments.end();
9090          ++i) {
9091       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
9092     }
9093   }
Argv()9094   char* const* Argv() {
9095     return &args_[0];
9096   }
9097 
size()9098   int size() {
9099     return static_cast<int>(args_.size()) - 1;
9100   }
9101 
9102  private:
9103   std::vector<char*> args_;
9104 };
9105 
9106 // Waits for the child in a death test to exit, returning its exit
9107 // status, or 0 if no child process exists.  As a side effect, sets the
9108 // outcome data member.
Wait()9109 int FuchsiaDeathTest::Wait() {
9110   const int kProcessKey = 0;
9111   const int kSocketKey = 1;
9112   const int kExceptionKey = 2;
9113 
9114   if (!spawned())
9115     return 0;
9116 
9117   // Create a port to wait for socket/task/exception events.
9118   zx_status_t status_zx;
9119   zx::port port;
9120   status_zx = zx::port::create(0, &port);
9121   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9122 
9123   // Register to wait for the child process to terminate.
9124   status_zx = child_process_.wait_async(
9125       port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
9126   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9127 
9128   // Register to wait for the socket to be readable or closed.
9129   status_zx = stderr_socket_.wait_async(
9130       port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
9131   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9132 
9133   // Register to wait for an exception.
9134   status_zx = exception_channel_.wait_async(
9135       port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
9136   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9137 
9138   bool process_terminated = false;
9139   bool socket_closed = false;
9140   do {
9141     zx_port_packet_t packet = {};
9142     status_zx = port.wait(zx::time::infinite(), &packet);
9143     GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9144 
9145     if (packet.key == kExceptionKey) {
9146       // Process encountered an exception. Kill it directly rather than
9147       // letting other handlers process the event. We will get a kProcessKey
9148       // event when the process actually terminates.
9149       status_zx = child_process_.kill();
9150       GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9151     } else if (packet.key == kProcessKey) {
9152       // Process terminated.
9153       GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
9154       GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
9155       process_terminated = true;
9156     } else if (packet.key == kSocketKey) {
9157       GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
9158       if (packet.signal.observed & ZX_SOCKET_READABLE) {
9159         // Read data from the socket.
9160         constexpr size_t kBufferSize = 1024;
9161         do {
9162           size_t old_length = captured_stderr_.length();
9163           size_t bytes_read = 0;
9164           captured_stderr_.resize(old_length + kBufferSize);
9165           status_zx = stderr_socket_.read(
9166               0, &captured_stderr_.front() + old_length, kBufferSize,
9167               &bytes_read);
9168           captured_stderr_.resize(old_length + bytes_read);
9169         } while (status_zx == ZX_OK);
9170         if (status_zx == ZX_ERR_PEER_CLOSED) {
9171           socket_closed = true;
9172         } else {
9173           GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
9174           status_zx = stderr_socket_.wait_async(
9175               port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
9176           GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9177         }
9178       } else {
9179         GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
9180         socket_closed = true;
9181       }
9182     }
9183   } while (!process_terminated && !socket_closed);
9184 
9185   ReadAndInterpretStatusByte();
9186 
9187   zx_info_process_t buffer;
9188   status_zx = child_process_.get_info(ZX_INFO_PROCESS, &buffer, sizeof(buffer),
9189                                       nullptr, nullptr);
9190   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
9191 
9192   GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
9193   set_status(static_cast<int>(buffer.return_code));
9194   return status();
9195 }
9196 
9197 // The AssumeRole process for a Fuchsia death test.  It creates a child
9198 // process with the same executable as the current process to run the
9199 // death test.  The child process is given the --gtest_filter and
9200 // --gtest_internal_run_death_test flags such that it knows to run the
9201 // current death test only.
AssumeRole()9202 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
9203   const UnitTestImpl* const impl = GetUnitTestImpl();
9204   const InternalRunDeathTestFlag* const flag =
9205       impl->internal_run_death_test_flag();
9206   const TestInfo* const info = impl->current_test_info();
9207   const int death_test_index = info->result()->death_test_count();
9208 
9209   if (flag != nullptr) {
9210     // ParseInternalRunDeathTestFlag() has performed all the necessary
9211     // processing.
9212     set_write_fd(kFuchsiaReadPipeFd);
9213     return EXECUTE_TEST;
9214   }
9215 
9216   // Flush the log buffers since the log streams are shared with the child.
9217   FlushInfoLog();
9218 
9219   // Build the child process command line.
9220   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
9221                                   kFilterFlag + "=" + info->test_suite_name() +
9222                                   "." + info->name();
9223   const std::string internal_flag =
9224       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
9225       + file_ + "|"
9226       + StreamableToString(line_) + "|"
9227       + StreamableToString(death_test_index);
9228   Arguments args;
9229   args.AddArguments(GetInjectableArgvs());
9230   args.AddArgument(filter_flag.c_str());
9231   args.AddArgument(internal_flag.c_str());
9232 
9233   // Build the pipe for communication with the child.
9234   zx_status_t status;
9235   zx_handle_t child_pipe_handle;
9236   int child_pipe_fd;
9237   status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);
9238   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9239   set_read_fd(child_pipe_fd);
9240 
9241   // Set the pipe handle for the child.
9242   fdio_spawn_action_t spawn_actions[2] = {};
9243   fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
9244   add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
9245   add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
9246   add_handle_action->h.handle = child_pipe_handle;
9247 
9248   // Create a socket pair will be used to receive the child process' stderr.
9249   zx::socket stderr_producer_socket;
9250   status =
9251       zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
9252   GTEST_DEATH_TEST_CHECK_(status >= 0);
9253   int stderr_producer_fd = -1;
9254   status =
9255       fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
9256   GTEST_DEATH_TEST_CHECK_(status >= 0);
9257 
9258   // Make the stderr socket nonblocking.
9259   GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
9260 
9261   fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
9262   add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
9263   add_stderr_action->fd.local_fd = stderr_producer_fd;
9264   add_stderr_action->fd.target_fd = STDERR_FILENO;
9265 
9266   // Create a child job.
9267   zx_handle_t child_job = ZX_HANDLE_INVALID;
9268   status = zx_job_create(zx_job_default(), 0, & child_job);
9269   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9270   zx_policy_basic_t policy;
9271   policy.condition = ZX_POL_NEW_ANY;
9272   policy.policy = ZX_POL_ACTION_ALLOW;
9273   status = zx_job_set_policy(
9274       child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
9275   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9276 
9277   // Create an exception channel attached to the |child_job|, to allow
9278   // us to suppress the system default exception handler from firing.
9279   status =
9280       zx_task_create_exception_channel(
9281           child_job, 0, exception_channel_.reset_and_get_address());
9282   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9283 
9284   // Spawn the child process.
9285   status = fdio_spawn_etc(
9286       child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
9287       2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
9288   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
9289 
9290   set_spawned(true);
9291   return OVERSEE_TEST;
9292 }
9293 
GetErrorLogs()9294 std::string FuchsiaDeathTest::GetErrorLogs() {
9295   return captured_stderr_;
9296 }
9297 
9298 #else  // We are neither on Windows, nor on Fuchsia.
9299 
9300 // ForkingDeathTest provides implementations for most of the abstract
9301 // methods of the DeathTest interface.  Only the AssumeRole method is
9302 // left undefined.
9303 class ForkingDeathTest : public DeathTestImpl {
9304  public:
9305   ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
9306 
9307   // All of these virtual functions are inherited from DeathTest.
9308   int Wait() override;
9309 
9310  protected:
set_child_pid(pid_t child_pid)9311   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
9312 
9313  private:
9314   // PID of child process during death test; 0 in the child process itself.
9315   pid_t child_pid_;
9316 };
9317 
9318 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * a_statement,Matcher<const std::string &> matcher)9319 ForkingDeathTest::ForkingDeathTest(const char* a_statement,
9320                                    Matcher<const std::string&> matcher)
9321     : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
9322 
9323 // Waits for the child in a death test to exit, returning its exit
9324 // status, or 0 if no child process exists.  As a side effect, sets the
9325 // outcome data member.
Wait()9326 int ForkingDeathTest::Wait() {
9327   if (!spawned())
9328     return 0;
9329 
9330   ReadAndInterpretStatusByte();
9331 
9332   int status_value;
9333   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
9334   set_status(status_value);
9335   return status_value;
9336 }
9337 
9338 // A concrete death test class that forks, then immediately runs the test
9339 // in the child process.
9340 class NoExecDeathTest : public ForkingDeathTest {
9341  public:
NoExecDeathTest(const char * a_statement,Matcher<const std::string &> matcher)9342   NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
9343       : ForkingDeathTest(a_statement, std::move(matcher)) {}
9344   TestRole AssumeRole() override;
9345 };
9346 
9347 // The AssumeRole process for a fork-and-run death test.  It implements a
9348 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()9349 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
9350   const size_t thread_count = GetThreadCount();
9351   if (thread_count != 1) {
9352     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
9353   }
9354 
9355   int pipe_fd[2];
9356   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
9357 
9358   DeathTest::set_last_death_test_message("");
9359   CaptureStderr();
9360   // When we fork the process below, the log file buffers are copied, but the
9361   // file descriptors are shared.  We flush all log files here so that closing
9362   // the file descriptors in the child process doesn't throw off the
9363   // synchronization between descriptors and buffers in the parent process.
9364   // This is as close to the fork as possible to avoid a race condition in case
9365   // there are multiple threads running before the death test, and another
9366   // thread writes to the log file.
9367   FlushInfoLog();
9368 
9369   const pid_t child_pid = fork();
9370   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
9371   set_child_pid(child_pid);
9372   if (child_pid == 0) {
9373     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
9374     set_write_fd(pipe_fd[1]);
9375     // Redirects all logging to stderr in the child process to prevent
9376     // concurrent writes to the log files.  We capture stderr in the parent
9377     // process and append the child process' output to a log.
9378     LogToStderr();
9379     // Event forwarding to the listeners of event listener API mush be shut
9380     // down in death test subprocesses.
9381     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
9382     g_in_fast_death_test_child = true;
9383     return EXECUTE_TEST;
9384   } else {
9385     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
9386     set_read_fd(pipe_fd[0]);
9387     set_spawned(true);
9388     return OVERSEE_TEST;
9389   }
9390 }
9391 
9392 // A concrete death test class that forks and re-executes the main
9393 // program from the beginning, with command-line flags set that cause
9394 // only this specific death test to be run.
9395 class ExecDeathTest : public ForkingDeathTest {
9396  public:
ExecDeathTest(const char * a_statement,Matcher<const std::string &> matcher,const char * file,int line)9397   ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
9398                 const char* file, int line)
9399       : ForkingDeathTest(a_statement, std::move(matcher)),
9400         file_(file),
9401         line_(line) {}
9402   TestRole AssumeRole() override;
9403 
9404  private:
GetArgvsForDeathTestChildProcess()9405   static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
9406     ::std::vector<std::string> args = GetInjectableArgvs();
9407 #  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
9408     ::std::vector<std::string> extra_args =
9409         GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
9410     args.insert(args.end(), extra_args.begin(), extra_args.end());
9411 #  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
9412     return args;
9413   }
9414   // The name of the file in which the death test is located.
9415   const char* const file_;
9416   // The line number on which the death test is located.
9417   const int line_;
9418 };
9419 
9420 // Utility class for accumulating command-line arguments.
9421 class Arguments {
9422  public:
Arguments()9423   Arguments() { args_.push_back(nullptr); }
9424 
~Arguments()9425   ~Arguments() {
9426     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
9427          ++i) {
9428       free(*i);
9429     }
9430   }
AddArgument(const char * argument)9431   void AddArgument(const char* argument) {
9432     args_.insert(args_.end() - 1, posix::StrDup(argument));
9433   }
9434 
9435   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)9436   void AddArguments(const ::std::vector<Str>& arguments) {
9437     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
9438          i != arguments.end();
9439          ++i) {
9440       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
9441     }
9442   }
Argv()9443   char* const* Argv() {
9444     return &args_[0];
9445   }
9446 
9447  private:
9448   std::vector<char*> args_;
9449 };
9450 
9451 // A struct that encompasses the arguments to the child process of a
9452 // threadsafe-style death test process.
9453 struct ExecDeathTestArgs {
9454   char* const* argv;  // Command-line arguments for the child's call to exec
9455   int close_fd;       // File descriptor to close; the read end of a pipe
9456 };
9457 
9458 #  if GTEST_OS_QNX
9459 extern "C" char** environ;
9460 #  else  // GTEST_OS_QNX
9461 // The main function for a threadsafe-style death test child process.
9462 // This function is called in a clone()-ed process and thus must avoid
9463 // any potentially unsafe operations like malloc or libc functions.
ExecDeathTestChildMain(void * child_arg)9464 static int ExecDeathTestChildMain(void* child_arg) {
9465   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
9466   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
9467 
9468   // We need to execute the test program in the same environment where
9469   // it was originally invoked.  Therefore we change to the original
9470   // working directory first.
9471   const char* const original_dir =
9472       UnitTest::GetInstance()->original_working_dir();
9473   // We can safely call chdir() as it's a direct system call.
9474   if (chdir(original_dir) != 0) {
9475     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
9476                    GetLastErrnoDescription());
9477     return EXIT_FAILURE;
9478   }
9479 
9480   // We can safely call execv() as it's almost a direct system call. We
9481   // cannot use execvp() as it's a libc function and thus potentially
9482   // unsafe.  Since execv() doesn't search the PATH, the user must
9483   // invoke the test program via a valid path that contains at least
9484   // one path separator.
9485   execv(args->argv[0], args->argv);
9486   DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
9487                  original_dir + " failed: " +
9488                  GetLastErrnoDescription());
9489   return EXIT_FAILURE;
9490 }
9491 #  endif  // GTEST_OS_QNX
9492 
9493 #  if GTEST_HAS_CLONE
9494 // Two utility routines that together determine the direction the stack
9495 // grows.
9496 // This could be accomplished more elegantly by a single recursive
9497 // function, but we want to guard against the unlikely possibility of
9498 // a smart compiler optimizing the recursion away.
9499 //
9500 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
9501 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
9502 // correct answer.
9503 static void StackLowerThanAddress(const void* ptr,
9504                                   bool* result) GTEST_NO_INLINE_;
9505 // Make sure sanitizers do not tamper with the stack here.
9506 // Ideally, we want to use `__builtin_frame_address` instead of a local variable
9507 // address with sanitizer disabled, but it does not work when the
9508 // compiler optimizes the stack frame out, which happens on PowerPC targets.
9509 // HWAddressSanitizer add a random tag to the MSB of the local variable address,
9510 // making comparison result unpredictable.
9511 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
9512 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
StackLowerThanAddress(const void * ptr,bool * result)9513 static void StackLowerThanAddress(const void* ptr, bool* result) {
9514   int dummy = 0;
9515   *result = std::less<const void*>()(&dummy, ptr);
9516 }
9517 
9518 // Make sure AddressSanitizer does not tamper with the stack here.
9519 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
9520 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
StackGrowsDown()9521 static bool StackGrowsDown() {
9522   int dummy = 0;
9523   bool result;
9524   StackLowerThanAddress(&dummy, &result);
9525   return result;
9526 }
9527 #  endif  // GTEST_HAS_CLONE
9528 
9529 // Spawns a child process with the same executable as the current process in
9530 // a thread-safe manner and instructs it to run the death test.  The
9531 // implementation uses fork(2) + exec.  On systems where clone(2) is
9532 // available, it is used instead, being slightly more thread-safe.  On QNX,
9533 // fork supports only single-threaded environments, so this function uses
9534 // spawn(2) there instead.  The function dies with an error message if
9535 // anything goes wrong.
ExecDeathTestSpawnChild(char * const * argv,int close_fd)9536 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
9537   ExecDeathTestArgs args = { argv, close_fd };
9538   pid_t child_pid = -1;
9539 
9540 #  if GTEST_OS_QNX
9541   // Obtains the current directory and sets it to be closed in the child
9542   // process.
9543   const int cwd_fd = open(".", O_RDONLY);
9544   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
9545   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
9546   // We need to execute the test program in the same environment where
9547   // it was originally invoked.  Therefore we change to the original
9548   // working directory first.
9549   const char* const original_dir =
9550       UnitTest::GetInstance()->original_working_dir();
9551   // We can safely call chdir() as it's a direct system call.
9552   if (chdir(original_dir) != 0) {
9553     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
9554                    GetLastErrnoDescription());
9555     return EXIT_FAILURE;
9556   }
9557 
9558   int fd_flags;
9559   // Set close_fd to be closed after spawn.
9560   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
9561   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
9562                                         fd_flags | FD_CLOEXEC));
9563   struct inheritance inherit = {0};
9564   // spawn is a system call.
9565   child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
9566   // Restores the current working directory.
9567   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
9568   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
9569 
9570 #  else   // GTEST_OS_QNX
9571 #   if GTEST_OS_LINUX
9572   // When a SIGPROF signal is received while fork() or clone() are executing,
9573   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
9574   // it after the call to fork()/clone() is complete.
9575   struct sigaction saved_sigprof_action;
9576   struct sigaction ignore_sigprof_action;
9577   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
9578   sigemptyset(&ignore_sigprof_action.sa_mask);
9579   ignore_sigprof_action.sa_handler = SIG_IGN;
9580   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
9581       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
9582 #   endif  // GTEST_OS_LINUX
9583 
9584 #   if GTEST_HAS_CLONE
9585   const bool use_fork = GTEST_FLAG(death_test_use_fork);
9586 
9587   if (!use_fork) {
9588     static const bool stack_grows_down = StackGrowsDown();
9589     const auto stack_size = static_cast<size_t>(getpagesize() * 2);
9590     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
9591     void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
9592                              MAP_ANON | MAP_PRIVATE, -1, 0);
9593     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
9594 
9595     // Maximum stack alignment in bytes:  For a downward-growing stack, this
9596     // amount is subtracted from size of the stack space to get an address
9597     // that is within the stack space and is aligned on all systems we care
9598     // about.  As far as I know there is no ABI with stack alignment greater
9599     // than 64.  We assume stack and stack_size already have alignment of
9600     // kMaxStackAlignment.
9601     const size_t kMaxStackAlignment = 64;
9602     void* const stack_top =
9603         static_cast<char*>(stack) +
9604             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
9605     GTEST_DEATH_TEST_CHECK_(
9606         static_cast<size_t>(stack_size) > kMaxStackAlignment &&
9607         reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);
9608 
9609     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
9610 
9611     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
9612   }
9613 #   else
9614   const bool use_fork = true;
9615 #   endif  // GTEST_HAS_CLONE
9616 
9617   if (use_fork && (child_pid = fork()) == 0) {
9618       ExecDeathTestChildMain(&args);
9619       _exit(0);
9620   }
9621 #  endif  // GTEST_OS_QNX
9622 #  if GTEST_OS_LINUX
9623   GTEST_DEATH_TEST_CHECK_SYSCALL_(
9624       sigaction(SIGPROF, &saved_sigprof_action, nullptr));
9625 #  endif  // GTEST_OS_LINUX
9626 
9627   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
9628   return child_pid;
9629 }
9630 
9631 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
9632 // main program from the beginning, setting the --gtest_filter
9633 // and --gtest_internal_run_death_test flags to cause only the current
9634 // death test to be re-run.
AssumeRole()9635 DeathTest::TestRole ExecDeathTest::AssumeRole() {
9636   const UnitTestImpl* const impl = GetUnitTestImpl();
9637   const InternalRunDeathTestFlag* const flag =
9638       impl->internal_run_death_test_flag();
9639   const TestInfo* const info = impl->current_test_info();
9640   const int death_test_index = info->result()->death_test_count();
9641 
9642   if (flag != nullptr) {
9643     set_write_fd(flag->write_fd());
9644     return EXECUTE_TEST;
9645   }
9646 
9647   int pipe_fd[2];
9648   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
9649   // Clear the close-on-exec flag on the write end of the pipe, lest
9650   // it be closed when the child process does an exec:
9651   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
9652 
9653   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
9654                                   kFilterFlag + "=" + info->test_suite_name() +
9655                                   "." + info->name();
9656   const std::string internal_flag =
9657       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
9658       + file_ + "|" + StreamableToString(line_) + "|"
9659       + StreamableToString(death_test_index) + "|"
9660       + StreamableToString(pipe_fd[1]);
9661   Arguments args;
9662   args.AddArguments(GetArgvsForDeathTestChildProcess());
9663   args.AddArgument(filter_flag.c_str());
9664   args.AddArgument(internal_flag.c_str());
9665 
9666   DeathTest::set_last_death_test_message("");
9667 
9668   CaptureStderr();
9669   // See the comment in NoExecDeathTest::AssumeRole for why the next line
9670   // is necessary.
9671   FlushInfoLog();
9672 
9673   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
9674   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
9675   set_child_pid(child_pid);
9676   set_read_fd(pipe_fd[0]);
9677   set_spawned(true);
9678   return OVERSEE_TEST;
9679 }
9680 
9681 # endif  // !GTEST_OS_WINDOWS
9682 
9683 // Creates a concrete DeathTest-derived class that depends on the
9684 // --gtest_death_test_style flag, and sets the pointer pointed to
9685 // by the "test" argument to its address.  If the test should be
9686 // skipped, sets that pointer to NULL.  Returns true, unless the
9687 // flag is set to an invalid value.
Create(const char * statement,Matcher<const std::string &> matcher,const char * file,int line,DeathTest ** test)9688 bool DefaultDeathTestFactory::Create(const char* statement,
9689                                      Matcher<const std::string&> matcher,
9690                                      const char* file, int line,
9691                                      DeathTest** test) {
9692   UnitTestImpl* const impl = GetUnitTestImpl();
9693   const InternalRunDeathTestFlag* const flag =
9694       impl->internal_run_death_test_flag();
9695   const int death_test_index = impl->current_test_info()
9696       ->increment_death_test_count();
9697 
9698   if (flag != nullptr) {
9699     if (death_test_index > flag->index()) {
9700       DeathTest::set_last_death_test_message(
9701           "Death test count (" + StreamableToString(death_test_index)
9702           + ") somehow exceeded expected maximum ("
9703           + StreamableToString(flag->index()) + ")");
9704       return false;
9705     }
9706 
9707     if (!(flag->file() == file && flag->line() == line &&
9708           flag->index() == death_test_index)) {
9709       *test = nullptr;
9710       return true;
9711     }
9712   }
9713 
9714 # if GTEST_OS_WINDOWS
9715 
9716   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9717       GTEST_FLAG(death_test_style) == "fast") {
9718     *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
9719   }
9720 
9721 # elif GTEST_OS_FUCHSIA
9722 
9723   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9724       GTEST_FLAG(death_test_style) == "fast") {
9725     *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
9726   }
9727 
9728 # else
9729 
9730   if (GTEST_FLAG(death_test_style) == "threadsafe") {
9731     *test = new ExecDeathTest(statement, std::move(matcher), file, line);
9732   } else if (GTEST_FLAG(death_test_style) == "fast") {
9733     *test = new NoExecDeathTest(statement, std::move(matcher));
9734   }
9735 
9736 # endif  // GTEST_OS_WINDOWS
9737 
9738   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
9739     DeathTest::set_last_death_test_message(
9740         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
9741         + "\" encountered");
9742     return false;
9743   }
9744 
9745   return true;
9746 }
9747 
9748 # if GTEST_OS_WINDOWS
9749 // Recreates the pipe and event handles from the provided parameters,
9750 // signals the event, and returns a file descriptor wrapped around the pipe
9751 // handle. This function is called in the child process only.
GetStatusFileDescriptor(unsigned int parent_process_id,size_t write_handle_as_size_t,size_t event_handle_as_size_t)9752 static int GetStatusFileDescriptor(unsigned int parent_process_id,
9753                             size_t write_handle_as_size_t,
9754                             size_t event_handle_as_size_t) {
9755   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
9756                                                    FALSE,  // Non-inheritable.
9757                                                    parent_process_id));
9758   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
9759     DeathTestAbort("Unable to open parent process " +
9760                    StreamableToString(parent_process_id));
9761   }
9762 
9763   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
9764 
9765   const HANDLE write_handle =
9766       reinterpret_cast<HANDLE>(write_handle_as_size_t);
9767   HANDLE dup_write_handle;
9768 
9769   // The newly initialized handle is accessible only in the parent
9770   // process. To obtain one accessible within the child, we need to use
9771   // DuplicateHandle.
9772   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
9773                          ::GetCurrentProcess(), &dup_write_handle,
9774                          0x0,    // Requested privileges ignored since
9775                                  // DUPLICATE_SAME_ACCESS is used.
9776                          FALSE,  // Request non-inheritable handler.
9777                          DUPLICATE_SAME_ACCESS)) {
9778     DeathTestAbort("Unable to duplicate the pipe handle " +
9779                    StreamableToString(write_handle_as_size_t) +
9780                    " from the parent process " +
9781                    StreamableToString(parent_process_id));
9782   }
9783 
9784   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
9785   HANDLE dup_event_handle;
9786 
9787   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
9788                          ::GetCurrentProcess(), &dup_event_handle,
9789                          0x0,
9790                          FALSE,
9791                          DUPLICATE_SAME_ACCESS)) {
9792     DeathTestAbort("Unable to duplicate the event handle " +
9793                    StreamableToString(event_handle_as_size_t) +
9794                    " from the parent process " +
9795                    StreamableToString(parent_process_id));
9796   }
9797 
9798   const int write_fd =
9799       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
9800   if (write_fd == -1) {
9801     DeathTestAbort("Unable to convert pipe handle " +
9802                    StreamableToString(write_handle_as_size_t) +
9803                    " to a file descriptor");
9804   }
9805 
9806   // Signals the parent that the write end of the pipe has been acquired
9807   // so the parent can release its own write end.
9808   ::SetEvent(dup_event_handle);
9809 
9810   return write_fd;
9811 }
9812 # endif  // GTEST_OS_WINDOWS
9813 
9814 // Returns a newly created InternalRunDeathTestFlag object with fields
9815 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
9816 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()9817 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
9818   if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
9819 
9820   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
9821   // can use it here.
9822   int line = -1;
9823   int index = -1;
9824   ::std::vector< ::std::string> fields;
9825   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
9826   int write_fd = -1;
9827 
9828 # if GTEST_OS_WINDOWS
9829 
9830   unsigned int parent_process_id = 0;
9831   size_t write_handle_as_size_t = 0;
9832   size_t event_handle_as_size_t = 0;
9833 
9834   if (fields.size() != 6
9835       || !ParseNaturalNumber(fields[1], &line)
9836       || !ParseNaturalNumber(fields[2], &index)
9837       || !ParseNaturalNumber(fields[3], &parent_process_id)
9838       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
9839       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
9840     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
9841                    GTEST_FLAG(internal_run_death_test));
9842   }
9843   write_fd = GetStatusFileDescriptor(parent_process_id,
9844                                      write_handle_as_size_t,
9845                                      event_handle_as_size_t);
9846 
9847 # elif GTEST_OS_FUCHSIA
9848 
9849   if (fields.size() != 3
9850       || !ParseNaturalNumber(fields[1], &line)
9851       || !ParseNaturalNumber(fields[2], &index)) {
9852     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9853         + GTEST_FLAG(internal_run_death_test));
9854   }
9855 
9856 # else
9857 
9858   if (fields.size() != 4
9859       || !ParseNaturalNumber(fields[1], &line)
9860       || !ParseNaturalNumber(fields[2], &index)
9861       || !ParseNaturalNumber(fields[3], &write_fd)) {
9862     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9863         + GTEST_FLAG(internal_run_death_test));
9864   }
9865 
9866 # endif  // GTEST_OS_WINDOWS
9867 
9868   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9869 }
9870 
9871 }  // namespace internal
9872 
9873 #endif  // GTEST_HAS_DEATH_TEST
9874 
9875 }  // namespace testing
9876 // Copyright 2008, Google Inc.
9877 // All rights reserved.
9878 //
9879 // Redistribution and use in source and binary forms, with or without
9880 // modification, are permitted provided that the following conditions are
9881 // met:
9882 //
9883 //     * Redistributions of source code must retain the above copyright
9884 // notice, this list of conditions and the following disclaimer.
9885 //     * Redistributions in binary form must reproduce the above
9886 // copyright notice, this list of conditions and the following disclaimer
9887 // in the documentation and/or other materials provided with the
9888 // distribution.
9889 //     * Neither the name of Google Inc. nor the names of its
9890 // contributors may be used to endorse or promote products derived from
9891 // this software without specific prior written permission.
9892 //
9893 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9894 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9895 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9896 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9897 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9898 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9899 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9900 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9901 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9902 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9903 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9904 
9905 
9906 #include <stdlib.h>
9907 
9908 #if GTEST_OS_WINDOWS_MOBILE
9909 # include <windows.h>
9910 #elif GTEST_OS_WINDOWS
9911 # include <direct.h>
9912 # include <io.h>
9913 #else
9914 # include <limits.h>
9915 # include <climits>  // Some Linux distributions define PATH_MAX here.
9916 #endif  // GTEST_OS_WINDOWS_MOBILE
9917 
9918 
9919 #if GTEST_OS_WINDOWS
9920 # define GTEST_PATH_MAX_ _MAX_PATH
9921 #elif defined(PATH_MAX)
9922 # define GTEST_PATH_MAX_ PATH_MAX
9923 #elif defined(_XOPEN_PATH_MAX)
9924 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
9925 #else
9926 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
9927 #endif  // GTEST_OS_WINDOWS
9928 
9929 namespace testing {
9930 namespace internal {
9931 
9932 #if GTEST_OS_WINDOWS
9933 // On Windows, '\\' is the standard path separator, but many tools and the
9934 // Windows API also accept '/' as an alternate path separator. Unless otherwise
9935 // noted, a file path can contain either kind of path separators, or a mixture
9936 // of them.
9937 const char kPathSeparator = '\\';
9938 const char kAlternatePathSeparator = '/';
9939 const char kAlternatePathSeparatorString[] = "/";
9940 # if GTEST_OS_WINDOWS_MOBILE
9941 // Windows CE doesn't have a current directory. You should not use
9942 // the current directory in tests on Windows CE, but this at least
9943 // provides a reasonable fallback.
9944 const char kCurrentDirectoryString[] = "\\";
9945 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
9946 const DWORD kInvalidFileAttributes = 0xffffffff;
9947 # else
9948 const char kCurrentDirectoryString[] = ".\\";
9949 # endif  // GTEST_OS_WINDOWS_MOBILE
9950 #else
9951 const char kPathSeparator = '/';
9952 const char kCurrentDirectoryString[] = "./";
9953 #endif  // GTEST_OS_WINDOWS
9954 
9955 // Returns whether the given character is a valid path separator.
IsPathSeparator(char c)9956 static bool IsPathSeparator(char c) {
9957 #if GTEST_HAS_ALT_PATH_SEP_
9958   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
9959 #else
9960   return c == kPathSeparator;
9961 #endif
9962 }
9963 
9964 // Returns the current working directory, or "" if unsuccessful.
GetCurrentDir()9965 FilePath FilePath::GetCurrentDir() {
9966 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE ||         \
9967     GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
9968     GTEST_OS_XTENSA
9969   // These platforms do not have a current directory, so we just return
9970   // something reasonable.
9971   return FilePath(kCurrentDirectoryString);
9972 #elif GTEST_OS_WINDOWS
9973   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9974   return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
9975 #else
9976   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9977   char* result = getcwd(cwd, sizeof(cwd));
9978 # if GTEST_OS_NACL
9979   // getcwd will likely fail in NaCl due to the sandbox, so return something
9980   // reasonable. The user may have provided a shim implementation for getcwd,
9981   // however, so fallback only when failure is detected.
9982   return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
9983 # endif  // GTEST_OS_NACL
9984   return FilePath(result == nullptr ? "" : cwd);
9985 #endif  // GTEST_OS_WINDOWS_MOBILE
9986 }
9987 
9988 // Returns a copy of the FilePath with the case-insensitive extension removed.
9989 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
9990 // FilePath("dir/file"). If a case-insensitive extension is not
9991 // found, returns a copy of the original FilePath.
RemoveExtension(const char * extension) const9992 FilePath FilePath::RemoveExtension(const char* extension) const {
9993   const std::string dot_extension = std::string(".") + extension;
9994   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9995     return FilePath(pathname_.substr(
9996         0, pathname_.length() - dot_extension.length()));
9997   }
9998   return *this;
9999 }
10000 
10001 // Returns a pointer to the last occurrence of a valid path separator in
10002 // the FilePath. On Windows, for example, both '/' and '\' are valid path
10003 // separators. Returns NULL if no path separator was found.
FindLastPathSeparator() const10004 const char* FilePath::FindLastPathSeparator() const {
10005   const char* const last_sep = strrchr(c_str(), kPathSeparator);
10006 #if GTEST_HAS_ALT_PATH_SEP_
10007   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
10008   // Comparing two pointers of which only one is NULL is undefined.
10009   if (last_alt_sep != nullptr &&
10010       (last_sep == nullptr || last_alt_sep > last_sep)) {
10011     return last_alt_sep;
10012   }
10013 #endif
10014   return last_sep;
10015 }
10016 
10017 // Returns a copy of the FilePath with the directory part removed.
10018 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
10019 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
10020 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
10021 // returns an empty FilePath ("").
10022 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveDirectoryName() const10023 FilePath FilePath::RemoveDirectoryName() const {
10024   const char* const last_sep = FindLastPathSeparator();
10025   return last_sep ? FilePath(last_sep + 1) : *this;
10026 }
10027 
10028 // RemoveFileName returns the directory path with the filename removed.
10029 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
10030 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
10031 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
10032 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
10033 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveFileName() const10034 FilePath FilePath::RemoveFileName() const {
10035   const char* const last_sep = FindLastPathSeparator();
10036   std::string dir;
10037   if (last_sep) {
10038     dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
10039   } else {
10040     dir = kCurrentDirectoryString;
10041   }
10042   return FilePath(dir);
10043 }
10044 
10045 // Helper functions for naming files in a directory for xml output.
10046 
10047 // Given directory = "dir", base_name = "test", number = 0,
10048 // extension = "xml", returns "dir/test.xml". If number is greater
10049 // than zero (e.g., 12), returns "dir/test_12.xml".
10050 // On Windows platform, uses \ as the separator rather than /.
MakeFileName(const FilePath & directory,const FilePath & base_name,int number,const char * extension)10051 FilePath FilePath::MakeFileName(const FilePath& directory,
10052                                 const FilePath& base_name,
10053                                 int number,
10054                                 const char* extension) {
10055   std::string file;
10056   if (number == 0) {
10057     file = base_name.string() + "." + extension;
10058   } else {
10059     file = base_name.string() + "_" + StreamableToString(number)
10060         + "." + extension;
10061   }
10062   return ConcatPaths(directory, FilePath(file));
10063 }
10064 
10065 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
10066 // On Windows, uses \ as the separator rather than /.
ConcatPaths(const FilePath & directory,const FilePath & relative_path)10067 FilePath FilePath::ConcatPaths(const FilePath& directory,
10068                                const FilePath& relative_path) {
10069   if (directory.IsEmpty())
10070     return relative_path;
10071   const FilePath dir(directory.RemoveTrailingPathSeparator());
10072   return FilePath(dir.string() + kPathSeparator + relative_path.string());
10073 }
10074 
10075 // Returns true if pathname describes something findable in the file-system,
10076 // either a file, directory, or whatever.
FileOrDirectoryExists() const10077 bool FilePath::FileOrDirectoryExists() const {
10078 #if GTEST_OS_WINDOWS_MOBILE
10079   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
10080   const DWORD attributes = GetFileAttributes(unicode);
10081   delete [] unicode;
10082   return attributes != kInvalidFileAttributes;
10083 #else
10084   posix::StatStruct file_stat{};
10085   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
10086 #endif  // GTEST_OS_WINDOWS_MOBILE
10087 }
10088 
10089 // Returns true if pathname describes a directory in the file-system
10090 // that exists.
DirectoryExists() const10091 bool FilePath::DirectoryExists() const {
10092   bool result = false;
10093 #if GTEST_OS_WINDOWS
10094   // Don't strip off trailing separator if path is a root directory on
10095   // Windows (like "C:\\").
10096   const FilePath& path(IsRootDirectory() ? *this :
10097                                            RemoveTrailingPathSeparator());
10098 #else
10099   const FilePath& path(*this);
10100 #endif
10101 
10102 #if GTEST_OS_WINDOWS_MOBILE
10103   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
10104   const DWORD attributes = GetFileAttributes(unicode);
10105   delete [] unicode;
10106   if ((attributes != kInvalidFileAttributes) &&
10107       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
10108     result = true;
10109   }
10110 #else
10111   posix::StatStruct file_stat{};
10112   result = posix::Stat(path.c_str(), &file_stat) == 0 &&
10113       posix::IsDir(file_stat);
10114 #endif  // GTEST_OS_WINDOWS_MOBILE
10115 
10116   return result;
10117 }
10118 
10119 // Returns true if pathname describes a root directory. (Windows has one
10120 // root directory per disk drive.)
IsRootDirectory() const10121 bool FilePath::IsRootDirectory() const {
10122 #if GTEST_OS_WINDOWS
10123   return pathname_.length() == 3 && IsAbsolutePath();
10124 #else
10125   return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
10126 #endif
10127 }
10128 
10129 // Returns true if pathname describes an absolute path.
IsAbsolutePath() const10130 bool FilePath::IsAbsolutePath() const {
10131   const char* const name = pathname_.c_str();
10132 #if GTEST_OS_WINDOWS
10133   return pathname_.length() >= 3 &&
10134      ((name[0] >= 'a' && name[0] <= 'z') ||
10135       (name[0] >= 'A' && name[0] <= 'Z')) &&
10136      name[1] == ':' &&
10137      IsPathSeparator(name[2]);
10138 #else
10139   return IsPathSeparator(name[0]);
10140 #endif
10141 }
10142 
10143 // Returns a pathname for a file that does not currently exist. The pathname
10144 // will be directory/base_name.extension or
10145 // directory/base_name_<number>.extension if directory/base_name.extension
10146 // already exists. The number will be incremented until a pathname is found
10147 // that does not already exist.
10148 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
10149 // There could be a race condition if two or more processes are calling this
10150 // function at the same time -- they could both pick the same filename.
GenerateUniqueFileName(const FilePath & directory,const FilePath & base_name,const char * extension)10151 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
10152                                           const FilePath& base_name,
10153                                           const char* extension) {
10154   FilePath full_pathname;
10155   int number = 0;
10156   do {
10157     full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
10158   } while (full_pathname.FileOrDirectoryExists());
10159   return full_pathname;
10160 }
10161 
10162 // Returns true if FilePath ends with a path separator, which indicates that
10163 // it is intended to represent a directory. Returns false otherwise.
10164 // This does NOT check that a directory (or file) actually exists.
IsDirectory() const10165 bool FilePath::IsDirectory() const {
10166   return !pathname_.empty() &&
10167          IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
10168 }
10169 
10170 // Create directories so that path exists. Returns true if successful or if
10171 // the directories already exist; returns false if unable to create directories
10172 // for any reason.
CreateDirectoriesRecursively() const10173 bool FilePath::CreateDirectoriesRecursively() const {
10174   if (!this->IsDirectory()) {
10175     return false;
10176   }
10177 
10178   if (pathname_.length() == 0 || this->DirectoryExists()) {
10179     return true;
10180   }
10181 
10182   const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
10183   return parent.CreateDirectoriesRecursively() && this->CreateFolder();
10184 }
10185 
10186 // Create the directory so that path exists. Returns true if successful or
10187 // if the directory already exists; returns false if unable to create the
10188 // directory for any reason, including if the parent directory does not
10189 // exist. Not named "CreateDirectory" because that's a macro on Windows.
CreateFolder() const10190 bool FilePath::CreateFolder() const {
10191 #if GTEST_OS_WINDOWS_MOBILE
10192   FilePath removed_sep(this->RemoveTrailingPathSeparator());
10193   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
10194   int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
10195   delete [] unicode;
10196 #elif GTEST_OS_WINDOWS
10197   int result = _mkdir(pathname_.c_str());
10198 #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
10199   // do nothing
10200   int result = 0;
10201 #else
10202   int result = mkdir(pathname_.c_str(), 0777);
10203 #endif  // GTEST_OS_WINDOWS_MOBILE
10204 
10205   if (result == -1) {
10206     return this->DirectoryExists();  // An error is OK if the directory exists.
10207   }
10208   return true;  // No error.
10209 }
10210 
10211 // If input name has a trailing separator character, remove it and return the
10212 // name, otherwise return the name string unmodified.
10213 // On Windows platform, uses \ as the separator, other platforms use /.
RemoveTrailingPathSeparator() const10214 FilePath FilePath::RemoveTrailingPathSeparator() const {
10215   return IsDirectory()
10216       ? FilePath(pathname_.substr(0, pathname_.length() - 1))
10217       : *this;
10218 }
10219 
10220 // Removes any redundant separators that might be in the pathname.
10221 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
10222 // redundancies that might be in a pathname involving "." or "..".
Normalize()10223 void FilePath::Normalize() {
10224   auto out = pathname_.begin();
10225 
10226   for (const char character : pathname_) {
10227     if (!IsPathSeparator(character)) {
10228       *(out++) = character;
10229     } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
10230       *(out++) = kPathSeparator;
10231     } else {
10232       continue;
10233     }
10234   }
10235 
10236   pathname_.erase(out, pathname_.end());
10237 }
10238 
10239 }  // namespace internal
10240 }  // namespace testing
10241 // Copyright 2007, Google Inc.
10242 // All rights reserved.
10243 //
10244 // Redistribution and use in source and binary forms, with or without
10245 // modification, are permitted provided that the following conditions are
10246 // met:
10247 //
10248 //     * Redistributions of source code must retain the above copyright
10249 // notice, this list of conditions and the following disclaimer.
10250 //     * Redistributions in binary form must reproduce the above
10251 // copyright notice, this list of conditions and the following disclaimer
10252 // in the documentation and/or other materials provided with the
10253 // distribution.
10254 //     * Neither the name of Google Inc. nor the names of its
10255 // contributors may be used to endorse or promote products derived from
10256 // this software without specific prior written permission.
10257 //
10258 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10259 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10260 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10261 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10262 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10263 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10264 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10265 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10266 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10267 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10268 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10269 
10270 // The Google C++ Testing and Mocking Framework (Google Test)
10271 //
10272 // This file implements just enough of the matcher interface to allow
10273 // EXPECT_DEATH and friends to accept a matcher argument.
10274 
10275 
10276 #include <string>
10277 
10278 namespace testing {
10279 
10280 // Constructs a matcher that matches a const std::string& whose value is
10281 // equal to s.
Matcher(const std::string & s)10282 Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
10283 
10284 // Constructs a matcher that matches a const std::string& whose value is
10285 // equal to s.
Matcher(const char * s)10286 Matcher<const std::string&>::Matcher(const char* s) {
10287   *this = Eq(std::string(s));
10288 }
10289 
10290 // Constructs a matcher that matches a std::string whose value is equal to
10291 // s.
Matcher(const std::string & s)10292 Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
10293 
10294 // Constructs a matcher that matches a std::string whose value is equal to
10295 // s.
Matcher(const char * s)10296 Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
10297 
10298 #if GTEST_INTERNAL_HAS_STRING_VIEW
10299 // Constructs a matcher that matches a const StringView& whose value is
10300 // equal to s.
Matcher(const std::string & s)10301 Matcher<const internal::StringView&>::Matcher(const std::string& s) {
10302   *this = Eq(s);
10303 }
10304 
10305 // Constructs a matcher that matches a const StringView& whose value is
10306 // equal to s.
Matcher(const char * s)10307 Matcher<const internal::StringView&>::Matcher(const char* s) {
10308   *this = Eq(std::string(s));
10309 }
10310 
10311 // Constructs a matcher that matches a const StringView& whose value is
10312 // equal to s.
Matcher(internal::StringView s)10313 Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
10314   *this = Eq(std::string(s));
10315 }
10316 
10317 // Constructs a matcher that matches a StringView whose value is equal to
10318 // s.
Matcher(const std::string & s)10319 Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
10320 
10321 // Constructs a matcher that matches a StringView whose value is equal to
10322 // s.
Matcher(const char * s)10323 Matcher<internal::StringView>::Matcher(const char* s) {
10324   *this = Eq(std::string(s));
10325 }
10326 
10327 // Constructs a matcher that matches a StringView whose value is equal to
10328 // s.
Matcher(internal::StringView s)10329 Matcher<internal::StringView>::Matcher(internal::StringView s) {
10330   *this = Eq(std::string(s));
10331 }
10332 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
10333 
10334 }  // namespace testing
10335 // Copyright 2008, Google Inc.
10336 // All rights reserved.
10337 //
10338 // Redistribution and use in source and binary forms, with or without
10339 // modification, are permitted provided that the following conditions are
10340 // met:
10341 //
10342 //     * Redistributions of source code must retain the above copyright
10343 // notice, this list of conditions and the following disclaimer.
10344 //     * Redistributions in binary form must reproduce the above
10345 // copyright notice, this list of conditions and the following disclaimer
10346 // in the documentation and/or other materials provided with the
10347 // distribution.
10348 //     * Neither the name of Google Inc. nor the names of its
10349 // contributors may be used to endorse or promote products derived from
10350 // this software without specific prior written permission.
10351 //
10352 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10353 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10354 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10355 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10356 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10357 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10358 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10359 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10360 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10361 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10362 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10363 
10364 
10365 
10366 #include <limits.h>
10367 #include <stdio.h>
10368 #include <stdlib.h>
10369 #include <string.h>
10370 #include <cstdint>
10371 #include <fstream>
10372 #include <memory>
10373 
10374 #if GTEST_OS_WINDOWS
10375 # include <windows.h>
10376 # include <io.h>
10377 # include <sys/stat.h>
10378 # include <map>  // Used in ThreadLocal.
10379 # ifdef _MSC_VER
10380 #  include <crtdbg.h>
10381 # endif  // _MSC_VER
10382 #else
10383 # include <unistd.h>
10384 #endif  // GTEST_OS_WINDOWS
10385 
10386 #if GTEST_OS_MAC
10387 # include <mach/mach_init.h>
10388 # include <mach/task.h>
10389 # include <mach/vm_map.h>
10390 #endif  // GTEST_OS_MAC
10391 
10392 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
10393     GTEST_OS_NETBSD || GTEST_OS_OPENBSD
10394 # include <sys/sysctl.h>
10395 # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
10396 #  include <sys/user.h>
10397 # endif
10398 #endif
10399 
10400 #if GTEST_OS_QNX
10401 # include <devctl.h>
10402 # include <fcntl.h>
10403 # include <sys/procfs.h>
10404 #endif  // GTEST_OS_QNX
10405 
10406 #if GTEST_OS_AIX
10407 # include <procinfo.h>
10408 # include <sys/types.h>
10409 #endif  // GTEST_OS_AIX
10410 
10411 #if GTEST_OS_FUCHSIA
10412 # include <zircon/process.h>
10413 # include <zircon/syscalls.h>
10414 #endif  // GTEST_OS_FUCHSIA
10415 
10416 
10417 namespace testing {
10418 namespace internal {
10419 
10420 #if defined(_MSC_VER) || defined(__BORLANDC__)
10421 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
10422 const int kStdOutFileno = 1;
10423 const int kStdErrFileno = 2;
10424 #else
10425 const int kStdOutFileno = STDOUT_FILENO;
10426 const int kStdErrFileno = STDERR_FILENO;
10427 #endif  // _MSC_VER
10428 
10429 #if GTEST_OS_LINUX || GTEST_OS_GNU_HURD
10430 
10431 namespace {
10432 template <typename T>
ReadProcFileField(const std::string & filename,int field)10433 T ReadProcFileField(const std::string& filename, int field) {
10434   std::string dummy;
10435   std::ifstream file(filename.c_str());
10436   while (field-- > 0) {
10437     file >> dummy;
10438   }
10439   T output = 0;
10440   file >> output;
10441   return output;
10442 }
10443 }  // namespace
10444 
10445 // Returns the number of active threads, or 0 when there is an error.
GetThreadCount()10446 size_t GetThreadCount() {
10447   const std::string filename =
10448       (Message() << "/proc/" << getpid() << "/stat").GetString();
10449   return ReadProcFileField<size_t>(filename, 19);
10450 }
10451 
10452 #elif GTEST_OS_MAC
10453 
GetThreadCount()10454 size_t GetThreadCount() {
10455   const task_t task = mach_task_self();
10456   mach_msg_type_number_t thread_count;
10457   thread_act_array_t thread_list;
10458   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
10459   if (status == KERN_SUCCESS) {
10460     // task_threads allocates resources in thread_list and we need to free them
10461     // to avoid leaks.
10462     vm_deallocate(task,
10463                   reinterpret_cast<vm_address_t>(thread_list),
10464                   sizeof(thread_t) * thread_count);
10465     return static_cast<size_t>(thread_count);
10466   } else {
10467     return 0;
10468   }
10469 }
10470 
10471 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
10472       GTEST_OS_NETBSD
10473 
10474 #if GTEST_OS_NETBSD
10475 #undef KERN_PROC
10476 #define KERN_PROC KERN_PROC2
10477 #define kinfo_proc kinfo_proc2
10478 #endif
10479 
10480 #if GTEST_OS_DRAGONFLY
10481 #define KP_NLWP(kp) (kp.kp_nthreads)
10482 #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
10483 #define KP_NLWP(kp) (kp.ki_numthreads)
10484 #elif GTEST_OS_NETBSD
10485 #define KP_NLWP(kp) (kp.p_nlwps)
10486 #endif
10487 
10488 // Returns the number of threads running in the process, or 0 to indicate that
10489 // we cannot detect it.
GetThreadCount()10490 size_t GetThreadCount() {
10491   int mib[] = {
10492     CTL_KERN,
10493     KERN_PROC,
10494     KERN_PROC_PID,
10495     getpid(),
10496 #if GTEST_OS_NETBSD
10497     sizeof(struct kinfo_proc),
10498     1,
10499 #endif
10500   };
10501   u_int miblen = sizeof(mib) / sizeof(mib[0]);
10502   struct kinfo_proc info;
10503   size_t size = sizeof(info);
10504   if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
10505     return 0;
10506   }
10507   return static_cast<size_t>(KP_NLWP(info));
10508 }
10509 #elif GTEST_OS_OPENBSD
10510 
10511 // Returns the number of threads running in the process, or 0 to indicate that
10512 // we cannot detect it.
GetThreadCount()10513 size_t GetThreadCount() {
10514   int mib[] = {
10515     CTL_KERN,
10516     KERN_PROC,
10517     KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
10518     getpid(),
10519     sizeof(struct kinfo_proc),
10520     0,
10521   };
10522   u_int miblen = sizeof(mib) / sizeof(mib[0]);
10523 
10524   // get number of structs
10525   size_t size;
10526   if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
10527     return 0;
10528   }
10529 
10530   mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
10531 
10532   // populate array of structs
10533   struct kinfo_proc info[mib[5]];
10534   if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
10535     return 0;
10536   }
10537 
10538   // exclude empty members
10539   size_t nthreads = 0;
10540   for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
10541     if (info[i].p_tid != -1)
10542       nthreads++;
10543   }
10544   return nthreads;
10545 }
10546 
10547 #elif GTEST_OS_QNX
10548 
10549 // Returns the number of threads running in the process, or 0 to indicate that
10550 // we cannot detect it.
GetThreadCount()10551 size_t GetThreadCount() {
10552   const int fd = open("/proc/self/as", O_RDONLY);
10553   if (fd < 0) {
10554     return 0;
10555   }
10556   procfs_info process_info;
10557   const int status =
10558       devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
10559   close(fd);
10560   if (status == EOK) {
10561     return static_cast<size_t>(process_info.num_threads);
10562   } else {
10563     return 0;
10564   }
10565 }
10566 
10567 #elif GTEST_OS_AIX
10568 
GetThreadCount()10569 size_t GetThreadCount() {
10570   struct procentry64 entry;
10571   pid_t pid = getpid();
10572   int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
10573   if (status == 1) {
10574     return entry.pi_thcount;
10575   } else {
10576     return 0;
10577   }
10578 }
10579 
10580 #elif GTEST_OS_FUCHSIA
10581 
GetThreadCount()10582 size_t GetThreadCount() {
10583   int dummy_buffer;
10584   size_t avail;
10585   zx_status_t status = zx_object_get_info(
10586       zx_process_self(),
10587       ZX_INFO_PROCESS_THREADS,
10588       &dummy_buffer,
10589       0,
10590       nullptr,
10591       &avail);
10592   if (status == ZX_OK) {
10593     return avail;
10594   } else {
10595     return 0;
10596   }
10597 }
10598 
10599 #else
10600 
GetThreadCount()10601 size_t GetThreadCount() {
10602   // There's no portable way to detect the number of threads, so we just
10603   // return 0 to indicate that we cannot detect it.
10604   return 0;
10605 }
10606 
10607 #endif  // GTEST_OS_LINUX
10608 
10609 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
10610 
SleepMilliseconds(int n)10611 void SleepMilliseconds(int n) {
10612   ::Sleep(static_cast<DWORD>(n));
10613 }
10614 
AutoHandle()10615 AutoHandle::AutoHandle()
10616     : handle_(INVALID_HANDLE_VALUE) {}
10617 
AutoHandle(Handle handle)10618 AutoHandle::AutoHandle(Handle handle)
10619     : handle_(handle) {}
10620 
~AutoHandle()10621 AutoHandle::~AutoHandle() {
10622   Reset();
10623 }
10624 
Get() const10625 AutoHandle::Handle AutoHandle::Get() const {
10626   return handle_;
10627 }
10628 
Reset()10629 void AutoHandle::Reset() {
10630   Reset(INVALID_HANDLE_VALUE);
10631 }
10632 
Reset(HANDLE handle)10633 void AutoHandle::Reset(HANDLE handle) {
10634   // Resetting with the same handle we already own is invalid.
10635   if (handle_ != handle) {
10636     if (IsCloseable()) {
10637       ::CloseHandle(handle_);
10638     }
10639     handle_ = handle;
10640   } else {
10641     GTEST_CHECK_(!IsCloseable())
10642         << "Resetting a valid handle to itself is likely a programmer error "
10643             "and thus not allowed.";
10644   }
10645 }
10646 
IsCloseable() const10647 bool AutoHandle::IsCloseable() const {
10648   // Different Windows APIs may use either of these values to represent an
10649   // invalid handle.
10650   return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
10651 }
10652 
Notification()10653 Notification::Notification()
10654     : event_(::CreateEvent(nullptr,     // Default security attributes.
10655                            TRUE,        // Do not reset automatically.
10656                            FALSE,       // Initially unset.
10657                            nullptr)) {  // Anonymous event.
10658   GTEST_CHECK_(event_.Get() != nullptr);
10659 }
10660 
Notify()10661 void Notification::Notify() {
10662   GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
10663 }
10664 
WaitForNotification()10665 void Notification::WaitForNotification() {
10666   GTEST_CHECK_(
10667       ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
10668 }
10669 
Mutex()10670 Mutex::Mutex()
10671     : owner_thread_id_(0),
10672       type_(kDynamic),
10673       critical_section_init_phase_(0),
10674       critical_section_(new CRITICAL_SECTION) {
10675   ::InitializeCriticalSection(critical_section_);
10676 }
10677 
~Mutex()10678 Mutex::~Mutex() {
10679   // Static mutexes are leaked intentionally. It is not thread-safe to try
10680   // to clean them up.
10681   if (type_ == kDynamic) {
10682     ::DeleteCriticalSection(critical_section_);
10683     delete critical_section_;
10684     critical_section_ = nullptr;
10685   }
10686 }
10687 
Lock()10688 void Mutex::Lock() {
10689   ThreadSafeLazyInit();
10690   ::EnterCriticalSection(critical_section_);
10691   owner_thread_id_ = ::GetCurrentThreadId();
10692 }
10693 
Unlock()10694 void Mutex::Unlock() {
10695   ThreadSafeLazyInit();
10696   // We don't protect writing to owner_thread_id_ here, as it's the
10697   // caller's responsibility to ensure that the current thread holds the
10698   // mutex when this is called.
10699   owner_thread_id_ = 0;
10700   ::LeaveCriticalSection(critical_section_);
10701 }
10702 
10703 // Does nothing if the current thread holds the mutex. Otherwise, crashes
10704 // with high probability.
AssertHeld()10705 void Mutex::AssertHeld() {
10706   ThreadSafeLazyInit();
10707   GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
10708       << "The current thread is not holding the mutex @" << this;
10709 }
10710 
10711 namespace {
10712 
10713 #ifdef _MSC_VER
10714 // Use the RAII idiom to flag mem allocs that are intentionally never
10715 // deallocated. The motivation is to silence the false positive mem leaks
10716 // that are reported by the debug version of MS's CRT which can only detect
10717 // if an alloc is missing a matching deallocation.
10718 // Example:
10719 //    MemoryIsNotDeallocated memory_is_not_deallocated;
10720 //    critical_section_ = new CRITICAL_SECTION;
10721 //
10722 class MemoryIsNotDeallocated
10723 {
10724  public:
MemoryIsNotDeallocated()10725   MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
10726     old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10727     // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
10728     // doesn't report mem leak if there's no matching deallocation.
10729     _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
10730   }
10731 
~MemoryIsNotDeallocated()10732   ~MemoryIsNotDeallocated() {
10733     // Restore the original _CRTDBG_ALLOC_MEM_DF flag
10734     _CrtSetDbgFlag(old_crtdbg_flag_);
10735   }
10736 
10737  private:
10738   int old_crtdbg_flag_;
10739 
10740   GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
10741 };
10742 #endif  // _MSC_VER
10743 
10744 }  // namespace
10745 
10746 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
ThreadSafeLazyInit()10747 void Mutex::ThreadSafeLazyInit() {
10748   // Dynamic mutexes are initialized in the constructor.
10749   if (type_ == kStatic) {
10750     switch (
10751         ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
10752       case 0:
10753         // If critical_section_init_phase_ was 0 before the exchange, we
10754         // are the first to test it and need to perform the initialization.
10755         owner_thread_id_ = 0;
10756         {
10757           // Use RAII to flag that following mem alloc is never deallocated.
10758 #ifdef _MSC_VER
10759           MemoryIsNotDeallocated memory_is_not_deallocated;
10760 #endif  // _MSC_VER
10761           critical_section_ = new CRITICAL_SECTION;
10762         }
10763         ::InitializeCriticalSection(critical_section_);
10764         // Updates the critical_section_init_phase_ to 2 to signal
10765         // initialization complete.
10766         GTEST_CHECK_(::InterlockedCompareExchange(
10767                           &critical_section_init_phase_, 2L, 1L) ==
10768                       1L);
10769         break;
10770       case 1:
10771         // Somebody else is already initializing the mutex; spin until they
10772         // are done.
10773         while (::InterlockedCompareExchange(&critical_section_init_phase_,
10774                                             2L,
10775                                             2L) != 2L) {
10776           // Possibly yields the rest of the thread's time slice to other
10777           // threads.
10778           ::Sleep(0);
10779         }
10780         break;
10781 
10782       case 2:
10783         break;  // The mutex is already initialized and ready for use.
10784 
10785       default:
10786         GTEST_CHECK_(false)
10787             << "Unexpected value of critical_section_init_phase_ "
10788             << "while initializing a static mutex.";
10789     }
10790   }
10791 }
10792 
10793 namespace {
10794 
10795 class ThreadWithParamSupport : public ThreadWithParamBase {
10796  public:
CreateThread(Runnable * runnable,Notification * thread_can_start)10797   static HANDLE CreateThread(Runnable* runnable,
10798                              Notification* thread_can_start) {
10799     ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
10800     DWORD thread_id;
10801     HANDLE thread_handle = ::CreateThread(
10802         nullptr,  // Default security.
10803         0,        // Default stack size.
10804         &ThreadWithParamSupport::ThreadMain,
10805         param,        // Parameter to ThreadMainStatic
10806         0x0,          // Default creation flags.
10807         &thread_id);  // Need a valid pointer for the call to work under Win98.
10808     GTEST_CHECK_(thread_handle != nullptr)
10809         << "CreateThread failed with error " << ::GetLastError() << ".";
10810     if (thread_handle == nullptr) {
10811       delete param;
10812     }
10813     return thread_handle;
10814   }
10815 
10816  private:
10817   struct ThreadMainParam {
ThreadMainParamtesting::internal::__anon123a64d50e11::ThreadWithParamSupport::ThreadMainParam10818     ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
10819         : runnable_(runnable),
10820           thread_can_start_(thread_can_start) {
10821     }
10822     std::unique_ptr<Runnable> runnable_;
10823     // Does not own.
10824     Notification* thread_can_start_;
10825   };
10826 
ThreadMain(void * ptr)10827   static DWORD WINAPI ThreadMain(void* ptr) {
10828     // Transfers ownership.
10829     std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
10830     if (param->thread_can_start_ != nullptr)
10831       param->thread_can_start_->WaitForNotification();
10832     param->runnable_->Run();
10833     return 0;
10834   }
10835 
10836   // Prohibit instantiation.
10837   ThreadWithParamSupport();
10838 
10839   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
10840 };
10841 
10842 }  // namespace
10843 
ThreadWithParamBase(Runnable * runnable,Notification * thread_can_start)10844 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
10845                                          Notification* thread_can_start)
10846       : thread_(ThreadWithParamSupport::CreateThread(runnable,
10847                                                      thread_can_start)) {
10848 }
10849 
~ThreadWithParamBase()10850 ThreadWithParamBase::~ThreadWithParamBase() {
10851   Join();
10852 }
10853 
Join()10854 void ThreadWithParamBase::Join() {
10855   GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
10856       << "Failed to join the thread with error " << ::GetLastError() << ".";
10857 }
10858 
10859 // Maps a thread to a set of ThreadIdToThreadLocals that have values
10860 // instantiated on that thread and notifies them when the thread exits.  A
10861 // ThreadLocal instance is expected to persist until all threads it has
10862 // values on have terminated.
10863 class ThreadLocalRegistryImpl {
10864  public:
10865   // Registers thread_local_instance as having value on the current thread.
10866   // Returns a value that can be used to identify the thread from other threads.
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)10867   static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
10868       const ThreadLocalBase* thread_local_instance) {
10869 #ifdef _MSC_VER
10870     MemoryIsNotDeallocated memory_is_not_deallocated;
10871 #endif  // _MSC_VER
10872     DWORD current_thread = ::GetCurrentThreadId();
10873     MutexLock lock(&mutex_);
10874     ThreadIdToThreadLocals* const thread_to_thread_locals =
10875         GetThreadLocalsMapLocked();
10876     ThreadIdToThreadLocals::iterator thread_local_pos =
10877         thread_to_thread_locals->find(current_thread);
10878     if (thread_local_pos == thread_to_thread_locals->end()) {
10879       thread_local_pos = thread_to_thread_locals->insert(
10880           std::make_pair(current_thread, ThreadLocalValues())).first;
10881       StartWatcherThreadFor(current_thread);
10882     }
10883     ThreadLocalValues& thread_local_values = thread_local_pos->second;
10884     ThreadLocalValues::iterator value_pos =
10885         thread_local_values.find(thread_local_instance);
10886     if (value_pos == thread_local_values.end()) {
10887       value_pos =
10888           thread_local_values
10889               .insert(std::make_pair(
10890                   thread_local_instance,
10891                   std::shared_ptr<ThreadLocalValueHolderBase>(
10892                       thread_local_instance->NewValueForCurrentThread())))
10893               .first;
10894     }
10895     return value_pos->second.get();
10896   }
10897 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)10898   static void OnThreadLocalDestroyed(
10899       const ThreadLocalBase* thread_local_instance) {
10900     std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10901     // Clean up the ThreadLocalValues data structure while holding the lock, but
10902     // defer the destruction of the ThreadLocalValueHolderBases.
10903     {
10904       MutexLock lock(&mutex_);
10905       ThreadIdToThreadLocals* const thread_to_thread_locals =
10906           GetThreadLocalsMapLocked();
10907       for (ThreadIdToThreadLocals::iterator it =
10908           thread_to_thread_locals->begin();
10909           it != thread_to_thread_locals->end();
10910           ++it) {
10911         ThreadLocalValues& thread_local_values = it->second;
10912         ThreadLocalValues::iterator value_pos =
10913             thread_local_values.find(thread_local_instance);
10914         if (value_pos != thread_local_values.end()) {
10915           value_holders.push_back(value_pos->second);
10916           thread_local_values.erase(value_pos);
10917           // This 'if' can only be successful at most once, so theoretically we
10918           // could break out of the loop here, but we don't bother doing so.
10919         }
10920       }
10921     }
10922     // Outside the lock, let the destructor for 'value_holders' deallocate the
10923     // ThreadLocalValueHolderBases.
10924   }
10925 
OnThreadExit(DWORD thread_id)10926   static void OnThreadExit(DWORD thread_id) {
10927     GTEST_CHECK_(thread_id != 0) << ::GetLastError();
10928     std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10929     // Clean up the ThreadIdToThreadLocals data structure while holding the
10930     // lock, but defer the destruction of the ThreadLocalValueHolderBases.
10931     {
10932       MutexLock lock(&mutex_);
10933       ThreadIdToThreadLocals* const thread_to_thread_locals =
10934           GetThreadLocalsMapLocked();
10935       ThreadIdToThreadLocals::iterator thread_local_pos =
10936           thread_to_thread_locals->find(thread_id);
10937       if (thread_local_pos != thread_to_thread_locals->end()) {
10938         ThreadLocalValues& thread_local_values = thread_local_pos->second;
10939         for (ThreadLocalValues::iterator value_pos =
10940             thread_local_values.begin();
10941             value_pos != thread_local_values.end();
10942             ++value_pos) {
10943           value_holders.push_back(value_pos->second);
10944         }
10945         thread_to_thread_locals->erase(thread_local_pos);
10946       }
10947     }
10948     // Outside the lock, let the destructor for 'value_holders' deallocate the
10949     // ThreadLocalValueHolderBases.
10950   }
10951 
10952  private:
10953   // In a particular thread, maps a ThreadLocal object to its value.
10954   typedef std::map<const ThreadLocalBase*,
10955                    std::shared_ptr<ThreadLocalValueHolderBase> >
10956       ThreadLocalValues;
10957   // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
10958   // thread's ID.
10959   typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
10960 
10961   // Holds the thread id and thread handle that we pass from
10962   // StartWatcherThreadFor to WatcherThreadFunc.
10963   typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
10964 
StartWatcherThreadFor(DWORD thread_id)10965   static void StartWatcherThreadFor(DWORD thread_id) {
10966     // The returned handle will be kept in thread_map and closed by
10967     // watcher_thread in WatcherThreadFunc.
10968     HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
10969                                  FALSE,
10970                                  thread_id);
10971     GTEST_CHECK_(thread != nullptr);
10972     // We need to pass a valid thread ID pointer into CreateThread for it
10973     // to work correctly under Win98.
10974     DWORD watcher_thread_id;
10975     HANDLE watcher_thread = ::CreateThread(
10976         nullptr,  // Default security.
10977         0,        // Default stack size
10978         &ThreadLocalRegistryImpl::WatcherThreadFunc,
10979         reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
10980         CREATE_SUSPENDED, &watcher_thread_id);
10981     GTEST_CHECK_(watcher_thread != nullptr);
10982     // Give the watcher thread the same priority as ours to avoid being
10983     // blocked by it.
10984     ::SetThreadPriority(watcher_thread,
10985                         ::GetThreadPriority(::GetCurrentThread()));
10986     ::ResumeThread(watcher_thread);
10987     ::CloseHandle(watcher_thread);
10988   }
10989 
10990   // Monitors exit from a given thread and notifies those
10991   // ThreadIdToThreadLocals about thread termination.
WatcherThreadFunc(LPVOID param)10992   static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
10993     const ThreadIdAndHandle* tah =
10994         reinterpret_cast<const ThreadIdAndHandle*>(param);
10995     GTEST_CHECK_(
10996         ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
10997     OnThreadExit(tah->first);
10998     ::CloseHandle(tah->second);
10999     delete tah;
11000     return 0;
11001   }
11002 
11003   // Returns map of thread local instances.
GetThreadLocalsMapLocked()11004   static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
11005     mutex_.AssertHeld();
11006 #ifdef _MSC_VER
11007     MemoryIsNotDeallocated memory_is_not_deallocated;
11008 #endif  // _MSC_VER
11009     static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
11010     return map;
11011   }
11012 
11013   // Protects access to GetThreadLocalsMapLocked() and its return value.
11014   static Mutex mutex_;
11015   // Protects access to GetThreadMapLocked() and its return value.
11016   static Mutex thread_map_mutex_;
11017 };
11018 
11019 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);  // NOLINT
11020 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);  // NOLINT
11021 
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)11022 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
11023       const ThreadLocalBase* thread_local_instance) {
11024   return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
11025       thread_local_instance);
11026 }
11027 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)11028 void ThreadLocalRegistry::OnThreadLocalDestroyed(
11029       const ThreadLocalBase* thread_local_instance) {
11030   ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
11031 }
11032 
11033 #endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
11034 
11035 #if GTEST_USES_POSIX_RE
11036 
11037 // Implements RE.  Currently only needed for death tests.
11038 
~RE()11039 RE::~RE() {
11040   if (is_valid_) {
11041     // regfree'ing an invalid regex might crash because the content
11042     // of the regex is undefined. Since the regex's are essentially
11043     // the same, one cannot be valid (or invalid) without the other
11044     // being so too.
11045     regfree(&partial_regex_);
11046     regfree(&full_regex_);
11047   }
11048   free(const_cast<char*>(pattern_));
11049 }
11050 
11051 // Returns true if and only if regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)11052 bool RE::FullMatch(const char* str, const RE& re) {
11053   if (!re.is_valid_) return false;
11054 
11055   regmatch_t match;
11056   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
11057 }
11058 
11059 // Returns true if and only if regular expression re matches a substring of
11060 // str (including str itself).
PartialMatch(const char * str,const RE & re)11061 bool RE::PartialMatch(const char* str, const RE& re) {
11062   if (!re.is_valid_) return false;
11063 
11064   regmatch_t match;
11065   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
11066 }
11067 
11068 // Initializes an RE from its string representation.
Init(const char * regex)11069 void RE::Init(const char* regex) {
11070   pattern_ = posix::StrDup(regex);
11071 
11072   // Reserves enough bytes to hold the regular expression used for a
11073   // full match.
11074   const size_t full_regex_len = strlen(regex) + 10;
11075   char* const full_pattern = new char[full_regex_len];
11076 
11077   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
11078   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
11079   // We want to call regcomp(&partial_regex_, ...) even if the
11080   // previous expression returns false.  Otherwise partial_regex_ may
11081   // not be properly initialized can may cause trouble when it's
11082   // freed.
11083   //
11084   // Some implementation of POSIX regex (e.g. on at least some
11085   // versions of Cygwin) doesn't accept the empty string as a valid
11086   // regex.  We change it to an equivalent form "()" to be safe.
11087   if (is_valid_) {
11088     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
11089     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
11090   }
11091   EXPECT_TRUE(is_valid_)
11092       << "Regular expression \"" << regex
11093       << "\" is not a valid POSIX Extended regular expression.";
11094 
11095   delete[] full_pattern;
11096 }
11097 
11098 #elif GTEST_USES_SIMPLE_RE
11099 
11100 // Returns true if and only if ch appears anywhere in str (excluding the
11101 // terminating '\0' character).
IsInSet(char ch,const char * str)11102 bool IsInSet(char ch, const char* str) {
11103   return ch != '\0' && strchr(str, ch) != nullptr;
11104 }
11105 
11106 // Returns true if and only if ch belongs to the given classification.
11107 // Unlike similar functions in <ctype.h>, these aren't affected by the
11108 // current locale.
IsAsciiDigit(char ch)11109 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)11110 bool IsAsciiPunct(char ch) {
11111   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
11112 }
IsRepeat(char ch)11113 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)11114 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)11115 bool IsAsciiWordChar(char ch) {
11116   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
11117       ('0' <= ch && ch <= '9') || ch == '_';
11118 }
11119 
11120 // Returns true if and only if "\\c" is a supported escape sequence.
IsValidEscape(char c)11121 bool IsValidEscape(char c) {
11122   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
11123 }
11124 
11125 // Returns true if and only if the given atom (specified by escaped and
11126 // pattern) matches ch.  The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)11127 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
11128   if (escaped) {  // "\\p" where p is pattern_char.
11129     switch (pattern_char) {
11130       case 'd': return IsAsciiDigit(ch);
11131       case 'D': return !IsAsciiDigit(ch);
11132       case 'f': return ch == '\f';
11133       case 'n': return ch == '\n';
11134       case 'r': return ch == '\r';
11135       case 's': return IsAsciiWhiteSpace(ch);
11136       case 'S': return !IsAsciiWhiteSpace(ch);
11137       case 't': return ch == '\t';
11138       case 'v': return ch == '\v';
11139       case 'w': return IsAsciiWordChar(ch);
11140       case 'W': return !IsAsciiWordChar(ch);
11141     }
11142     return IsAsciiPunct(pattern_char) && pattern_char == ch;
11143   }
11144 
11145   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
11146 }
11147 
11148 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)11149 static std::string FormatRegexSyntaxError(const char* regex, int index) {
11150   return (Message() << "Syntax error at index " << index
11151           << " in simple regular expression \"" << regex << "\": ").GetString();
11152 }
11153 
11154 // Generates non-fatal failures and returns false if regex is invalid;
11155 // otherwise returns true.
ValidateRegex(const char * regex)11156 bool ValidateRegex(const char* regex) {
11157   if (regex == nullptr) {
11158     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
11159     return false;
11160   }
11161 
11162   bool is_valid = true;
11163 
11164   // True if and only if ?, *, or + can follow the previous atom.
11165   bool prev_repeatable = false;
11166   for (int i = 0; regex[i]; i++) {
11167     if (regex[i] == '\\') {  // An escape sequence
11168       i++;
11169       if (regex[i] == '\0') {
11170         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
11171                       << "'\\' cannot appear at the end.";
11172         return false;
11173       }
11174 
11175       if (!IsValidEscape(regex[i])) {
11176         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
11177                       << "invalid escape sequence \"\\" << regex[i] << "\".";
11178         is_valid = false;
11179       }
11180       prev_repeatable = true;
11181     } else {  // Not an escape sequence.
11182       const char ch = regex[i];
11183 
11184       if (ch == '^' && i > 0) {
11185         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11186                       << "'^' can only appear at the beginning.";
11187         is_valid = false;
11188       } else if (ch == '$' && regex[i + 1] != '\0') {
11189         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11190                       << "'$' can only appear at the end.";
11191         is_valid = false;
11192       } else if (IsInSet(ch, "()[]{}|")) {
11193         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11194                       << "'" << ch << "' is unsupported.";
11195         is_valid = false;
11196       } else if (IsRepeat(ch) && !prev_repeatable) {
11197         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
11198                       << "'" << ch << "' can only follow a repeatable token.";
11199         is_valid = false;
11200       }
11201 
11202       prev_repeatable = !IsInSet(ch, "^$?*+");
11203     }
11204   }
11205 
11206   return is_valid;
11207 }
11208 
11209 // Matches a repeated regex atom followed by a valid simple regular
11210 // expression.  The regex atom is defined as c if escaped is false,
11211 // or \c otherwise.  repeat is the repetition meta character (?, *,
11212 // or +).  The behavior is undefined if str contains too many
11213 // characters to be indexable by size_t, in which case the test will
11214 // probably time out anyway.  We are fine with this limitation as
11215 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)11216 bool MatchRepetitionAndRegexAtHead(
11217     bool escaped, char c, char repeat, const char* regex,
11218     const char* str) {
11219   const size_t min_count = (repeat == '+') ? 1 : 0;
11220   const size_t max_count = (repeat == '?') ? 1 :
11221       static_cast<size_t>(-1) - 1;
11222   // We cannot call numeric_limits::max() as it conflicts with the
11223   // max() macro on Windows.
11224 
11225   for (size_t i = 0; i <= max_count; ++i) {
11226     // We know that the atom matches each of the first i characters in str.
11227     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
11228       // We have enough matches at the head, and the tail matches too.
11229       // Since we only care about *whether* the pattern matches str
11230       // (as opposed to *how* it matches), there is no need to find a
11231       // greedy match.
11232       return true;
11233     }
11234     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
11235       return false;
11236   }
11237   return false;
11238 }
11239 
11240 // Returns true if and only if regex matches a prefix of str. regex must
11241 // be a valid simple regular expression and not start with "^", or the
11242 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)11243 bool MatchRegexAtHead(const char* regex, const char* str) {
11244   if (*regex == '\0')  // An empty regex matches a prefix of anything.
11245     return true;
11246 
11247   // "$" only matches the end of a string.  Note that regex being
11248   // valid guarantees that there's nothing after "$" in it.
11249   if (*regex == '$')
11250     return *str == '\0';
11251 
11252   // Is the first thing in regex an escape sequence?
11253   const bool escaped = *regex == '\\';
11254   if (escaped)
11255     ++regex;
11256   if (IsRepeat(regex[1])) {
11257     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
11258     // here's an indirect recursion.  It terminates as the regex gets
11259     // shorter in each recursion.
11260     return MatchRepetitionAndRegexAtHead(
11261         escaped, regex[0], regex[1], regex + 2, str);
11262   } else {
11263     // regex isn't empty, isn't "$", and doesn't start with a
11264     // repetition.  We match the first atom of regex with the first
11265     // character of str and recurse.
11266     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
11267         MatchRegexAtHead(regex + 1, str + 1);
11268   }
11269 }
11270 
11271 // Returns true if and only if regex matches any substring of str.  regex must
11272 // be a valid simple regular expression, or the result is undefined.
11273 //
11274 // The algorithm is recursive, but the recursion depth doesn't exceed
11275 // the regex length, so we won't need to worry about running out of
11276 // stack space normally.  In rare cases the time complexity can be
11277 // exponential with respect to the regex length + the string length,
11278 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)11279 bool MatchRegexAnywhere(const char* regex, const char* str) {
11280   if (regex == nullptr || str == nullptr) return false;
11281 
11282   if (*regex == '^')
11283     return MatchRegexAtHead(regex + 1, str);
11284 
11285   // A successful match can be anywhere in str.
11286   do {
11287     if (MatchRegexAtHead(regex, str))
11288       return true;
11289   } while (*str++ != '\0');
11290   return false;
11291 }
11292 
11293 // Implements the RE class.
11294 
~RE()11295 RE::~RE() {
11296   free(const_cast<char*>(pattern_));
11297   free(const_cast<char*>(full_pattern_));
11298 }
11299 
11300 // Returns true if and only if regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)11301 bool RE::FullMatch(const char* str, const RE& re) {
11302   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
11303 }
11304 
11305 // Returns true if and only if regular expression re matches a substring of
11306 // str (including str itself).
PartialMatch(const char * str,const RE & re)11307 bool RE::PartialMatch(const char* str, const RE& re) {
11308   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
11309 }
11310 
11311 // Initializes an RE from its string representation.
Init(const char * regex)11312 void RE::Init(const char* regex) {
11313   pattern_ = full_pattern_ = nullptr;
11314   if (regex != nullptr) {
11315     pattern_ = posix::StrDup(regex);
11316   }
11317 
11318   is_valid_ = ValidateRegex(regex);
11319   if (!is_valid_) {
11320     // No need to calculate the full pattern when the regex is invalid.
11321     return;
11322   }
11323 
11324   const size_t len = strlen(regex);
11325   // Reserves enough bytes to hold the regular expression used for a
11326   // full match: we need space to prepend a '^', append a '$', and
11327   // terminate the string with '\0'.
11328   char* buffer = static_cast<char*>(malloc(len + 3));
11329   full_pattern_ = buffer;
11330 
11331   if (*regex != '^')
11332     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
11333 
11334   // We don't use snprintf or strncpy, as they trigger a warning when
11335   // compiled with VC++ 8.0.
11336   memcpy(buffer, regex, len);
11337   buffer += len;
11338 
11339   if (len == 0 || regex[len - 1] != '$')
11340     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
11341 
11342   *buffer = '\0';
11343 }
11344 
11345 #endif  // GTEST_USES_POSIX_RE
11346 
11347 const char kUnknownFile[] = "unknown file";
11348 
11349 // Formats a source file path and a line number as they would appear
11350 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)11351 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
11352   const std::string file_name(file == nullptr ? kUnknownFile : file);
11353 
11354   if (line < 0) {
11355     return file_name + ":";
11356   }
11357 #ifdef _MSC_VER
11358   return file_name + "(" + StreamableToString(line) + "):";
11359 #else
11360   return file_name + ":" + StreamableToString(line) + ":";
11361 #endif  // _MSC_VER
11362 }
11363 
11364 // Formats a file location for compiler-independent XML output.
11365 // Although this function is not platform dependent, we put it next to
11366 // FormatFileLocation in order to contrast the two functions.
11367 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
11368 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)11369 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
11370     const char* file, int line) {
11371   const std::string file_name(file == nullptr ? kUnknownFile : file);
11372 
11373   if (line < 0)
11374     return file_name;
11375   else
11376     return file_name + ":" + StreamableToString(line);
11377 }
11378 
GTestLog(GTestLogSeverity severity,const char * file,int line)11379 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
11380     : severity_(severity) {
11381   const char* const marker =
11382       severity == GTEST_INFO ?    "[  INFO ]" :
11383       severity == GTEST_WARNING ? "[WARNING]" :
11384       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
11385   GetStream() << ::std::endl << marker << " "
11386               << FormatFileLocation(file, line).c_str() << ": ";
11387 }
11388 
11389 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()11390 GTestLog::~GTestLog() {
11391   GetStream() << ::std::endl;
11392   if (severity_ == GTEST_FATAL) {
11393     fflush(stderr);
11394     posix::Abort();
11395   }
11396 }
11397 
11398 // Disable Microsoft deprecation warnings for POSIX functions called from
11399 // this class (creat, dup, dup2, and close)
11400 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
11401 
11402 #if GTEST_HAS_STREAM_REDIRECTION
11403 
11404 // Object that captures an output stream (stdout/stderr).
11405 class CapturedStream {
11406  public:
11407   // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)11408   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
11409 # if GTEST_OS_WINDOWS
11410     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
11411     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
11412 
11413     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
11414     const UINT success = ::GetTempFileNameA(temp_dir_path,
11415                                             "gtest_redir",
11416                                             0,  // Generate unique file name.
11417                                             temp_file_path);
11418     GTEST_CHECK_(success != 0)
11419         << "Unable to create a temporary file in " << temp_dir_path;
11420     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
11421     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
11422                                     << temp_file_path;
11423     filename_ = temp_file_path;
11424 # else
11425     // There's no guarantee that a test has write access to the current
11426     // directory, so we create the temporary file in a temporary directory.
11427     std::string name_template;
11428 
11429 #  if GTEST_OS_LINUX_ANDROID
11430     // Note: Android applications are expected to call the framework's
11431     // Context.getExternalStorageDirectory() method through JNI to get
11432     // the location of the world-writable SD Card directory. However,
11433     // this requires a Context handle, which cannot be retrieved
11434     // globally from native code. Doing so also precludes running the
11435     // code as part of a regular standalone executable, which doesn't
11436     // run in a Dalvik process (e.g. when running it through 'adb shell').
11437     //
11438     // The location /data/local/tmp is directly accessible from native code.
11439     // '/sdcard' and other variants cannot be relied on, as they are not
11440     // guaranteed to be mounted, or may have a delay in mounting.
11441     name_template = "/data/local/tmp/";
11442 #  elif GTEST_OS_IOS
11443     char user_temp_dir[PATH_MAX + 1];
11444 
11445     // Documented alternative to NSTemporaryDirectory() (for obtaining creating
11446     // a temporary directory) at
11447     // https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10
11448     //
11449     // _CS_DARWIN_USER_TEMP_DIR (as well as _CS_DARWIN_USER_CACHE_DIR) is not
11450     // documented in the confstr() man page at
11451     // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/confstr.3.html#//apple_ref/doc/man/3/confstr
11452     // but are still available, according to the WebKit patches at
11453     // https://trac.webkit.org/changeset/262004/webkit
11454     // https://trac.webkit.org/changeset/263705/webkit
11455     //
11456     // The confstr() implementation falls back to getenv("TMPDIR"). See
11457     // https://opensource.apple.com/source/Libc/Libc-1439.100.3/gen/confstr.c.auto.html
11458     ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir));
11459 
11460     name_template = user_temp_dir;
11461     if (name_template.back() != GTEST_PATH_SEP_[0])
11462       name_template.push_back(GTEST_PATH_SEP_[0]);
11463 #  else
11464     name_template = "/tmp/";
11465 #  endif
11466     name_template.append("gtest_captured_stream.XXXXXX");
11467 
11468     // mkstemp() modifies the string bytes in place, and does not go beyond the
11469     // string's length. This results in well-defined behavior in C++17.
11470     //
11471     // The const_cast is needed below C++17. The constraints on std::string
11472     // implementations in C++11 and above make assumption behind the const_cast
11473     // fairly safe.
11474     const int captured_fd = ::mkstemp(const_cast<char*>(name_template.data()));
11475     if (captured_fd == -1) {
11476       GTEST_LOG_(WARNING)
11477           << "Failed to create tmp file " << name_template
11478           << " for test; does the test have access to the /tmp directory?";
11479     }
11480     filename_ = std::move(name_template);
11481 # endif  // GTEST_OS_WINDOWS
11482     fflush(nullptr);
11483     dup2(captured_fd, fd_);
11484     close(captured_fd);
11485   }
11486 
~CapturedStream()11487   ~CapturedStream() {
11488     remove(filename_.c_str());
11489   }
11490 
GetCapturedString()11491   std::string GetCapturedString() {
11492     if (uncaptured_fd_ != -1) {
11493       // Restores the original stream.
11494       fflush(nullptr);
11495       dup2(uncaptured_fd_, fd_);
11496       close(uncaptured_fd_);
11497       uncaptured_fd_ = -1;
11498     }
11499 
11500     FILE* const file = posix::FOpen(filename_.c_str(), "r");
11501     if (file == nullptr) {
11502       GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
11503                         << " for capturing stream.";
11504     }
11505     const std::string content = ReadEntireFile(file);
11506     posix::FClose(file);
11507     return content;
11508   }
11509 
11510  private:
11511   const int fd_;  // A stream to capture.
11512   int uncaptured_fd_;
11513   // Name of the temporary file holding the stderr output.
11514   ::std::string filename_;
11515 
11516   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
11517 };
11518 
11519 GTEST_DISABLE_MSC_DEPRECATED_POP_()
11520 
11521 static CapturedStream* g_captured_stderr = nullptr;
11522 static CapturedStream* g_captured_stdout = nullptr;
11523 
11524 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)11525 static void CaptureStream(int fd, const char* stream_name,
11526                           CapturedStream** stream) {
11527   if (*stream != nullptr) {
11528     GTEST_LOG_(FATAL) << "Only one " << stream_name
11529                       << " capturer can exist at a time.";
11530   }
11531   *stream = new CapturedStream(fd);
11532 }
11533 
11534 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)11535 static std::string GetCapturedStream(CapturedStream** captured_stream) {
11536   const std::string content = (*captured_stream)->GetCapturedString();
11537 
11538   delete *captured_stream;
11539   *captured_stream = nullptr;
11540 
11541   return content;
11542 }
11543 
11544 // Starts capturing stdout.
CaptureStdout()11545 void CaptureStdout() {
11546   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
11547 }
11548 
11549 // Starts capturing stderr.
CaptureStderr()11550 void CaptureStderr() {
11551   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
11552 }
11553 
11554 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()11555 std::string GetCapturedStdout() {
11556   return GetCapturedStream(&g_captured_stdout);
11557 }
11558 
11559 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()11560 std::string GetCapturedStderr() {
11561   return GetCapturedStream(&g_captured_stderr);
11562 }
11563 
11564 #endif  // GTEST_HAS_STREAM_REDIRECTION
11565 
11566 
11567 
11568 
11569 
GetFileSize(FILE * file)11570 size_t GetFileSize(FILE* file) {
11571   fseek(file, 0, SEEK_END);
11572   return static_cast<size_t>(ftell(file));
11573 }
11574 
ReadEntireFile(FILE * file)11575 std::string ReadEntireFile(FILE* file) {
11576   const size_t file_size = GetFileSize(file);
11577   char* const buffer = new char[file_size];
11578 
11579   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
11580   size_t bytes_read = 0;       // # of bytes read so far
11581 
11582   fseek(file, 0, SEEK_SET);
11583 
11584   // Keeps reading the file until we cannot read further or the
11585   // pre-determined file size is reached.
11586   do {
11587     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
11588     bytes_read += bytes_last_read;
11589   } while (bytes_last_read > 0 && bytes_read < file_size);
11590 
11591   const std::string content(buffer, bytes_read);
11592   delete[] buffer;
11593 
11594   return content;
11595 }
11596 
11597 #if GTEST_HAS_DEATH_TEST
11598 static const std::vector<std::string>* g_injected_test_argvs =
11599     nullptr;  // Owned.
11600 
GetInjectableArgvs()11601 std::vector<std::string> GetInjectableArgvs() {
11602   if (g_injected_test_argvs != nullptr) {
11603     return *g_injected_test_argvs;
11604   }
11605   return GetArgvs();
11606 }
11607 
SetInjectableArgvs(const std::vector<std::string> * new_argvs)11608 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
11609   if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
11610   g_injected_test_argvs = new_argvs;
11611 }
11612 
SetInjectableArgvs(const std::vector<std::string> & new_argvs)11613 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
11614   SetInjectableArgvs(
11615       new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
11616 }
11617 
ClearInjectableArgvs()11618 void ClearInjectableArgvs() {
11619   delete g_injected_test_argvs;
11620   g_injected_test_argvs = nullptr;
11621 }
11622 #endif  // GTEST_HAS_DEATH_TEST
11623 
11624 #if GTEST_OS_WINDOWS_MOBILE
11625 namespace posix {
Abort()11626 void Abort() {
11627   DebugBreak();
11628   TerminateProcess(GetCurrentProcess(), 1);
11629 }
11630 }  // namespace posix
11631 #endif  // GTEST_OS_WINDOWS_MOBILE
11632 
11633 // Returns the name of the environment variable corresponding to the
11634 // given flag.  For example, FlagToEnvVar("foo") will return
11635 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)11636 static std::string FlagToEnvVar(const char* flag) {
11637   const std::string full_flag =
11638       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
11639 
11640   Message env_var;
11641   for (size_t i = 0; i != full_flag.length(); i++) {
11642     env_var << ToUpper(full_flag.c_str()[i]);
11643   }
11644 
11645   return env_var.GetString();
11646 }
11647 
11648 // Parses 'str' for a 32-bit signed integer.  If successful, writes
11649 // the result to *value and returns true; otherwise leaves *value
11650 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,int32_t * value)11651 bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
11652   // Parses the environment variable as a decimal integer.
11653   char* end = nullptr;
11654   const long long_value = strtol(str, &end, 10);  // NOLINT
11655 
11656   // Has strtol() consumed all characters in the string?
11657   if (*end != '\0') {
11658     // No - an invalid character was encountered.
11659     Message msg;
11660     msg << "WARNING: " << src_text
11661         << " is expected to be a 32-bit integer, but actually"
11662         << " has value \"" << str << "\".\n";
11663     printf("%s", msg.GetString().c_str());
11664     fflush(stdout);
11665     return false;
11666   }
11667 
11668   // Is the parsed value in the range of an int32_t?
11669   const auto result = static_cast<int32_t>(long_value);
11670   if (long_value == LONG_MAX || long_value == LONG_MIN ||
11671       // The parsed value overflows as a long.  (strtol() returns
11672       // LONG_MAX or LONG_MIN when the input overflows.)
11673       result != long_value
11674       // The parsed value overflows as an int32_t.
11675       ) {
11676     Message msg;
11677     msg << "WARNING: " << src_text
11678         << " is expected to be a 32-bit integer, but actually"
11679         << " has value " << str << ", which overflows.\n";
11680     printf("%s", msg.GetString().c_str());
11681     fflush(stdout);
11682     return false;
11683   }
11684 
11685   *value = result;
11686   return true;
11687 }
11688 
11689 // Reads and returns the Boolean environment variable corresponding to
11690 // the given flag; if it's not set, returns default_value.
11691 //
11692 // The value is considered true if and only if it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)11693 bool BoolFromGTestEnv(const char* flag, bool default_value) {
11694 #if defined(GTEST_GET_BOOL_FROM_ENV_)
11695   return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
11696 #else
11697   const std::string env_var = FlagToEnvVar(flag);
11698   const char* const string_value = posix::GetEnv(env_var.c_str());
11699   return string_value == nullptr ? default_value
11700                                  : strcmp(string_value, "0") != 0;
11701 #endif  // defined(GTEST_GET_BOOL_FROM_ENV_)
11702 }
11703 
11704 // Reads and returns a 32-bit integer stored in the environment
11705 // variable corresponding to the given flag; if it isn't set or
11706 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,int32_t default_value)11707 int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
11708 #if defined(GTEST_GET_INT32_FROM_ENV_)
11709   return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
11710 #else
11711   const std::string env_var = FlagToEnvVar(flag);
11712   const char* const string_value = posix::GetEnv(env_var.c_str());
11713   if (string_value == nullptr) {
11714     // The environment variable is not set.
11715     return default_value;
11716   }
11717 
11718   int32_t result = default_value;
11719   if (!ParseInt32(Message() << "Environment variable " << env_var,
11720                   string_value, &result)) {
11721     printf("The default value %s is used.\n",
11722            (Message() << default_value).GetString().c_str());
11723     fflush(stdout);
11724     return default_value;
11725   }
11726 
11727   return result;
11728 #endif  // defined(GTEST_GET_INT32_FROM_ENV_)
11729 }
11730 
11731 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
11732 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
11733 // system.  The value of XML_OUTPUT_FILE is a filename without the
11734 // "xml:" prefix of GTEST_OUTPUT.
11735 // Note that this is meant to be called at the call site so it does
11736 // not check that the flag is 'output'
11737 // In essence this checks an env variable called XML_OUTPUT_FILE
11738 // and if it is set we prepend "xml:" to its value, if it not set we return ""
OutputFlagAlsoCheckEnvVar()11739 std::string OutputFlagAlsoCheckEnvVar(){
11740   std::string default_value_for_output_flag = "";
11741   const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
11742   if (nullptr != xml_output_file_env) {
11743     default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
11744   }
11745   return default_value_for_output_flag;
11746 }
11747 
11748 // Reads and returns the string environment variable corresponding to
11749 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)11750 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
11751 #if defined(GTEST_GET_STRING_FROM_ENV_)
11752   return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
11753 #else
11754   const std::string env_var = FlagToEnvVar(flag);
11755   const char* const value = posix::GetEnv(env_var.c_str());
11756   return value == nullptr ? default_value : value;
11757 #endif  // defined(GTEST_GET_STRING_FROM_ENV_)
11758 }
11759 
11760 }  // namespace internal
11761 }  // namespace testing
11762 // Copyright 2007, Google Inc.
11763 // All rights reserved.
11764 //
11765 // Redistribution and use in source and binary forms, with or without
11766 // modification, are permitted provided that the following conditions are
11767 // met:
11768 //
11769 //     * Redistributions of source code must retain the above copyright
11770 // notice, this list of conditions and the following disclaimer.
11771 //     * Redistributions in binary form must reproduce the above
11772 // copyright notice, this list of conditions and the following disclaimer
11773 // in the documentation and/or other materials provided with the
11774 // distribution.
11775 //     * Neither the name of Google Inc. nor the names of its
11776 // contributors may be used to endorse or promote products derived from
11777 // this software without specific prior written permission.
11778 //
11779 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11780 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11781 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11782 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11783 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11784 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11785 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11786 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11787 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11788 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11789 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11790 
11791 
11792 // Google Test - The Google C++ Testing and Mocking Framework
11793 //
11794 // This file implements a universal value printer that can print a
11795 // value of any type T:
11796 //
11797 //   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
11798 //
11799 // It uses the << operator when possible, and prints the bytes in the
11800 // object otherwise.  A user can override its behavior for a class
11801 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
11802 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
11803 // defines Foo.
11804 
11805 
11806 #include <stdio.h>
11807 
11808 #include <cctype>
11809 #include <cstdint>
11810 #include <cwchar>
11811 #include <ostream>  // NOLINT
11812 #include <string>
11813 #include <type_traits>
11814 
11815 
11816 namespace testing {
11817 
11818 namespace {
11819 
11820 using ::std::ostream;
11821 
11822 // Prints a segment of bytes in the given object.
11823 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11824 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11825 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
11826 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintByteSegmentInObjectTo(const unsigned char * obj_bytes,size_t start,size_t count,ostream * os)11827 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
11828                                 size_t count, ostream* os) {
11829   char text[5] = "";
11830   for (size_t i = 0; i != count; i++) {
11831     const size_t j = start + i;
11832     if (i != 0) {
11833       // Organizes the bytes into groups of 2 for easy parsing by
11834       // human.
11835       if ((j % 2) == 0)
11836         *os << ' ';
11837       else
11838         *os << '-';
11839     }
11840     GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
11841     *os << text;
11842   }
11843 }
11844 
11845 // Prints the bytes in the given value to the given ostream.
PrintBytesInObjectToImpl(const unsigned char * obj_bytes,size_t count,ostream * os)11846 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
11847                               ostream* os) {
11848   // Tells the user how big the object is.
11849   *os << count << "-byte object <";
11850 
11851   const size_t kThreshold = 132;
11852   const size_t kChunkSize = 64;
11853   // If the object size is bigger than kThreshold, we'll have to omit
11854   // some details by printing only the first and the last kChunkSize
11855   // bytes.
11856   if (count < kThreshold) {
11857     PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
11858   } else {
11859     PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
11860     *os << " ... ";
11861     // Rounds up to 2-byte boundary.
11862     const size_t resume_pos = (count - kChunkSize + 1)/2*2;
11863     PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
11864   }
11865   *os << ">";
11866 }
11867 
11868 // Helpers for widening a character to char32_t. Since the standard does not
11869 // specify if char / wchar_t is signed or unsigned, it is important to first
11870 // convert it to the unsigned type of the same width before widening it to
11871 // char32_t.
11872 template <typename CharType>
ToChar32(CharType in)11873 char32_t ToChar32(CharType in) {
11874   return static_cast<char32_t>(
11875       static_cast<typename std::make_unsigned<CharType>::type>(in));
11876 }
11877 
11878 }  // namespace
11879 
11880 namespace internal {
11881 
11882 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
11883 // given object.  The delegation simplifies the implementation, which
11884 // uses the << operator and thus is easier done outside of the
11885 // ::testing::internal namespace, which contains a << operator that
11886 // sometimes conflicts with the one in STL.
PrintBytesInObjectTo(const unsigned char * obj_bytes,size_t count,ostream * os)11887 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
11888                           ostream* os) {
11889   PrintBytesInObjectToImpl(obj_bytes, count, os);
11890 }
11891 
11892 // Depending on the value of a char (or wchar_t), we print it in one
11893 // of three formats:
11894 //   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
11895 //   - as a hexadecimal escape sequence (e.g. '\x7F'), or
11896 //   - as a special escape sequence (e.g. '\r', '\n').
11897 enum CharFormat {
11898   kAsIs,
11899   kHexEscape,
11900   kSpecialEscape
11901 };
11902 
11903 // Returns true if c is a printable ASCII character.  We test the
11904 // value of c directly instead of calling isprint(), which is buggy on
11905 // Windows Mobile.
IsPrintableAscii(char32_t c)11906 inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
11907 
11908 // Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
11909 // character literal without the quotes, escaping it when necessary; returns how
11910 // c was formatted.
11911 template <typename Char>
PrintAsCharLiteralTo(Char c,ostream * os)11912 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
11913   const char32_t u_c = ToChar32(c);
11914   switch (u_c) {
11915     case L'\0':
11916       *os << "\\0";
11917       break;
11918     case L'\'':
11919       *os << "\\'";
11920       break;
11921     case L'\\':
11922       *os << "\\\\";
11923       break;
11924     case L'\a':
11925       *os << "\\a";
11926       break;
11927     case L'\b':
11928       *os << "\\b";
11929       break;
11930     case L'\f':
11931       *os << "\\f";
11932       break;
11933     case L'\n':
11934       *os << "\\n";
11935       break;
11936     case L'\r':
11937       *os << "\\r";
11938       break;
11939     case L'\t':
11940       *os << "\\t";
11941       break;
11942     case L'\v':
11943       *os << "\\v";
11944       break;
11945     default:
11946       if (IsPrintableAscii(u_c)) {
11947         *os << static_cast<char>(c);
11948         return kAsIs;
11949       } else {
11950         ostream::fmtflags flags = os->flags();
11951         *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
11952         os->flags(flags);
11953         return kHexEscape;
11954       }
11955   }
11956   return kSpecialEscape;
11957 }
11958 
11959 // Prints a char32_t c as if it's part of a string literal, escaping it when
11960 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char32_t c,ostream * os)11961 static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
11962   switch (c) {
11963     case L'\'':
11964       *os << "'";
11965       return kAsIs;
11966     case L'"':
11967       *os << "\\\"";
11968       return kSpecialEscape;
11969     default:
11970       return PrintAsCharLiteralTo(c, os);
11971   }
11972 }
11973 
GetCharWidthPrefix(char)11974 static const char* GetCharWidthPrefix(char) {
11975   return "";
11976 }
11977 
GetCharWidthPrefix(signed char)11978 static const char* GetCharWidthPrefix(signed char) {
11979   return "";
11980 }
11981 
GetCharWidthPrefix(unsigned char)11982 static const char* GetCharWidthPrefix(unsigned char) {
11983   return "";
11984 }
11985 
11986 #ifdef __cpp_char8_t
GetCharWidthPrefix(char8_t)11987 static const char* GetCharWidthPrefix(char8_t) {
11988   return "u8";
11989 }
11990 #endif
11991 
GetCharWidthPrefix(char16_t)11992 static const char* GetCharWidthPrefix(char16_t) {
11993   return "u";
11994 }
11995 
GetCharWidthPrefix(char32_t)11996 static const char* GetCharWidthPrefix(char32_t) {
11997   return "U";
11998 }
11999 
GetCharWidthPrefix(wchar_t)12000 static const char* GetCharWidthPrefix(wchar_t) {
12001   return "L";
12002 }
12003 
12004 // Prints a char c as if it's part of a string literal, escaping it when
12005 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char c,ostream * os)12006 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
12007   return PrintAsStringLiteralTo(ToChar32(c), os);
12008 }
12009 
12010 #ifdef __cpp_char8_t
PrintAsStringLiteralTo(char8_t c,ostream * os)12011 static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
12012   return PrintAsStringLiteralTo(ToChar32(c), os);
12013 }
12014 #endif
12015 
PrintAsStringLiteralTo(char16_t c,ostream * os)12016 static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
12017   return PrintAsStringLiteralTo(ToChar32(c), os);
12018 }
12019 
PrintAsStringLiteralTo(wchar_t c,ostream * os)12020 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
12021   return PrintAsStringLiteralTo(ToChar32(c), os);
12022 }
12023 
12024 // Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
12025 // and its code. '\0' is printed as "'\\0'", other unprintable characters are
12026 // also properly escaped using the standard C++ escape sequence.
12027 template <typename Char>
PrintCharAndCodeTo(Char c,ostream * os)12028 void PrintCharAndCodeTo(Char c, ostream* os) {
12029   // First, print c as a literal in the most readable form we can find.
12030   *os << GetCharWidthPrefix(c) << "'";
12031   const CharFormat format = PrintAsCharLiteralTo(c, os);
12032   *os << "'";
12033 
12034   // To aid user debugging, we also print c's code in decimal, unless
12035   // it's 0 (in which case c was printed as '\\0', making the code
12036   // obvious).
12037   if (c == 0)
12038     return;
12039   *os << " (" << static_cast<int>(c);
12040 
12041   // For more convenience, we print c's code again in hexadecimal,
12042   // unless c was already printed in the form '\x##' or the code is in
12043   // [1, 9].
12044   if (format == kHexEscape || (1 <= c && c <= 9)) {
12045     // Do nothing.
12046   } else {
12047     *os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
12048   }
12049   *os << ")";
12050 }
12051 
PrintTo(unsigned char c,::std::ostream * os)12052 void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
PrintTo(signed char c,::std::ostream * os)12053 void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
12054 
12055 // Prints a wchar_t as a symbol if it is printable or as its internal
12056 // code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
PrintTo(wchar_t wc,ostream * os)12057 void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
12058 
12059 // TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
PrintTo(char32_t c,::std::ostream * os)12060 void PrintTo(char32_t c, ::std::ostream* os) {
12061   *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
12062       << static_cast<uint32_t>(c);
12063 }
12064 
12065 // Prints the given array of characters to the ostream.  CharType must be either
12066 // char, char8_t, char16_t, char32_t, or wchar_t.
12067 // The array starts at begin, the length is len, it may include '\0' characters
12068 // and may not be NUL-terminated.
12069 template <typename CharType>
12070 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
12071 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
12072 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
12073 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintCharsAsStringTo(const CharType * begin,size_t len,ostream * os)12074 static CharFormat PrintCharsAsStringTo(
12075     const CharType* begin, size_t len, ostream* os) {
12076   const char* const quote_prefix = GetCharWidthPrefix(*begin);
12077   *os << quote_prefix << "\"";
12078   bool is_previous_hex = false;
12079   CharFormat print_format = kAsIs;
12080   for (size_t index = 0; index < len; ++index) {
12081     const CharType cur = begin[index];
12082     if (is_previous_hex && IsXDigit(cur)) {
12083       // Previous character is of '\x..' form and this character can be
12084       // interpreted as another hexadecimal digit in its number. Break string to
12085       // disambiguate.
12086       *os << "\" " << quote_prefix << "\"";
12087     }
12088     is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
12089     // Remember if any characters required hex escaping.
12090     if (is_previous_hex) {
12091       print_format = kHexEscape;
12092     }
12093   }
12094   *os << "\"";
12095   return print_format;
12096 }
12097 
12098 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
12099 // 'begin'.  CharType must be either char or wchar_t.
12100 template <typename CharType>
12101 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
12102 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
12103 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
12104 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
UniversalPrintCharArray(const CharType * begin,size_t len,ostream * os)12105 static void UniversalPrintCharArray(
12106     const CharType* begin, size_t len, ostream* os) {
12107   // The code
12108   //   const char kFoo[] = "foo";
12109   // generates an array of 4, not 3, elements, with the last one being '\0'.
12110   //
12111   // Therefore when printing a char array, we don't print the last element if
12112   // it's '\0', such that the output matches the string literal as it's
12113   // written in the source code.
12114   if (len > 0 && begin[len - 1] == '\0') {
12115     PrintCharsAsStringTo(begin, len - 1, os);
12116     return;
12117   }
12118 
12119   // If, however, the last element in the array is not '\0', e.g.
12120   //    const char kFoo[] = { 'f', 'o', 'o' };
12121   // we must print the entire array.  We also print a message to indicate
12122   // that the array is not NUL-terminated.
12123   PrintCharsAsStringTo(begin, len, os);
12124   *os << " (no terminating NUL)";
12125 }
12126 
12127 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
UniversalPrintArray(const char * begin,size_t len,ostream * os)12128 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
12129   UniversalPrintCharArray(begin, len, os);
12130 }
12131 
12132 #ifdef __cpp_char8_t
12133 // Prints a (const) char8_t array of 'len' elements, starting at address
12134 // 'begin'.
UniversalPrintArray(const char8_t * begin,size_t len,ostream * os)12135 void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
12136   UniversalPrintCharArray(begin, len, os);
12137 }
12138 #endif
12139 
12140 // Prints a (const) char16_t array of 'len' elements, starting at address
12141 // 'begin'.
UniversalPrintArray(const char16_t * begin,size_t len,ostream * os)12142 void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
12143   UniversalPrintCharArray(begin, len, os);
12144 }
12145 
12146 // Prints a (const) char32_t array of 'len' elements, starting at address
12147 // 'begin'.
UniversalPrintArray(const char32_t * begin,size_t len,ostream * os)12148 void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
12149   UniversalPrintCharArray(begin, len, os);
12150 }
12151 
12152 // Prints a (const) wchar_t array of 'len' elements, starting at address
12153 // 'begin'.
UniversalPrintArray(const wchar_t * begin,size_t len,ostream * os)12154 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
12155   UniversalPrintCharArray(begin, len, os);
12156 }
12157 
12158 namespace {
12159 
12160 // Prints a null-terminated C-style string to the ostream.
12161 template <typename Char>
PrintCStringTo(const Char * s,ostream * os)12162 void PrintCStringTo(const Char* s, ostream* os) {
12163   if (s == nullptr) {
12164     *os << "NULL";
12165   } else {
12166     *os << ImplicitCast_<const void*>(s) << " pointing to ";
12167     PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
12168   }
12169 }
12170 
12171 }  // anonymous namespace
12172 
PrintTo(const char * s,ostream * os)12173 void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
12174 
12175 #ifdef __cpp_char8_t
PrintTo(const char8_t * s,ostream * os)12176 void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
12177 #endif
12178 
PrintTo(const char16_t * s,ostream * os)12179 void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
12180 
PrintTo(const char32_t * s,ostream * os)12181 void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
12182 
12183 // MSVC compiler can be configured to define whar_t as a typedef
12184 // of unsigned short. Defining an overload for const wchar_t* in that case
12185 // would cause pointers to unsigned shorts be printed as wide strings,
12186 // possibly accessing more memory than intended and causing invalid
12187 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
12188 // wchar_t is implemented as a native type.
12189 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
12190 // Prints the given wide C string to the ostream.
PrintTo(const wchar_t * s,ostream * os)12191 void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
12192 #endif  // wchar_t is native
12193 
12194 namespace {
12195 
ContainsUnprintableControlCodes(const char * str,size_t length)12196 bool ContainsUnprintableControlCodes(const char* str, size_t length) {
12197   const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
12198 
12199   for (size_t i = 0; i < length; i++) {
12200     unsigned char ch = *s++;
12201     if (std::iscntrl(ch)) {
12202         switch (ch) {
12203         case '\t':
12204         case '\n':
12205         case '\r':
12206           break;
12207         default:
12208           return true;
12209         }
12210       }
12211   }
12212   return false;
12213 }
12214 
IsUTF8TrailByte(unsigned char t)12215 bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
12216 
IsValidUTF8(const char * str,size_t length)12217 bool IsValidUTF8(const char* str, size_t length) {
12218   const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
12219 
12220   for (size_t i = 0; i < length;) {
12221     unsigned char lead = s[i++];
12222 
12223     if (lead <= 0x7f) {
12224       continue;  // single-byte character (ASCII) 0..7F
12225     }
12226     if (lead < 0xc2) {
12227       return false;  // trail byte or non-shortest form
12228     } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
12229       ++i;  // 2-byte character
12230     } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
12231                IsUTF8TrailByte(s[i]) &&
12232                IsUTF8TrailByte(s[i + 1]) &&
12233                // check for non-shortest form and surrogate
12234                (lead != 0xe0 || s[i] >= 0xa0) &&
12235                (lead != 0xed || s[i] < 0xa0)) {
12236       i += 2;  // 3-byte character
12237     } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
12238                IsUTF8TrailByte(s[i]) &&
12239                IsUTF8TrailByte(s[i + 1]) &&
12240                IsUTF8TrailByte(s[i + 2]) &&
12241                // check for non-shortest form
12242                (lead != 0xf0 || s[i] >= 0x90) &&
12243                (lead != 0xf4 || s[i] < 0x90)) {
12244       i += 3;  // 4-byte character
12245     } else {
12246       return false;
12247     }
12248   }
12249   return true;
12250 }
12251 
ConditionalPrintAsText(const char * str,size_t length,ostream * os)12252 void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
12253   if (!ContainsUnprintableControlCodes(str, length) &&
12254       IsValidUTF8(str, length)) {
12255     *os << "\n    As Text: \"" << str << "\"";
12256   }
12257 }
12258 
12259 }  // anonymous namespace
12260 
PrintStringTo(const::std::string & s,ostream * os)12261 void PrintStringTo(const ::std::string& s, ostream* os) {
12262   if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
12263     if (GTEST_FLAG(print_utf8)) {
12264       ConditionalPrintAsText(s.data(), s.size(), os);
12265     }
12266   }
12267 }
12268 
12269 #ifdef __cpp_char8_t
PrintU8StringTo(const::std::u8string & s,ostream * os)12270 void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
12271   PrintCharsAsStringTo(s.data(), s.size(), os);
12272 }
12273 #endif
12274 
PrintU16StringTo(const::std::u16string & s,ostream * os)12275 void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
12276   PrintCharsAsStringTo(s.data(), s.size(), os);
12277 }
12278 
PrintU32StringTo(const::std::u32string & s,ostream * os)12279 void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
12280   PrintCharsAsStringTo(s.data(), s.size(), os);
12281 }
12282 
12283 #if GTEST_HAS_STD_WSTRING
PrintWideStringTo(const::std::wstring & s,ostream * os)12284 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
12285   PrintCharsAsStringTo(s.data(), s.size(), os);
12286 }
12287 #endif  // GTEST_HAS_STD_WSTRING
12288 
12289 }  // namespace internal
12290 
12291 }  // namespace testing
12292 // Copyright 2008, Google Inc.
12293 // All rights reserved.
12294 //
12295 // Redistribution and use in source and binary forms, with or without
12296 // modification, are permitted provided that the following conditions are
12297 // met:
12298 //
12299 //     * Redistributions of source code must retain the above copyright
12300 // notice, this list of conditions and the following disclaimer.
12301 //     * Redistributions in binary form must reproduce the above
12302 // copyright notice, this list of conditions and the following disclaimer
12303 // in the documentation and/or other materials provided with the
12304 // distribution.
12305 //     * Neither the name of Google Inc. nor the names of its
12306 // contributors may be used to endorse or promote products derived from
12307 // this software without specific prior written permission.
12308 //
12309 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12310 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12311 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12312 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12313 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12314 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12315 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12316 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12317 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12318 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12319 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12320 
12321 //
12322 // The Google C++ Testing and Mocking Framework (Google Test)
12323 
12324 
12325 
12326 namespace testing {
12327 
12328 using internal::GetUnitTestImpl;
12329 
12330 // Gets the summary of the failure message by omitting the stack trace
12331 // in it.
ExtractSummary(const char * message)12332 std::string TestPartResult::ExtractSummary(const char* message) {
12333   const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
12334   return stack_trace == nullptr ? message : std::string(message, stack_trace);
12335 }
12336 
12337 // Prints a TestPartResult object.
operator <<(std::ostream & os,const TestPartResult & result)12338 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
12339   return os << internal::FormatFileLocation(result.file_name(),
12340                                             result.line_number())
12341             << " "
12342             << (result.type() == TestPartResult::kSuccess
12343                     ? "Success"
12344                     : result.type() == TestPartResult::kSkip
12345                           ? "Skipped"
12346                           : result.type() == TestPartResult::kFatalFailure
12347                                 ? "Fatal failure"
12348                                 : "Non-fatal failure")
12349             << ":\n"
12350             << result.message() << std::endl;
12351 }
12352 
12353 // Appends a TestPartResult to the array.
Append(const TestPartResult & result)12354 void TestPartResultArray::Append(const TestPartResult& result) {
12355   array_.push_back(result);
12356 }
12357 
12358 // Returns the TestPartResult at the given index (0-based).
GetTestPartResult(int index) const12359 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
12360   if (index < 0 || index >= size()) {
12361     printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
12362     internal::posix::Abort();
12363   }
12364 
12365   return array_[static_cast<size_t>(index)];
12366 }
12367 
12368 // Returns the number of TestPartResult objects in the array.
size() const12369 int TestPartResultArray::size() const {
12370   return static_cast<int>(array_.size());
12371 }
12372 
12373 namespace internal {
12374 
HasNewFatalFailureHelper()12375 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
12376     : has_new_fatal_failure_(false),
12377       original_reporter_(GetUnitTestImpl()->
12378                          GetTestPartResultReporterForCurrentThread()) {
12379   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
12380 }
12381 
~HasNewFatalFailureHelper()12382 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
12383   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
12384       original_reporter_);
12385 }
12386 
ReportTestPartResult(const TestPartResult & result)12387 void HasNewFatalFailureHelper::ReportTestPartResult(
12388     const TestPartResult& result) {
12389   if (result.fatally_failed())
12390     has_new_fatal_failure_ = true;
12391   original_reporter_->ReportTestPartResult(result);
12392 }
12393 
12394 }  // namespace internal
12395 
12396 }  // namespace testing
12397 // Copyright 2008 Google Inc.
12398 // All Rights Reserved.
12399 //
12400 // Redistribution and use in source and binary forms, with or without
12401 // modification, are permitted provided that the following conditions are
12402 // met:
12403 //
12404 //     * Redistributions of source code must retain the above copyright
12405 // notice, this list of conditions and the following disclaimer.
12406 //     * Redistributions in binary form must reproduce the above
12407 // copyright notice, this list of conditions and the following disclaimer
12408 // in the documentation and/or other materials provided with the
12409 // distribution.
12410 //     * Neither the name of Google Inc. nor the names of its
12411 // contributors may be used to endorse or promote products derived from
12412 // this software without specific prior written permission.
12413 //
12414 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12415 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12416 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12417 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12418 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12419 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12420 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12421 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12422 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12423 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12424 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12425 
12426 
12427 
12428 
12429 namespace testing {
12430 namespace internal {
12431 
12432 // Skips to the first non-space char in str. Returns an empty string if str
12433 // contains only whitespace characters.
SkipSpaces(const char * str)12434 static const char* SkipSpaces(const char* str) {
12435   while (IsSpace(*str))
12436     str++;
12437   return str;
12438 }
12439 
SplitIntoTestNames(const char * src)12440 static std::vector<std::string> SplitIntoTestNames(const char* src) {
12441   std::vector<std::string> name_vec;
12442   src = SkipSpaces(src);
12443   for (; src != nullptr; src = SkipComma(src)) {
12444     name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
12445   }
12446   return name_vec;
12447 }
12448 
12449 // Verifies that registered_tests match the test names in
12450 // registered_tests_; returns registered_tests if successful, or
12451 // aborts the program otherwise.
VerifyRegisteredTestNames(const char * test_suite_name,const char * file,int line,const char * registered_tests)12452 const char* TypedTestSuitePState::VerifyRegisteredTestNames(
12453     const char* test_suite_name, const char* file, int line,
12454     const char* registered_tests) {
12455   RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));
12456 
12457   typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
12458   registered_ = true;
12459 
12460   std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
12461 
12462   Message errors;
12463 
12464   std::set<std::string> tests;
12465   for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
12466        name_it != name_vec.end(); ++name_it) {
12467     const std::string& name = *name_it;
12468     if (tests.count(name) != 0) {
12469       errors << "Test " << name << " is listed more than once.\n";
12470       continue;
12471     }
12472 
12473     if (registered_tests_.count(name) != 0) {
12474       tests.insert(name);
12475     } else {
12476       errors << "No test named " << name
12477              << " can be found in this test suite.\n";
12478     }
12479   }
12480 
12481   for (RegisteredTestIter it = registered_tests_.begin();
12482        it != registered_tests_.end();
12483        ++it) {
12484     if (tests.count(it->first) == 0) {
12485       errors << "You forgot to list test " << it->first << ".\n";
12486     }
12487   }
12488 
12489   const std::string& errors_str = errors.GetString();
12490   if (errors_str != "") {
12491     fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
12492             errors_str.c_str());
12493     fflush(stderr);
12494     posix::Abort();
12495   }
12496 
12497   return registered_tests;
12498 }
12499 
12500 }  // namespace internal
12501 }  // namespace testing
12502