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 GTEST_INCLUDE_GTEST_GTEST_SPI_H_
109 #define GTEST_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   virtual ~ScopedFakeTestPartResultReporter();
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   virtual void ReportTestPartResult(const TestPartResult& result);
154  private:
155   void Init();
156 
157   const InterceptMode intercept_mode_;
158   TestPartResultReporterInterface* old_reporter_;
159   TestPartResultArray* const result_;
160 
161   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
162 };
163 
164 namespace internal {
165 
166 // A helper class for implementing EXPECT_FATAL_FAILURE() and
167 // EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
168 // TestPartResultArray contains exactly one failure that has the given
169 // type and contains the given substring.  If that's not the case, a
170 // non-fatal failure will be generated.
171 class GTEST_API_ SingleFailureChecker {
172  public:
173   // The constructor remembers the arguments.
174   SingleFailureChecker(const TestPartResultArray* results,
175                        TestPartResult::Type type, const std::string& substr);
176   ~SingleFailureChecker();
177  private:
178   const TestPartResultArray* const results_;
179   const TestPartResult::Type type_;
180   const std::string substr_;
181 
182   GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
183 };
184 
185 }  // namespace internal
186 
187 }  // namespace testing
188 
189 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
190 
191 // A set of macros for testing Google Test assertions or code that's expected
192 // to generate Google Test fatal failures.  It verifies that the given
193 // statement will cause exactly one fatal Google Test failure with 'substr'
194 // being part of the failure message.
195 //
196 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
197 // affects and considers failures generated in the current thread and
198 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
199 //
200 // The verification of the assertion is done correctly even when the statement
201 // throws an exception or aborts the current function.
202 //
203 // Known restrictions:
204 //   - 'statement' cannot reference local non-static variables or
205 //     non-static members of the current object.
206 //   - 'statement' cannot return a value.
207 //   - You cannot stream a failure message to this macro.
208 //
209 // Note that even though the implementations of the following two
210 // macros are much alike, we cannot refactor them to use a common
211 // helper macro, due to some peculiarity in how the preprocessor
212 // works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
213 // gtest_unittest.cc will fail to compile if we do that.
214 #define EXPECT_FATAL_FAILURE(statement, substr) \
215   do { \
216     class GTestExpectFatalFailureHelper {\
217      public:\
218       static void Execute() { statement; }\
219     };\
220     ::testing::TestPartResultArray gtest_failures;\
221     ::testing::internal::SingleFailureChecker gtest_checker(\
222         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
223     {\
224       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
225           ::testing::ScopedFakeTestPartResultReporter:: \
226           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
227       GTestExpectFatalFailureHelper::Execute();\
228     }\
229   } while (::testing::internal::AlwaysFalse())
230 
231 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
232   do { \
233     class GTestExpectFatalFailureHelper {\
234      public:\
235       static void Execute() { statement; }\
236     };\
237     ::testing::TestPartResultArray gtest_failures;\
238     ::testing::internal::SingleFailureChecker gtest_checker(\
239         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
240     {\
241       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
242           ::testing::ScopedFakeTestPartResultReporter:: \
243           INTERCEPT_ALL_THREADS, &gtest_failures);\
244       GTestExpectFatalFailureHelper::Execute();\
245     }\
246   } while (::testing::internal::AlwaysFalse())
247 
248 // A macro for testing Google Test assertions or code that's expected to
249 // generate Google Test non-fatal failures.  It asserts that the given
250 // statement will cause exactly one non-fatal Google Test failure with 'substr'
251 // being part of the failure message.
252 //
253 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
254 // affects and considers failures generated in the current thread and
255 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
256 //
257 // 'statement' is allowed to reference local variables and members of
258 // the current object.
259 //
260 // The verification of the assertion is done correctly even when the statement
261 // throws an exception or aborts the current function.
262 //
263 // Known restrictions:
264 //   - You cannot stream a failure message to this macro.
265 //
266 // Note that even though the implementations of the following two
267 // macros are much alike, we cannot refactor them to use a common
268 // helper macro, due to some peculiarity in how the preprocessor
269 // works.  If we do that, the code won't compile when the user gives
270 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
271 // expands to code containing an unprotected comma.  The
272 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
273 // catches that.
274 //
275 // For the same reason, we have to write
276 //   if (::testing::internal::AlwaysTrue()) { statement; }
277 // instead of
278 //   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
279 // to avoid an MSVC warning on unreachable code.
280 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
281   do {\
282     ::testing::TestPartResultArray gtest_failures;\
283     ::testing::internal::SingleFailureChecker gtest_checker(\
284         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
285         (substr));\
286     {\
287       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
288           ::testing::ScopedFakeTestPartResultReporter:: \
289           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
290       if (::testing::internal::AlwaysTrue()) { statement; }\
291     }\
292   } while (::testing::internal::AlwaysFalse())
293 
294 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
295   do {\
296     ::testing::TestPartResultArray gtest_failures;\
297     ::testing::internal::SingleFailureChecker gtest_checker(\
298         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
299         (substr));\
300     {\
301       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
302           ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
303           &gtest_failures);\
304       if (::testing::internal::AlwaysTrue()) { statement; }\
305     }\
306   } while (::testing::internal::AlwaysFalse())
307 
308 #endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
309 
310 #include <ctype.h>
311 #include <math.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 <iomanip>
321 #include <limits>
322 #include <list>
323 #include <map>
324 #include <ostream>  // NOLINT
325 #include <sstream>
326 #include <vector>
327 
328 #if GTEST_OS_LINUX
329 
330 // FIXME: Use autoconf to detect availability of
331 // gettimeofday().
332 # define GTEST_HAS_GETTIMEOFDAY_ 1
333 
334 # include <fcntl.h>  // NOLINT
335 # include <limits.h>  // NOLINT
336 # include <sched.h>  // NOLINT
337 // Declares vsnprintf().  This header is not available on Windows.
338 # include <strings.h>  // NOLINT
339 # include <sys/mman.h>  // NOLINT
340 # include <sys/time.h>  // NOLINT
341 # include <unistd.h>  // NOLINT
342 # include <string>
343 
344 #elif GTEST_OS_SYMBIAN
345 # define GTEST_HAS_GETTIMEOFDAY_ 1
346 # include <sys/time.h>  // NOLINT
347 
348 #elif GTEST_OS_ZOS
349 # define GTEST_HAS_GETTIMEOFDAY_ 1
350 # include <sys/time.h>  // NOLINT
351 
352 // On z/OS we additionally need strings.h for strcasecmp.
353 # include <strings.h>  // NOLINT
354 
355 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
356 
357 # include <windows.h>  // NOLINT
358 # undef min
359 
360 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
361 
362 # include <io.h>  // NOLINT
363 # include <sys/timeb.h>  // NOLINT
364 # include <sys/types.h>  // NOLINT
365 # include <sys/stat.h>  // NOLINT
366 
367 # if GTEST_OS_WINDOWS_MINGW
368 // MinGW has gettimeofday() but not _ftime64().
369 // FIXME: Use autoconf to detect availability of
370 //   gettimeofday().
371 // FIXME: There are other ways to get the time on
372 //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
373 //   supports these.  consider using them instead.
374 #  define GTEST_HAS_GETTIMEOFDAY_ 1
375 #  include <sys/time.h>  // NOLINT
376 # endif  // GTEST_OS_WINDOWS_MINGW
377 
378 // cpplint thinks that the header is already included, so we want to
379 // silence it.
380 # include <windows.h>  // NOLINT
381 # undef min
382 
383 #else
384 
385 // Assume other platforms have gettimeofday().
386 // FIXME: Use autoconf to detect availability of
387 //   gettimeofday().
388 # define GTEST_HAS_GETTIMEOFDAY_ 1
389 
390 // cpplint thinks that the header is already included, so we want to
391 // silence it.
392 # include <sys/time.h>  // NOLINT
393 # include <unistd.h>  // NOLINT
394 
395 #endif  // GTEST_OS_LINUX
396 
397 #if GTEST_HAS_EXCEPTIONS
398 # include <stdexcept>
399 #endif
400 
401 #if GTEST_CAN_STREAM_RESULTS_
402 # include <arpa/inet.h>  // NOLINT
403 # include <netdb.h>  // NOLINT
404 # include <sys/socket.h>  // NOLINT
405 # include <sys/types.h>  // NOLINT
406 #endif
407 
408 // Copyright 2005, Google Inc.
409 // All rights reserved.
410 //
411 // Redistribution and use in source and binary forms, with or without
412 // modification, are permitted provided that the following conditions are
413 // met:
414 //
415 //     * Redistributions of source code must retain the above copyright
416 // notice, this list of conditions and the following disclaimer.
417 //     * Redistributions in binary form must reproduce the above
418 // copyright notice, this list of conditions and the following disclaimer
419 // in the documentation and/or other materials provided with the
420 // distribution.
421 //     * Neither the name of Google Inc. nor the names of its
422 // contributors may be used to endorse or promote products derived from
423 // this software without specific prior written permission.
424 //
425 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
426 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
427 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
428 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
429 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
430 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
431 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
432 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
433 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
434 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
435 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
436 
437 // Utility functions and classes used by the Google C++ testing framework.//
438 // This file contains purely Google Test's internal implementation.  Please
439 // DO NOT #INCLUDE IT IN A USER PROGRAM.
440 
441 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
442 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
443 
444 #ifndef _WIN32_WCE
445 # include <errno.h>
446 #endif  // !_WIN32_WCE
447 #include <stddef.h>
448 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
449 #include <string.h>  // For memmove.
450 
451 #include <algorithm>
452 #include <string>
453 #include <vector>
454 
455 
456 #if GTEST_CAN_STREAM_RESULTS_
457 # include <arpa/inet.h>  // NOLINT
458 # include <netdb.h>  // NOLINT
459 #endif
460 
461 #if GTEST_OS_WINDOWS
462 # include <windows.h>  // NOLINT
463 #endif  // GTEST_OS_WINDOWS
464 
465 
466 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
467 /* class A needs to have dll-interface to be used by clients of class B */)
468 
469 namespace testing {
470 
471 // Declares the flags.
472 //
473 // We don't want the users to modify this flag in the code, but want
474 // Google Test's own unit tests to be able to access it. Therefore we
475 // declare it here as opposed to in gtest.h.
476 GTEST_DECLARE_bool_(death_test_use_fork);
477 
478 namespace internal {
479 
480 // The value of GetTestTypeId() as seen from within the Google Test
481 // library.  This is solely for testing GetTestTypeId().
482 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
483 
484 // Names of the flags (needed for parsing Google Test flags).
485 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
486 const char kBreakOnFailureFlag[] = "break_on_failure";
487 const char kCatchExceptionsFlag[] = "catch_exceptions";
488 const char kColorFlag[] = "color";
489 const char kFilterFlag[] = "filter";
490 const char kListTestsFlag[] = "list_tests";
491 const char kOutputFlag[] = "output";
492 const char kPrintTimeFlag[] = "print_time";
493 const char kPrintUTF8Flag[] = "print_utf8";
494 const char kRandomSeedFlag[] = "random_seed";
495 const char kRepeatFlag[] = "repeat";
496 const char kShuffleFlag[] = "shuffle";
497 const char kStackTraceDepthFlag[] = "stack_trace_depth";
498 const char kStreamResultToFlag[] = "stream_result_to";
499 const char kThrowOnFailureFlag[] = "throw_on_failure";
500 const char kFlagfileFlag[] = "flagfile";
501 
502 // A valid random seed must be in [1, kMaxRandomSeed].
503 const int kMaxRandomSeed = 99999;
504 
505 // g_help_flag is true iff the --help flag or an equivalent form is
506 // specified on the command line.
507 GTEST_API_ extern bool g_help_flag;
508 
509 // Returns the current time in milliseconds.
510 GTEST_API_ TimeInMillis GetTimeInMillis();
511 
512 // Returns true iff Google Test should use colors in the output.
513 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
514 
515 // Formats the given time in milliseconds as seconds.
516 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
517 
518 // Converts the given time in milliseconds to a date string in the ISO 8601
519 // format, without the timezone information.  N.B.: due to the use the
520 // non-reentrant localtime() function, this function is not thread safe.  Do
521 // not use it in any code that can be called from multiple threads.
522 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
523 
524 // Parses a string for an Int32 flag, in the form of "--flag=value".
525 //
526 // On success, stores the value of the flag in *value, and returns
527 // true.  On failure, returns false without changing *value.
528 GTEST_API_ bool ParseInt32Flag(
529     const char* str, const char* flag, Int32* value);
530 
531 // Returns a random seed in range [1, kMaxRandomSeed] based on the
532 // given --gtest_random_seed flag value.
GetRandomSeedFromFlag(Int32 random_seed_flag)533 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
534   const unsigned int raw_seed = (random_seed_flag == 0) ?
535       static_cast<unsigned int>(GetTimeInMillis()) :
536       static_cast<unsigned int>(random_seed_flag);
537 
538   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
539   // it's easy to type.
540   const int normalized_seed =
541       static_cast<int>((raw_seed - 1U) %
542                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
543   return normalized_seed;
544 }
545 
546 // Returns the first valid random seed after 'seed'.  The behavior is
547 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
548 // considered to be 1.
GetNextRandomSeed(int seed)549 inline int GetNextRandomSeed(int seed) {
550   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
551       << "Invalid random seed " << seed << " - must be in [1, "
552       << kMaxRandomSeed << "].";
553   const int next_seed = seed + 1;
554   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
555 }
556 
557 // This class saves the values of all Google Test flags in its c'tor, and
558 // restores them in its d'tor.
559 class GTestFlagSaver {
560  public:
561   // The c'tor.
GTestFlagSaver()562   GTestFlagSaver() {
563     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
564     break_on_failure_ = GTEST_FLAG(break_on_failure);
565     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
566     color_ = GTEST_FLAG(color);
567     death_test_style_ = GTEST_FLAG(death_test_style);
568     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
569     filter_ = GTEST_FLAG(filter);
570     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
571     list_tests_ = GTEST_FLAG(list_tests);
572     output_ = GTEST_FLAG(output);
573     print_time_ = GTEST_FLAG(print_time);
574     print_utf8_ = GTEST_FLAG(print_utf8);
575     random_seed_ = GTEST_FLAG(random_seed);
576     repeat_ = GTEST_FLAG(repeat);
577     shuffle_ = GTEST_FLAG(shuffle);
578     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
579     stream_result_to_ = GTEST_FLAG(stream_result_to);
580     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
581   }
582 
583   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver()584   ~GTestFlagSaver() {
585     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
586     GTEST_FLAG(break_on_failure) = break_on_failure_;
587     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
588     GTEST_FLAG(color) = color_;
589     GTEST_FLAG(death_test_style) = death_test_style_;
590     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
591     GTEST_FLAG(filter) = filter_;
592     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
593     GTEST_FLAG(list_tests) = list_tests_;
594     GTEST_FLAG(output) = output_;
595     GTEST_FLAG(print_time) = print_time_;
596     GTEST_FLAG(print_utf8) = print_utf8_;
597     GTEST_FLAG(random_seed) = random_seed_;
598     GTEST_FLAG(repeat) = repeat_;
599     GTEST_FLAG(shuffle) = shuffle_;
600     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
601     GTEST_FLAG(stream_result_to) = stream_result_to_;
602     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
603   }
604 
605  private:
606   // Fields for saving the original values of flags.
607   bool also_run_disabled_tests_;
608   bool break_on_failure_;
609   bool catch_exceptions_;
610   std::string color_;
611   std::string death_test_style_;
612   bool death_test_use_fork_;
613   std::string filter_;
614   std::string internal_run_death_test_;
615   bool list_tests_;
616   std::string output_;
617   bool print_time_;
618   bool print_utf8_;
619   internal::Int32 random_seed_;
620   internal::Int32 repeat_;
621   bool shuffle_;
622   internal::Int32 stack_trace_depth_;
623   std::string stream_result_to_;
624   bool throw_on_failure_;
625 } GTEST_ATTRIBUTE_UNUSED_;
626 
627 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
628 // code_point parameter is of type UInt32 because wchar_t may not be
629 // wide enough to contain a code point.
630 // If the code_point is not a valid Unicode code point
631 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
632 // to "(Invalid Unicode 0xXXXXXXXX)".
633 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
634 
635 // Converts a wide string to a narrow string in UTF-8 encoding.
636 // The wide string is assumed to have the following encoding:
637 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
638 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
639 // Parameter str points to a null-terminated wide string.
640 // Parameter num_chars may additionally limit the number
641 // of wchar_t characters processed. -1 is used when the entire string
642 // should be processed.
643 // If the string contains code points that are not valid Unicode code points
644 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
645 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
646 // and contains invalid UTF-16 surrogate pairs, values in those pairs
647 // will be encoded as individual Unicode characters from Basic Normal Plane.
648 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
649 
650 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
651 // if the variable is present. If a file already exists at this location, this
652 // function will write over it. If the variable is present, but the file cannot
653 // be created, prints an error and exits.
654 void WriteToShardStatusFileIfNeeded();
655 
656 // Checks whether sharding is enabled by examining the relevant
657 // environment variable values. If the variables are present,
658 // but inconsistent (e.g., shard_index >= total_shards), prints
659 // an error and exits. If in_subprocess_for_death_test, sharding is
660 // disabled because it must only be applied to the original test
661 // process. Otherwise, we could filter out death tests we intended to execute.
662 GTEST_API_ bool ShouldShard(const char* total_shards_str,
663                             const char* shard_index_str,
664                             bool in_subprocess_for_death_test);
665 
666 // Parses the environment variable var as an Int32. If it is unset,
667 // returns default_val. If it is not an Int32, prints an error and
668 // and aborts.
669 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
670 
671 // Given the total number of shards, the shard index, and the test id,
672 // returns true iff the test should be run on this shard. The test id is
673 // some arbitrary but unique non-negative integer assigned to each test
674 // method. Assumes that 0 <= shard_index < total_shards.
675 GTEST_API_ bool ShouldRunTestOnShard(
676     int total_shards, int shard_index, int test_id);
677 
678 // STL container utilities.
679 
680 // Returns the number of elements in the given container that satisfy
681 // the given predicate.
682 template <class Container, typename Predicate>
CountIf(const Container & c,Predicate predicate)683 inline int CountIf(const Container& c, Predicate predicate) {
684   // Implemented as an explicit loop since std::count_if() in libCstd on
685   // Solaris has a non-standard signature.
686   int count = 0;
687   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
688     if (predicate(*it))
689       ++count;
690   }
691   return count;
692 }
693 
694 // Applies a function/functor to each element in the container.
695 template <class Container, typename Functor>
ForEach(const Container & c,Functor functor)696 void ForEach(const Container& c, Functor functor) {
697   std::for_each(c.begin(), c.end(), functor);
698 }
699 
700 // Returns the i-th element of the vector, or default_value if i is not
701 // in range [0, v.size()).
702 template <typename E>
GetElementOr(const std::vector<E> & v,int i,E default_value)703 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
704   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
705 }
706 
707 // Performs an in-place shuffle of a range of the vector's elements.
708 // 'begin' and 'end' are element indices as an STL-style range;
709 // i.e. [begin, end) are shuffled, where 'end' == size() means to
710 // shuffle to the end of the vector.
711 template <typename E>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)712 void ShuffleRange(internal::Random* random, int begin, int end,
713                   std::vector<E>* v) {
714   const int size = static_cast<int>(v->size());
715   GTEST_CHECK_(0 <= begin && begin <= size)
716       << "Invalid shuffle range start " << begin << ": must be in range [0, "
717       << size << "].";
718   GTEST_CHECK_(begin <= end && end <= size)
719       << "Invalid shuffle range finish " << end << ": must be in range ["
720       << begin << ", " << size << "].";
721 
722   // Fisher-Yates shuffle, from
723   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
724   for (int range_width = end - begin; range_width >= 2; range_width--) {
725     const int last_in_range = begin + range_width - 1;
726     const int selected = begin + random->Generate(range_width);
727     std::swap((*v)[selected], (*v)[last_in_range]);
728   }
729 }
730 
731 // Performs an in-place shuffle of the vector's elements.
732 template <typename E>
Shuffle(internal::Random * random,std::vector<E> * v)733 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
734   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
735 }
736 
737 // A function for deleting an object.  Handy for being used as a
738 // functor.
739 template <typename T>
Delete(T * x)740 static void Delete(T* x) {
741   delete x;
742 }
743 
744 // A predicate that checks the key of a TestProperty against a known key.
745 //
746 // TestPropertyKeyIs is copyable.
747 class TestPropertyKeyIs {
748  public:
749   // Constructor.
750   //
751   // TestPropertyKeyIs has NO default constructor.
TestPropertyKeyIs(const std::string & key)752   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
753 
754   // Returns true iff the test name of test property matches on key_.
operator ()(const TestProperty & test_property) const755   bool operator()(const TestProperty& test_property) const {
756     return test_property.key() == key_;
757   }
758 
759  private:
760   std::string key_;
761 };
762 
763 // Class UnitTestOptions.
764 //
765 // This class contains functions for processing options the user
766 // specifies when running the tests.  It has only static members.
767 //
768 // In most cases, the user can specify an option using either an
769 // environment variable or a command line flag.  E.g. you can set the
770 // test filter using either GTEST_FILTER or --gtest_filter.  If both
771 // the variable and the flag are present, the latter overrides the
772 // former.
773 class GTEST_API_ UnitTestOptions {
774  public:
775   // Functions for processing the gtest_output flag.
776 
777   // Returns the output format, or "" for normal printed output.
778   static std::string GetOutputFormat();
779 
780   // Returns the absolute path of the requested output file, or the
781   // default (test_detail.xml in the original working directory) if
782   // none was explicitly specified.
783   static std::string GetAbsolutePathToOutputFile();
784 
785   // Functions for processing the gtest_filter flag.
786 
787   // Returns true iff the wildcard pattern matches the string.  The
788   // first ':' or '\0' character in pattern marks the end of it.
789   //
790   // This recursive algorithm isn't very efficient, but is clear and
791   // works well enough for matching test names, which are short.
792   static bool PatternMatchesString(const char *pattern, const char *str);
793 
794   // Returns true iff the user-specified filter matches the test case
795   // name and the test name.
796   static bool FilterMatchesTest(const std::string &test_case_name,
797                                 const std::string &test_name);
798 
799 #if GTEST_OS_WINDOWS
800   // Function for supporting the gtest_catch_exception flag.
801 
802   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
803   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
804   // This function is useful as an __except condition.
805   static int GTestShouldProcessSEH(DWORD exception_code);
806 #endif  // GTEST_OS_WINDOWS
807 
808   // Returns true if "name" matches the ':' separated list of glob-style
809   // filters in "filter".
810   static bool MatchesFilter(const std::string& name, const char* filter);
811 };
812 
813 // Returns the current application's name, removing directory path if that
814 // is present.  Used by UnitTestOptions::GetOutputFile.
815 GTEST_API_ FilePath GetCurrentExecutableName();
816 
817 // The role interface for getting the OS stack trace as a string.
818 class OsStackTraceGetterInterface {
819  public:
OsStackTraceGetterInterface()820   OsStackTraceGetterInterface() {}
~OsStackTraceGetterInterface()821   virtual ~OsStackTraceGetterInterface() {}
822 
823   // Returns the current OS stack trace as an std::string.  Parameters:
824   //
825   //   max_depth  - the maximum number of stack frames to be included
826   //                in the trace.
827   //   skip_count - the number of top frames to be skipped; doesn't count
828   //                against max_depth.
829   virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
830 
831   // UponLeavingGTest() should be called immediately before Google Test calls
832   // user code. It saves some information about the current stack that
833   // CurrentStackTrace() will use to find and hide Google Test stack frames.
834   virtual void UponLeavingGTest() = 0;
835 
836   // This string is inserted in place of stack frames that are part of
837   // Google Test's implementation.
838   static const char* const kElidedFramesMarker;
839 
840  private:
841   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
842 };
843 
844 // A working implementation of the OsStackTraceGetterInterface interface.
845 class OsStackTraceGetter : public OsStackTraceGetterInterface {
846  public:
OsStackTraceGetter()847   OsStackTraceGetter() {}
848 
849   virtual std::string CurrentStackTrace(int max_depth, int skip_count);
850   virtual void UponLeavingGTest();
851 
852  private:
853 #if GTEST_HAS_ABSL
854   Mutex mutex_;  // Protects all internal state.
855 
856   // We save the stack frame below the frame that calls user code.
857   // We do this because the address of the frame immediately below
858   // the user code changes between the call to UponLeavingGTest()
859   // and any calls to the stack trace code from within the user code.
860   void* caller_frame_ = nullptr;
861 #endif  // GTEST_HAS_ABSL
862 
863   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
864 };
865 
866 // Information about a Google Test trace point.
867 struct TraceInfo {
868   const char* file;
869   int line;
870   std::string message;
871 };
872 
873 // This is the default global test part result reporter used in UnitTestImpl.
874 // This class should only be used by UnitTestImpl.
875 class DefaultGlobalTestPartResultReporter
876   : public TestPartResultReporterInterface {
877  public:
878   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
879   // Implements the TestPartResultReporterInterface. Reports the test part
880   // result in the current test.
881   virtual void ReportTestPartResult(const TestPartResult& result);
882 
883  private:
884   UnitTestImpl* const unit_test_;
885 
886   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
887 };
888 
889 // This is the default per thread test part result reporter used in
890 // UnitTestImpl. This class should only be used by UnitTestImpl.
891 class DefaultPerThreadTestPartResultReporter
892     : public TestPartResultReporterInterface {
893  public:
894   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
895   // Implements the TestPartResultReporterInterface. The implementation just
896   // delegates to the current global test part result reporter of *unit_test_.
897   virtual void ReportTestPartResult(const TestPartResult& result);
898 
899  private:
900   UnitTestImpl* const unit_test_;
901 
902   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
903 };
904 
905 // The private implementation of the UnitTest class.  We don't protect
906 // the methods under a mutex, as this class is not accessible by a
907 // user and the UnitTest class that delegates work to this class does
908 // proper locking.
909 class GTEST_API_ UnitTestImpl {
910  public:
911   explicit UnitTestImpl(UnitTest* parent);
912   virtual ~UnitTestImpl();
913 
914   // There are two different ways to register your own TestPartResultReporter.
915   // You can register your own repoter to listen either only for test results
916   // from the current thread or for results from all threads.
917   // By default, each per-thread test result repoter just passes a new
918   // TestPartResult to the global test result reporter, which registers the
919   // test part result for the currently running test.
920 
921   // Returns the global test part result reporter.
922   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
923 
924   // Sets the global test part result reporter.
925   void SetGlobalTestPartResultReporter(
926       TestPartResultReporterInterface* reporter);
927 
928   // Returns the test part result reporter for the current thread.
929   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
930 
931   // Sets the test part result reporter for the current thread.
932   void SetTestPartResultReporterForCurrentThread(
933       TestPartResultReporterInterface* reporter);
934 
935   // Gets the number of successful test cases.
936   int successful_test_case_count() const;
937 
938   // Gets the number of failed test cases.
939   int failed_test_case_count() const;
940 
941   // Gets the number of all test cases.
942   int total_test_case_count() const;
943 
944   // Gets the number of all test cases that contain at least one test
945   // that should run.
946   int test_case_to_run_count() const;
947 
948   // Gets the number of successful tests.
949   int successful_test_count() const;
950 
951   // Gets the number of failed tests.
952   int failed_test_count() const;
953 
954   // Gets the number of disabled tests that will be reported in the XML report.
955   int reportable_disabled_test_count() const;
956 
957   // Gets the number of disabled tests.
958   int disabled_test_count() const;
959 
960   // Gets the number of tests to be printed in the XML report.
961   int reportable_test_count() const;
962 
963   // Gets the number of all tests.
964   int total_test_count() const;
965 
966   // Gets the number of tests that should run.
967   int test_to_run_count() const;
968 
969   // Gets the time of the test program start, in ms from the start of the
970   // UNIX epoch.
start_timestamp() const971   TimeInMillis start_timestamp() const { return start_timestamp_; }
972 
973   // Gets the elapsed time, in milliseconds.
elapsed_time() const974   TimeInMillis elapsed_time() const { return elapsed_time_; }
975 
976   // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const977   bool Passed() const { return !Failed(); }
978 
979   // Returns true iff the unit test failed (i.e. some test case failed
980   // or something outside of all tests failed).
Failed() const981   bool Failed() const {
982     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
983   }
984 
985   // Gets the i-th test case among all the test cases. i can range from 0 to
986   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const987   const TestCase* GetTestCase(int i) const {
988     const int index = GetElementOr(test_case_indices_, i, -1);
989     return index < 0 ? NULL : test_cases_[i];
990   }
991 
992   // Gets the i-th test case among all the test cases. i can range from 0 to
993   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)994   TestCase* GetMutableTestCase(int i) {
995     const int index = GetElementOr(test_case_indices_, i, -1);
996     return index < 0 ? NULL : test_cases_[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 TestCase with the given name.  If one doesn't
1034   // exist, creates one and returns it.
1035   //
1036   // Arguments:
1037   //
1038   //   test_case_name: name of the test case
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 case
1042   //   tear_down_tc:   pointer to the function that tears down the test case
1043   TestCase* GetTestCase(const char* test_case_name,
1044                         const char* type_param,
1045                         Test::SetUpTestCaseFunc set_up_tc,
1046                         Test::TearDownTestCaseFunc tear_down_tc);
1047 
1048   // Adds a TestInfo to the unit test.
1049   //
1050   // Arguments:
1051   //
1052   //   set_up_tc:    pointer to the function that sets up the test case
1053   //   tear_down_tc: pointer to the function that tears down the test case
1054   //   test_info:    the TestInfo object
AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc,TestInfo * test_info)1055   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1056                    Test::TearDownTestCaseFunc tear_down_tc,
1057                    TestInfo* test_info) {
1058     // In order to support thread-safe death tests, we need to
1059     // remember the original working directory when the test program
1060     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
1061     // the user may have changed the current directory before calling
1062     // RUN_ALL_TESTS().  Therefore we capture the current directory in
1063     // AddTestInfo(), which is called to register a TEST or TEST_F
1064     // before main() is reached.
1065     if (original_working_dir_.IsEmpty()) {
1066       original_working_dir_.Set(FilePath::GetCurrentDir());
1067       GTEST_CHECK_(!original_working_dir_.IsEmpty())
1068           << "Failed to get the current working directory.";
1069     }
1070 
1071     GetTestCase(test_info->test_case_name(),
1072                 test_info->type_param(),
1073                 set_up_tc,
1074                 tear_down_tc)->AddTestInfo(test_info);
1075   }
1076 
1077   // Returns ParameterizedTestCaseRegistry object used to keep track of
1078   // value-parameterized tests and instantiate and register them.
parameterized_test_registry()1079   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1080     return parameterized_test_registry_;
1081   }
1082 
1083   // Sets the TestCase object for the test that's currently running.
set_current_test_case(TestCase * a_current_test_case)1084   void set_current_test_case(TestCase* a_current_test_case) {
1085     current_test_case_ = a_current_test_case;
1086   }
1087 
1088   // Sets the TestInfo object for the test that's currently running.  If
1089   // current_test_info is NULL, the assertion results will be stored in
1090   // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)1091   void set_current_test_info(TestInfo* a_current_test_info) {
1092     current_test_info_ = a_current_test_info;
1093   }
1094 
1095   // Registers all parameterized tests defined using TEST_P and
1096   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1097   // combination. This method can be called more then once; it has guards
1098   // protecting from registering the tests more then once.  If
1099   // value-parameterized tests are disabled, RegisterParameterizedTests is
1100   // present but does nothing.
1101   void RegisterParameterizedTests();
1102 
1103   // Runs all tests in this UnitTest object, prints the result, and
1104   // returns true if all tests are successful.  If any exception is
1105   // thrown during a test, this test is considered to be failed, but
1106   // the rest of the tests will still be run.
1107   bool RunAllTests();
1108 
1109   // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()1110   void ClearNonAdHocTestResult() {
1111     ForEach(test_cases_, TestCase::ClearTestCaseResult);
1112   }
1113 
1114   // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()1115   void ClearAdHocTestResult() {
1116     ad_hoc_test_result_.Clear();
1117   }
1118 
1119   // Adds a TestProperty to the current TestResult object when invoked in a
1120   // context of a test or a test case, or to the global property set. If the
1121   // result already contains a property with the same key, the value will be
1122   // updated.
1123   void RecordProperty(const TestProperty& test_property);
1124 
1125   enum ReactionToSharding {
1126     HONOR_SHARDING_PROTOCOL,
1127     IGNORE_SHARDING_PROTOCOL
1128   };
1129 
1130   // Matches the full name of each test against the user-specified
1131   // filter to decide whether the test should run, then records the
1132   // result in each TestCase and TestInfo object.
1133   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1134   // based on sharding variables in the environment.
1135   // Returns the number of tests that should run.
1136   int FilterTests(ReactionToSharding shard_tests);
1137 
1138   // Prints the names of the tests matching the user-specified filter flag.
1139   void ListTestsMatchingFilter();
1140 
current_test_case() const1141   const TestCase* current_test_case() const { return current_test_case_; }
current_test_info()1142   TestInfo* current_test_info() { return current_test_info_; }
current_test_info() const1143   const TestInfo* current_test_info() const { return current_test_info_; }
1144 
1145   // Returns the vector of environments that need to be set-up/torn-down
1146   // before/after the tests are run.
environments()1147   std::vector<Environment*>& environments() { return environments_; }
1148 
1149   // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()1150   std::vector<TraceInfo>& gtest_trace_stack() {
1151     return *(gtest_trace_stack_.pointer());
1152   }
gtest_trace_stack() const1153   const std::vector<TraceInfo>& gtest_trace_stack() const {
1154     return gtest_trace_stack_.get();
1155   }
1156 
1157 #if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()1158   void InitDeathTestSubprocessControlInfo() {
1159     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1160   }
1161   // Returns a pointer to the parsed --gtest_internal_run_death_test
1162   // flag, or NULL if that flag was not specified.
1163   // This information is useful only in a death test child process.
1164   // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag() const1165   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1166     return internal_run_death_test_flag_.get();
1167   }
1168 
1169   // Returns a pointer to the current death test factory.
death_test_factory()1170   internal::DeathTestFactory* death_test_factory() {
1171     return death_test_factory_.get();
1172   }
1173 
1174   void SuppressTestEventsIfInSubprocess();
1175 
1176   friend class ReplaceDeathTestFactory;
1177 #endif  // GTEST_HAS_DEATH_TEST
1178 
1179   // Initializes the event listener performing XML output as specified by
1180   // UnitTestOptions. Must not be called before InitGoogleTest.
1181   void ConfigureXmlOutput();
1182 
1183 #if GTEST_CAN_STREAM_RESULTS_
1184   // Initializes the event listener for streaming test results to a socket.
1185   // Must not be called before InitGoogleTest.
1186   void ConfigureStreamingOutput();
1187 #endif
1188 
1189   // Performs initialization dependent upon flag values obtained in
1190   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
1191   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
1192   // this function is also called from RunAllTests.  Since this function can be
1193   // called more than once, it has to be idempotent.
1194   void PostFlagParsingInit();
1195 
1196   // Gets the random seed used at the start of the current test iteration.
random_seed() const1197   int random_seed() const { return random_seed_; }
1198 
1199   // Gets the random number generator.
random()1200   internal::Random* random() { return &random_; }
1201 
1202   // Shuffles all test cases, and the tests within each test case,
1203   // making sure that death tests are still run first.
1204   void ShuffleTests();
1205 
1206   // Restores the test cases and tests to their order before the first shuffle.
1207   void UnshuffleTests();
1208 
1209   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1210   // UnitTest::Run() starts.
catch_exceptions() const1211   bool catch_exceptions() const { return catch_exceptions_; }
1212 
1213  private:
1214   friend class ::testing::UnitTest;
1215 
1216   // Used by UnitTest::Run() to capture the state of
1217   // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)1218   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1219 
1220   // The UnitTest object that owns this implementation object.
1221   UnitTest* const parent_;
1222 
1223   // The working directory when the first TEST() or TEST_F() was
1224   // executed.
1225   internal::FilePath original_working_dir_;
1226 
1227   // The default test part result reporters.
1228   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1229   DefaultPerThreadTestPartResultReporter
1230       default_per_thread_test_part_result_reporter_;
1231 
1232   // Points to (but doesn't own) the global test part result reporter.
1233   TestPartResultReporterInterface* global_test_part_result_repoter_;
1234 
1235   // Protects read and write access to global_test_part_result_reporter_.
1236   internal::Mutex global_test_part_result_reporter_mutex_;
1237 
1238   // Points to (but doesn't own) the per-thread test part result reporter.
1239   internal::ThreadLocal<TestPartResultReporterInterface*>
1240       per_thread_test_part_result_reporter_;
1241 
1242   // The vector of environments that need to be set-up/torn-down
1243   // before/after the tests are run.
1244   std::vector<Environment*> environments_;
1245 
1246   // The vector of TestCases in their original order.  It owns the
1247   // elements in the vector.
1248   std::vector<TestCase*> test_cases_;
1249 
1250   // Provides a level of indirection for the test case list to allow
1251   // easy shuffling and restoring the test case order.  The i-th
1252   // element of this vector is the index of the i-th test case in the
1253   // shuffled order.
1254   std::vector<int> test_case_indices_;
1255 
1256   // ParameterizedTestRegistry object used to register value-parameterized
1257   // tests.
1258   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1259 
1260   // Indicates whether RegisterParameterizedTests() has been called already.
1261   bool parameterized_tests_registered_;
1262 
1263   // Index of the last death test case registered.  Initially -1.
1264   int last_death_test_case_;
1265 
1266   // This points to the TestCase for the currently running test.  It
1267   // changes as Google Test goes through one test case after another.
1268   // When no test is running, this is set to NULL and Google Test
1269   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
1270   TestCase* current_test_case_;
1271 
1272   // This points to the TestInfo for the currently running test.  It
1273   // changes as Google Test goes through one test after another.  When
1274   // no test is running, this is set to NULL and Google Test stores
1275   // assertion results in ad_hoc_test_result_.  Initially NULL.
1276   TestInfo* current_test_info_;
1277 
1278   // Normally, a user only writes assertions inside a TEST or TEST_F,
1279   // or inside a function called by a TEST or TEST_F.  Since Google
1280   // Test keeps track of which test is current running, it can
1281   // associate such an assertion with the test it belongs to.
1282   //
1283   // If an assertion is encountered when no TEST or TEST_F is running,
1284   // Google Test attributes the assertion result to an imaginary "ad hoc"
1285   // test, and records the result in ad_hoc_test_result_.
1286   TestResult ad_hoc_test_result_;
1287 
1288   // The list of event listeners that can be used to track events inside
1289   // Google Test.
1290   TestEventListeners listeners_;
1291 
1292   // The OS stack trace getter.  Will be deleted when the UnitTest
1293   // object is destructed.  By default, an OsStackTraceGetter is used,
1294   // but the user can set this field to use a custom getter if that is
1295   // desired.
1296   OsStackTraceGetterInterface* os_stack_trace_getter_;
1297 
1298   // True iff PostFlagParsingInit() has been called.
1299   bool post_flag_parse_init_performed_;
1300 
1301   // The random number seed used at the beginning of the test run.
1302   int random_seed_;
1303 
1304   // Our random number generator.
1305   internal::Random random_;
1306 
1307   // The time of the test program start, in ms from the start of the
1308   // UNIX epoch.
1309   TimeInMillis start_timestamp_;
1310 
1311   // How long the test took to run, in milliseconds.
1312   TimeInMillis elapsed_time_;
1313 
1314 #if GTEST_HAS_DEATH_TEST
1315   // The decomposed components of the gtest_internal_run_death_test flag,
1316   // parsed when RUN_ALL_TESTS is called.
1317   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1318   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1319 #endif  // GTEST_HAS_DEATH_TEST
1320 
1321   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1322   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1323 
1324   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1325   // starts.
1326   bool catch_exceptions_;
1327 
1328   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1329 };  // class UnitTestImpl
1330 
1331 // Convenience function for accessing the global UnitTest
1332 // implementation object.
GetUnitTestImpl()1333 inline UnitTestImpl* GetUnitTestImpl() {
1334   return UnitTest::GetInstance()->impl();
1335 }
1336 
1337 #if GTEST_USES_SIMPLE_RE
1338 
1339 // Internal helper functions for implementing the simple regular
1340 // expression matcher.
1341 GTEST_API_ bool IsInSet(char ch, const char* str);
1342 GTEST_API_ bool IsAsciiDigit(char ch);
1343 GTEST_API_ bool IsAsciiPunct(char ch);
1344 GTEST_API_ bool IsRepeat(char ch);
1345 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1346 GTEST_API_ bool IsAsciiWordChar(char ch);
1347 GTEST_API_ bool IsValidEscape(char ch);
1348 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1349 GTEST_API_ bool ValidateRegex(const char* regex);
1350 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1351 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1352     bool escaped, char ch, char repeat, const char* regex, const char* str);
1353 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1354 
1355 #endif  // GTEST_USES_SIMPLE_RE
1356 
1357 // Parses the command line for Google Test flags, without initializing
1358 // other parts of Google Test.
1359 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1360 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1361 
1362 #if GTEST_HAS_DEATH_TEST
1363 
1364 // Returns the message describing the last system error, regardless of the
1365 // platform.
1366 GTEST_API_ std::string GetLastErrnoDescription();
1367 
1368 // Attempts to parse a string into a positive integer pointed to by the
1369 // number parameter.  Returns true if that is possible.
1370 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1371 // it here.
1372 template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)1373 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1374   // Fail fast if the given string does not begin with a digit;
1375   // this bypasses strtoXXX's "optional leading whitespace and plus
1376   // or minus sign" semantics, which are undesirable here.
1377   if (str.empty() || !IsDigit(str[0])) {
1378     return false;
1379   }
1380   errno = 0;
1381 
1382   char* end;
1383   // BiggestConvertible is the largest integer type that system-provided
1384   // string-to-number conversion routines can return.
1385 
1386 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1387 
1388   // MSVC and C++ Builder define __int64 instead of the standard long long.
1389   typedef unsigned __int64 BiggestConvertible;
1390   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1391 
1392 # else
1393 
1394   typedef unsigned long long BiggestConvertible;  // NOLINT
1395   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1396 
1397 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
1398 
1399   const bool parse_success = *end == '\0' && errno == 0;
1400 
1401   // FIXME: Convert this to compile time assertion when it is
1402   // available.
1403   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1404 
1405   const Integer result = static_cast<Integer>(parsed);
1406   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1407     *number = result;
1408     return true;
1409   }
1410   return false;
1411 }
1412 #endif  // GTEST_HAS_DEATH_TEST
1413 
1414 // TestResult contains some private methods that should be hidden from
1415 // Google Test user but are required for testing. This class allow our tests
1416 // to access them.
1417 //
1418 // This class is supplied only for the purpose of testing Google Test's own
1419 // constructs. Do not use it in user tests, either directly or indirectly.
1420 class TestResultAccessor {
1421  public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1422   static void RecordProperty(TestResult* test_result,
1423                              const std::string& xml_element,
1424                              const TestProperty& property) {
1425     test_result->RecordProperty(xml_element, property);
1426   }
1427 
ClearTestPartResults(TestResult * test_result)1428   static void ClearTestPartResults(TestResult* test_result) {
1429     test_result->ClearTestPartResults();
1430   }
1431 
test_part_results(const TestResult & test_result)1432   static const std::vector<testing::TestPartResult>& test_part_results(
1433       const TestResult& test_result) {
1434     return test_result.test_part_results();
1435   }
1436 };
1437 
1438 #if GTEST_CAN_STREAM_RESULTS_
1439 
1440 // Streams test results to the given port on the given host machine.
1441 class StreamingListener : public EmptyTestEventListener {
1442  public:
1443   // Abstract base class for writing strings to a socket.
1444   class AbstractSocketWriter {
1445    public:
~AbstractSocketWriter()1446     virtual ~AbstractSocketWriter() {}
1447 
1448     // Sends a string to the socket.
1449     virtual void Send(const std::string& message) = 0;
1450 
1451     // Closes the socket.
CloseConnection()1452     virtual void CloseConnection() {}
1453 
1454     // Sends a string and a newline to the socket.
SendLn(const std::string & message)1455     void SendLn(const std::string& message) { Send(message + "\n"); }
1456   };
1457 
1458   // Concrete class for actually writing strings to a socket.
1459   class SocketWriter : public AbstractSocketWriter {
1460    public:
SocketWriter(const std::string & host,const std::string & port)1461     SocketWriter(const std::string& host, const std::string& port)
1462         : sockfd_(-1), host_name_(host), port_num_(port) {
1463       MakeConnection();
1464     }
1465 
~SocketWriter()1466     virtual ~SocketWriter() {
1467       if (sockfd_ != -1)
1468         CloseConnection();
1469     }
1470 
1471     // Sends a string to the socket.
Send(const std::string & message)1472     virtual void Send(const std::string& message) {
1473       GTEST_CHECK_(sockfd_ != -1)
1474           << "Send() can be called only when there is a connection.";
1475 
1476       const int len = static_cast<int>(message.length());
1477       if (write(sockfd_, message.c_str(), len) != len) {
1478         GTEST_LOG_(WARNING)
1479             << "stream_result_to: failed to stream to "
1480             << host_name_ << ":" << port_num_;
1481       }
1482     }
1483 
1484    private:
1485     // Creates a client socket and connects to the server.
1486     void MakeConnection();
1487 
1488     // Closes the socket.
CloseConnection()1489     void CloseConnection() {
1490       GTEST_CHECK_(sockfd_ != -1)
1491           << "CloseConnection() can be called only when there is a connection.";
1492 
1493       close(sockfd_);
1494       sockfd_ = -1;
1495     }
1496 
1497     int sockfd_;  // socket file descriptor
1498     const std::string host_name_;
1499     const std::string port_num_;
1500 
1501     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1502   };  // class SocketWriter
1503 
1504   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1505   static std::string UrlEncode(const char* str);
1506 
StreamingListener(const std::string & host,const std::string & port)1507   StreamingListener(const std::string& host, const std::string& port)
1508       : socket_writer_(new SocketWriter(host, port)) {
1509     Start();
1510   }
1511 
StreamingListener(AbstractSocketWriter * socket_writer)1512   explicit StreamingListener(AbstractSocketWriter* socket_writer)
1513       : socket_writer_(socket_writer) { Start(); }
1514 
OnTestProgramStart(const UnitTest &)1515   void OnTestProgramStart(const UnitTest& /* unit_test */) {
1516     SendLn("event=TestProgramStart");
1517   }
1518 
OnTestProgramEnd(const UnitTest & unit_test)1519   void OnTestProgramEnd(const UnitTest& unit_test) {
1520     // Note that Google Test current only report elapsed time for each
1521     // test iteration, not for the entire test program.
1522     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1523 
1524     // Notify the streaming server to stop.
1525     socket_writer_->CloseConnection();
1526   }
1527 
OnTestIterationStart(const UnitTest &,int iteration)1528   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1529     SendLn("event=TestIterationStart&iteration=" +
1530            StreamableToString(iteration));
1531   }
1532 
OnTestIterationEnd(const UnitTest & unit_test,int)1533   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1534     SendLn("event=TestIterationEnd&passed=" +
1535            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1536            StreamableToString(unit_test.elapsed_time()) + "ms");
1537   }
1538 
OnTestCaseStart(const TestCase & test_case)1539   void OnTestCaseStart(const TestCase& test_case) {
1540     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1541   }
1542 
OnTestCaseEnd(const TestCase & test_case)1543   void OnTestCaseEnd(const TestCase& test_case) {
1544     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1545            + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1546            + "ms");
1547   }
1548 
OnTestStart(const TestInfo & test_info)1549   void OnTestStart(const TestInfo& test_info) {
1550     SendLn(std::string("event=TestStart&name=") + test_info.name());
1551   }
1552 
OnTestEnd(const TestInfo & test_info)1553   void OnTestEnd(const TestInfo& test_info) {
1554     SendLn("event=TestEnd&passed=" +
1555            FormatBool((test_info.result())->Passed()) +
1556            "&elapsed_time=" +
1557            StreamableToString((test_info.result())->elapsed_time()) + "ms");
1558   }
1559 
OnTestPartResult(const TestPartResult & test_part_result)1560   void OnTestPartResult(const TestPartResult& test_part_result) {
1561     const char* file_name = test_part_result.file_name();
1562     if (file_name == NULL)
1563       file_name = "";
1564     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1565            "&line=" + StreamableToString(test_part_result.line_number()) +
1566            "&message=" + UrlEncode(test_part_result.message()));
1567   }
1568 
1569  private:
1570   // Sends the given message and a newline to the socket.
SendLn(const std::string & message)1571   void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1572 
1573   // Called at the start of streaming to notify the receiver what
1574   // protocol we are using.
Start()1575   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1576 
FormatBool(bool value)1577   std::string FormatBool(bool value) { return value ? "1" : "0"; }
1578 
1579   const scoped_ptr<AbstractSocketWriter> socket_writer_;
1580 
1581   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1582 };  // class StreamingListener
1583 
1584 #endif  // GTEST_CAN_STREAM_RESULTS_
1585 
1586 }  // namespace internal
1587 }  // namespace testing
1588 
1589 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
1590 
1591 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
1592 
1593 #if GTEST_OS_WINDOWS
1594 # define vsnprintf _vsnprintf
1595 #endif  // GTEST_OS_WINDOWS
1596 
1597 #if GTEST_OS_MAC
1598 #ifndef GTEST_OS_IOS
1599 #include <crt_externs.h>
1600 #endif
1601 #endif
1602 
1603 #if GTEST_HAS_ABSL
1604 #include "absl/debugging/failure_signal_handler.h"
1605 #include "absl/debugging/stacktrace.h"
1606 #include "absl/debugging/symbolize.h"
1607 #include "absl/strings/str_cat.h"
1608 #endif  // GTEST_HAS_ABSL
1609 
1610 namespace testing {
1611 
1612 using internal::CountIf;
1613 using internal::ForEach;
1614 using internal::GetElementOr;
1615 using internal::Shuffle;
1616 
1617 // Constants.
1618 
1619 // A test whose test case name or test name matches this filter is
1620 // disabled and not run.
1621 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1622 
1623 // A test case whose name matches this filter is considered a death
1624 // test case and will be run before test cases whose name doesn't
1625 // match this filter.
1626 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1627 
1628 // A test filter that matches everything.
1629 static const char kUniversalFilter[] = "*";
1630 
1631 // The default output format.
1632 static const char kDefaultOutputFormat[] = "xml";
1633 // The default output file.
1634 static const char kDefaultOutputFile[] = "test_detail";
1635 
1636 // The environment variable name for the test shard index.
1637 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1638 // The environment variable name for the total number of test shards.
1639 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1640 // The environment variable name for the test shard status file.
1641 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1642 
1643 namespace internal {
1644 
1645 // The text used in failure messages to indicate the start of the
1646 // stack trace.
1647 const char kStackTraceMarker[] = "\nStack trace:\n";
1648 
1649 // g_help_flag is true iff the --help flag or an equivalent form is
1650 // specified on the command line.
1651 bool g_help_flag = false;
1652 
1653 // Utilty function to Open File for Writing
OpenFileForWriting(const std::string & output_file)1654 static FILE* OpenFileForWriting(const std::string& output_file) {
1655   FILE* fileout = NULL;
1656   FilePath output_file_path(output_file);
1657   FilePath output_dir(output_file_path.RemoveFileName());
1658 
1659   if (output_dir.CreateDirectoriesRecursively()) {
1660     fileout = posix::FOpen(output_file.c_str(), "w");
1661   }
1662   if (fileout == NULL) {
1663     GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
1664   }
1665   return fileout;
1666 }
1667 
1668 }  // namespace internal
1669 
1670 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
1671 // environment variable.
GetDefaultFilter()1672 static const char* GetDefaultFilter() {
1673   const char* const testbridge_test_only =
1674       internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
1675   if (testbridge_test_only != NULL) {
1676     return testbridge_test_only;
1677   }
1678   return kUniversalFilter;
1679 }
1680 
1681 GTEST_DEFINE_bool_(
1682     also_run_disabled_tests,
1683     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1684     "Run disabled tests too, in addition to the tests normally being run.");
1685 
1686 GTEST_DEFINE_bool_(
1687     break_on_failure,
1688     internal::BoolFromGTestEnv("break_on_failure", false),
1689     "True iff a failed assertion should be a debugger break-point.");
1690 
1691 GTEST_DEFINE_bool_(
1692     catch_exceptions,
1693     internal::BoolFromGTestEnv("catch_exceptions", true),
1694     "True iff " GTEST_NAME_
1695     " should catch exceptions and treat them as test failures.");
1696 
1697 GTEST_DEFINE_string_(
1698     color,
1699     internal::StringFromGTestEnv("color", "auto"),
1700     "Whether to use colors in the output.  Valid values: yes, no, "
1701     "and auto.  'auto' means to use colors if the output is "
1702     "being sent to a terminal and the TERM environment variable "
1703     "is set to a terminal type that supports colors.");
1704 
1705 GTEST_DEFINE_string_(
1706     filter,
1707     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1708     "A colon-separated list of glob (not regex) patterns "
1709     "for filtering the tests to run, optionally followed by a "
1710     "'-' and a : separated list of negative patterns (tests to "
1711     "exclude).  A test is run if it matches one of the positive "
1712     "patterns and does not match any of the negative patterns.");
1713 
1714 GTEST_DEFINE_bool_(
1715     install_failure_signal_handler,
1716     internal::BoolFromGTestEnv("install_failure_signal_handler", false),
1717     "If true and supported on the current platform, " GTEST_NAME_ " should "
1718     "install a signal handler that dumps debugging information when fatal "
1719     "signals are raised.");
1720 
1721 GTEST_DEFINE_bool_(list_tests, false,
1722                    "List all tests without running them.");
1723 
1724 // The net priority order after flag processing is thus:
1725 //   --gtest_output command line flag
1726 //   GTEST_OUTPUT environment variable
1727 //   XML_OUTPUT_FILE environment variable
1728 //   ''
1729 GTEST_DEFINE_string_(
1730     output,
1731     internal::StringFromGTestEnv("output",
1732       internal::OutputFlagAlsoCheckEnvVar().c_str()),
1733     "A format (defaults to \"xml\" but can be specified to be \"json\"), "
1734     "optionally followed by a colon and an output file name or directory. "
1735     "A directory is indicated by a trailing pathname separator. "
1736     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1737     "If a directory is specified, output files will be created "
1738     "within that directory, with file-names based on the test "
1739     "executable's name and, if necessary, made unique by adding "
1740     "digits.");
1741 
1742 GTEST_DEFINE_bool_(
1743     print_time,
1744     internal::BoolFromGTestEnv("print_time", true),
1745     "True iff " GTEST_NAME_
1746     " should display elapsed time in text output.");
1747 
1748 GTEST_DEFINE_bool_(
1749     print_utf8,
1750     internal::BoolFromGTestEnv("print_utf8", true),
1751     "True iff " GTEST_NAME_
1752     " prints UTF8 characters as text.");
1753 
1754 GTEST_DEFINE_int32_(
1755     random_seed,
1756     internal::Int32FromGTestEnv("random_seed", 0),
1757     "Random number seed to use when shuffling test orders.  Must be in range "
1758     "[1, 99999], or 0 to use a seed based on the current time.");
1759 
1760 GTEST_DEFINE_int32_(
1761     repeat,
1762     internal::Int32FromGTestEnv("repeat", 1),
1763     "How many times to repeat each test.  Specify a negative number "
1764     "for repeating forever.  Useful for shaking out flaky tests.");
1765 
1766 GTEST_DEFINE_bool_(
1767     show_internal_stack_frames, false,
1768     "True iff " GTEST_NAME_ " should include internal stack frames when "
1769     "printing test failure stack traces.");
1770 
1771 GTEST_DEFINE_bool_(
1772     shuffle,
1773     internal::BoolFromGTestEnv("shuffle", false),
1774     "True iff " GTEST_NAME_
1775     " should randomize tests' order on every run.");
1776 
1777 GTEST_DEFINE_int32_(
1778     stack_trace_depth,
1779     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1780     "The maximum number of stack frames to print when an "
1781     "assertion fails.  The valid range is 0 through 100, inclusive.");
1782 
1783 GTEST_DEFINE_string_(
1784     stream_result_to,
1785     internal::StringFromGTestEnv("stream_result_to", ""),
1786     "This flag specifies the host name and the port number on which to stream "
1787     "test results. Example: \"localhost:555\". The flag is effective only on "
1788     "Linux.");
1789 
1790 GTEST_DEFINE_bool_(
1791     throw_on_failure,
1792     internal::BoolFromGTestEnv("throw_on_failure", false),
1793     "When this flag is specified, a failed assertion will throw an exception "
1794     "if exceptions are enabled or exit the program with a non-zero code "
1795     "otherwise. For use with an external test framework.");
1796 
1797 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1798 GTEST_DEFINE_string_(
1799     flagfile,
1800     internal::StringFromGTestEnv("flagfile", ""),
1801     "This flag specifies the flagfile to read command-line flags from.");
1802 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
1803 
1804 namespace internal {
1805 
1806 // Generates a random number from [0, range), using a Linear
1807 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
1808 // than kMaxRange.
Generate(UInt32 range)1809 UInt32 Random::Generate(UInt32 range) {
1810   // These constants are the same as are used in glibc's rand(3).
1811   // Use wider types than necessary to prevent unsigned overflow diagnostics.
1812   state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
1813 
1814   GTEST_CHECK_(range > 0)
1815       << "Cannot generate a number in the range [0, 0).";
1816   GTEST_CHECK_(range <= kMaxRange)
1817       << "Generation of a number in [0, " << range << ") was requested, "
1818       << "but this can only generate numbers in [0, " << kMaxRange << ").";
1819 
1820   // Converting via modulus introduces a bit of downward bias, but
1821   // it's simple, and a linear congruential generator isn't too good
1822   // to begin with.
1823   return state_ % range;
1824 }
1825 
1826 // GTestIsInitialized() returns true iff the user has initialized
1827 // Google Test.  Useful for catching the user mistake of not initializing
1828 // Google Test before calling RUN_ALL_TESTS().
GTestIsInitialized()1829 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1830 
1831 // Iterates over a vector of TestCases, keeping a running sum of the
1832 // results of calling a given int-returning method on each.
1833 // Returns the sum.
SumOverTestCaseList(const std::vector<TestCase * > & case_list,int (TestCase::* method)()const)1834 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1835                                int (TestCase::*method)() const) {
1836   int sum = 0;
1837   for (size_t i = 0; i < case_list.size(); i++) {
1838     sum += (case_list[i]->*method)();
1839   }
1840   return sum;
1841 }
1842 
1843 // Returns true iff the test case passed.
TestCasePassed(const TestCase * test_case)1844 static bool TestCasePassed(const TestCase* test_case) {
1845   return test_case->should_run() && test_case->Passed();
1846 }
1847 
1848 // Returns true iff the test case failed.
TestCaseFailed(const TestCase * test_case)1849 static bool TestCaseFailed(const TestCase* test_case) {
1850   return test_case->should_run() && test_case->Failed();
1851 }
1852 
1853 // Returns true iff test_case contains at least one test that should
1854 // run.
ShouldRunTestCase(const TestCase * test_case)1855 static bool ShouldRunTestCase(const TestCase* test_case) {
1856   return test_case->should_run();
1857 }
1858 
1859 // AssertHelper constructor.
AssertHelper(TestPartResult::Type type,const char * file,int line,const char * message)1860 AssertHelper::AssertHelper(TestPartResult::Type type,
1861                            const char* file,
1862                            int line,
1863                            const char* message)
1864     : data_(new AssertHelperData(type, file, line, message)) {
1865 }
1866 
~AssertHelper()1867 AssertHelper::~AssertHelper() {
1868   delete data_;
1869 }
1870 
1871 // Message assignment, for assertion streaming support.
operator =(const Message & message) const1872 void AssertHelper::operator=(const Message& message) const {
1873   UnitTest::GetInstance()->
1874     AddTestPartResult(data_->type, data_->file, data_->line,
1875                       AppendUserMessage(data_->message, message),
1876                       UnitTest::GetInstance()->impl()
1877                       ->CurrentOsStackTraceExceptTop(1)
1878                       // Skips the stack frame for this function itself.
1879                       );  // NOLINT
1880 }
1881 
1882 // Mutex for linked pointers.
1883 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1884 
1885 // A copy of all command line arguments.  Set by InitGoogleTest().
1886 static ::std::vector<std::string> g_argvs;
1887 
GetArgvs()1888 ::std::vector<std::string> GetArgvs() {
1889 #if defined(GTEST_CUSTOM_GET_ARGVS_)
1890   // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
1891   // ::string. This code converts it to the appropriate type.
1892   const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
1893   return ::std::vector<std::string>(custom.begin(), custom.end());
1894 #else   // defined(GTEST_CUSTOM_GET_ARGVS_)
1895   return g_argvs;
1896 #endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
1897 }
1898 
1899 // Returns the current application's name, removing directory path if that
1900 // is present.
GetCurrentExecutableName()1901 FilePath GetCurrentExecutableName() {
1902   FilePath result;
1903 
1904 #if GTEST_OS_WINDOWS
1905   result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
1906 #else
1907   result.Set(FilePath(GetArgvs()[0]));
1908 #endif  // GTEST_OS_WINDOWS
1909 
1910   return result.RemoveDirectoryName();
1911 }
1912 
1913 // Functions for processing the gtest_output flag.
1914 
1915 // Returns the output format, or "" for normal printed output.
GetOutputFormat()1916 std::string UnitTestOptions::GetOutputFormat() {
1917   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1918   const char* const colon = strchr(gtest_output_flag, ':');
1919   return (colon == NULL) ?
1920       std::string(gtest_output_flag) :
1921       std::string(gtest_output_flag, colon - gtest_output_flag);
1922 }
1923 
1924 // Returns the name of the requested output file, or the default if none
1925 // was explicitly specified.
GetAbsolutePathToOutputFile()1926 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1927   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1928 
1929   std::string format = GetOutputFormat();
1930   if (format.empty())
1931     format = std::string(kDefaultOutputFormat);
1932 
1933   const char* const colon = strchr(gtest_output_flag, ':');
1934   if (colon == NULL)
1935     return internal::FilePath::MakeFileName(
1936         internal::FilePath(
1937             UnitTest::GetInstance()->original_working_dir()),
1938         internal::FilePath(kDefaultOutputFile), 0,
1939         format.c_str()).string();
1940 
1941   internal::FilePath output_name(colon + 1);
1942   if (!output_name.IsAbsolutePath())
1943     // FIXME: on Windows \some\path is not an absolute
1944     // path (as its meaning depends on the current drive), yet the
1945     // following logic for turning it into an absolute path is wrong.
1946     // Fix it.
1947     output_name = internal::FilePath::ConcatPaths(
1948         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1949         internal::FilePath(colon + 1));
1950 
1951   if (!output_name.IsDirectory())
1952     return output_name.string();
1953 
1954   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1955       output_name, internal::GetCurrentExecutableName(),
1956       GetOutputFormat().c_str()));
1957   return result.string();
1958 }
1959 
1960 // Returns true iff the wildcard pattern matches the string.  The
1961 // first ':' or '\0' character in pattern marks the end of it.
1962 //
1963 // This recursive algorithm isn't very efficient, but is clear and
1964 // works well enough for matching test names, which are short.
PatternMatchesString(const char * pattern,const char * str)1965 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1966                                            const char *str) {
1967   switch (*pattern) {
1968     case '\0':
1969     case ':':  // Either ':' or '\0' marks the end of the pattern.
1970       return *str == '\0';
1971     case '?':  // Matches any single character.
1972       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1973     case '*':  // Matches any string (possibly empty) of characters.
1974       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1975           PatternMatchesString(pattern + 1, str);
1976     default:  // Non-special character.  Matches itself.
1977       return *pattern == *str &&
1978           PatternMatchesString(pattern + 1, str + 1);
1979   }
1980 }
1981 
MatchesFilter(const std::string & name,const char * filter)1982 bool UnitTestOptions::MatchesFilter(
1983     const std::string& name, const char* filter) {
1984   const char *cur_pattern = filter;
1985   for (;;) {
1986     if (PatternMatchesString(cur_pattern, name.c_str())) {
1987       return true;
1988     }
1989 
1990     // Finds the next pattern in the filter.
1991     cur_pattern = strchr(cur_pattern, ':');
1992 
1993     // Returns if no more pattern can be found.
1994     if (cur_pattern == NULL) {
1995       return false;
1996     }
1997 
1998     // Skips the pattern separater (the ':' character).
1999     cur_pattern++;
2000   }
2001 }
2002 
2003 // Returns true iff the user-specified filter matches the test case
2004 // name and the test name.
FilterMatchesTest(const std::string & test_case_name,const std::string & test_name)2005 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
2006                                         const std::string &test_name) {
2007   const std::string& full_name = test_case_name + "." + test_name.c_str();
2008 
2009   // Split --gtest_filter at '-', if there is one, to separate into
2010   // positive filter and negative filter portions
2011   const char* const p = GTEST_FLAG(filter).c_str();
2012   const char* const dash = strchr(p, '-');
2013   std::string positive;
2014   std::string negative;
2015   if (dash == NULL) {
2016     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
2017     negative = "";
2018   } else {
2019     positive = std::string(p, dash);   // Everything up to the dash
2020     negative = std::string(dash + 1);  // Everything after the dash
2021     if (positive.empty()) {
2022       // Treat '-test1' as the same as '*-test1'
2023       positive = kUniversalFilter;
2024     }
2025   }
2026 
2027   // A filter is a colon-separated list of patterns.  It matches a
2028   // test if any pattern in it matches the test.
2029   return (MatchesFilter(full_name, positive.c_str()) &&
2030           !MatchesFilter(full_name, negative.c_str()));
2031 }
2032 
2033 #if GTEST_HAS_SEH
2034 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
2035 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
2036 // This function is useful as an __except condition.
GTestShouldProcessSEH(DWORD exception_code)2037 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2038   // Google Test should handle a SEH exception if:
2039   //   1. the user wants it to, AND
2040   //   2. this is not a breakpoint exception, AND
2041   //   3. this is not a C++ exception (VC++ implements them via SEH,
2042   //      apparently).
2043   //
2044   // SEH exception code for C++ exceptions.
2045   // (see http://support.microsoft.com/kb/185294 for more information).
2046   const DWORD kCxxExceptionCode = 0xe06d7363;
2047 
2048   bool should_handle = true;
2049 
2050   if (!GTEST_FLAG(catch_exceptions))
2051     should_handle = false;
2052   else if (exception_code == EXCEPTION_BREAKPOINT)
2053     should_handle = false;
2054   else if (exception_code == kCxxExceptionCode)
2055     should_handle = false;
2056 
2057   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2058 }
2059 #endif  // GTEST_HAS_SEH
2060 
2061 }  // namespace internal
2062 
2063 // The c'tor sets this object as the test part result reporter used by
2064 // Google Test.  The 'result' parameter specifies where to report the
2065 // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter(TestPartResultArray * result)2066 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2067     TestPartResultArray* result)
2068     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2069       result_(result) {
2070   Init();
2071 }
2072 
2073 // The c'tor sets this object as the test part result reporter used by
2074 // Google Test.  The 'result' parameter specifies where to report the
2075 // results.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,TestPartResultArray * result)2076 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2077     InterceptMode intercept_mode, TestPartResultArray* result)
2078     : intercept_mode_(intercept_mode),
2079       result_(result) {
2080   Init();
2081 }
2082 
Init()2083 void ScopedFakeTestPartResultReporter::Init() {
2084   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2085   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2086     old_reporter_ = impl->GetGlobalTestPartResultReporter();
2087     impl->SetGlobalTestPartResultReporter(this);
2088   } else {
2089     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2090     impl->SetTestPartResultReporterForCurrentThread(this);
2091   }
2092 }
2093 
2094 // The d'tor restores the test part result reporter used by Google Test
2095 // before.
~ScopedFakeTestPartResultReporter()2096 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2097   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2098   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2099     impl->SetGlobalTestPartResultReporter(old_reporter_);
2100   } else {
2101     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2102   }
2103 }
2104 
2105 // Increments the test part result count and remembers the result.
2106 // This method is from the TestPartResultReporterInterface interface.
ReportTestPartResult(const TestPartResult & result)2107 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2108     const TestPartResult& result) {
2109   result_->Append(result);
2110 }
2111 
2112 namespace internal {
2113 
2114 // Returns the type ID of ::testing::Test.  We should always call this
2115 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2116 // testing::Test.  This is to work around a suspected linker bug when
2117 // using Google Test as a framework on Mac OS X.  The bug causes
2118 // GetTypeId< ::testing::Test>() to return different values depending
2119 // on whether the call is from the Google Test framework itself or
2120 // from user test code.  GetTestTypeId() is guaranteed to always
2121 // return the same value, as it always calls GetTypeId<>() from the
2122 // gtest.cc, which is within the Google Test framework.
GetTestTypeId()2123 TypeId GetTestTypeId() {
2124   return GetTypeId<Test>();
2125 }
2126 
2127 // The value of GetTestTypeId() as seen from within the Google Test
2128 // library.  This is solely for testing GetTestTypeId().
2129 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2130 
2131 // This predicate-formatter checks that 'results' contains a test part
2132 // failure of the given type and that the failure message contains the
2133 // given substring.
HasOneFailure(const char *,const char *,const char *,const TestPartResultArray & results,TestPartResult::Type type,const std::string & substr)2134 static AssertionResult HasOneFailure(const char* /* results_expr */,
2135                                      const char* /* type_expr */,
2136                                      const char* /* substr_expr */,
2137                                      const TestPartResultArray& results,
2138                                      TestPartResult::Type type,
2139                                      const std::string& substr) {
2140   const std::string expected(type == TestPartResult::kFatalFailure ?
2141                         "1 fatal failure" :
2142                         "1 non-fatal failure");
2143   Message msg;
2144   if (results.size() != 1) {
2145     msg << "Expected: " << expected << "\n"
2146         << "  Actual: " << results.size() << " failures";
2147     for (int i = 0; i < results.size(); i++) {
2148       msg << "\n" << results.GetTestPartResult(i);
2149     }
2150     return AssertionFailure() << msg;
2151   }
2152 
2153   const TestPartResult& r = results.GetTestPartResult(0);
2154   if (r.type() != type) {
2155     return AssertionFailure() << "Expected: " << expected << "\n"
2156                               << "  Actual:\n"
2157                               << r;
2158   }
2159 
2160   if (strstr(r.message(), substr.c_str()) == NULL) {
2161     return AssertionFailure() << "Expected: " << expected << " containing \""
2162                               << substr << "\"\n"
2163                               << "  Actual:\n"
2164                               << r;
2165   }
2166 
2167   return AssertionSuccess();
2168 }
2169 
2170 // The constructor of SingleFailureChecker remembers where to look up
2171 // test part results, what type of failure we expect, and what
2172 // substring the failure message should contain.
SingleFailureChecker(const TestPartResultArray * results,TestPartResult::Type type,const std::string & substr)2173 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2174                                            TestPartResult::Type type,
2175                                            const std::string& substr)
2176     : results_(results), type_(type), substr_(substr) {}
2177 
2178 // The destructor of SingleFailureChecker verifies that the given
2179 // TestPartResultArray contains exactly one failure that has the given
2180 // type and contains the given substring.  If that's not the case, a
2181 // non-fatal failure will be generated.
~SingleFailureChecker()2182 SingleFailureChecker::~SingleFailureChecker() {
2183   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2184 }
2185 
DefaultGlobalTestPartResultReporter(UnitTestImpl * unit_test)2186 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2187     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2188 
ReportTestPartResult(const TestPartResult & result)2189 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2190     const TestPartResult& result) {
2191   unit_test_->current_test_result()->AddTestPartResult(result);
2192   unit_test_->listeners()->repeater()->OnTestPartResult(result);
2193 }
2194 
DefaultPerThreadTestPartResultReporter(UnitTestImpl * unit_test)2195 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2196     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2197 
ReportTestPartResult(const TestPartResult & result)2198 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2199     const TestPartResult& result) {
2200   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2201 }
2202 
2203 // Returns the global test part result reporter.
2204 TestPartResultReporterInterface*
GetGlobalTestPartResultReporter()2205 UnitTestImpl::GetGlobalTestPartResultReporter() {
2206   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2207   return global_test_part_result_repoter_;
2208 }
2209 
2210 // Sets the global test part result reporter.
SetGlobalTestPartResultReporter(TestPartResultReporterInterface * reporter)2211 void UnitTestImpl::SetGlobalTestPartResultReporter(
2212     TestPartResultReporterInterface* reporter) {
2213   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2214   global_test_part_result_repoter_ = reporter;
2215 }
2216 
2217 // Returns the test part result reporter for the current thread.
2218 TestPartResultReporterInterface*
GetTestPartResultReporterForCurrentThread()2219 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2220   return per_thread_test_part_result_reporter_.get();
2221 }
2222 
2223 // Sets the test part result reporter for the current thread.
SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface * reporter)2224 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2225     TestPartResultReporterInterface* reporter) {
2226   per_thread_test_part_result_reporter_.set(reporter);
2227 }
2228 
2229 // Gets the number of successful test cases.
successful_test_case_count() const2230 int UnitTestImpl::successful_test_case_count() const {
2231   return CountIf(test_cases_, TestCasePassed);
2232 }
2233 
2234 // Gets the number of failed test cases.
failed_test_case_count() const2235 int UnitTestImpl::failed_test_case_count() const {
2236   return CountIf(test_cases_, TestCaseFailed);
2237 }
2238 
2239 // Gets the number of all test cases.
total_test_case_count() const2240 int UnitTestImpl::total_test_case_count() const {
2241   return static_cast<int>(test_cases_.size());
2242 }
2243 
2244 // Gets the number of all test cases that contain at least one test
2245 // that should run.
test_case_to_run_count() const2246 int UnitTestImpl::test_case_to_run_count() const {
2247   return CountIf(test_cases_, ShouldRunTestCase);
2248 }
2249 
2250 // Gets the number of successful tests.
successful_test_count() const2251 int UnitTestImpl::successful_test_count() const {
2252   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2253 }
2254 
2255 // Gets the number of failed tests.
failed_test_count() const2256 int UnitTestImpl::failed_test_count() const {
2257   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2258 }
2259 
2260 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const2261 int UnitTestImpl::reportable_disabled_test_count() const {
2262   return SumOverTestCaseList(test_cases_,
2263                              &TestCase::reportable_disabled_test_count);
2264 }
2265 
2266 // Gets the number of disabled tests.
disabled_test_count() const2267 int UnitTestImpl::disabled_test_count() const {
2268   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2269 }
2270 
2271 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const2272 int UnitTestImpl::reportable_test_count() const {
2273   return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2274 }
2275 
2276 // Gets the number of all tests.
total_test_count() const2277 int UnitTestImpl::total_test_count() const {
2278   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2279 }
2280 
2281 // Gets the number of tests that should run.
test_to_run_count() const2282 int UnitTestImpl::test_to_run_count() const {
2283   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2284 }
2285 
2286 // Returns the current OS stack trace as an std::string.
2287 //
2288 // The maximum number of stack frames to be included is specified by
2289 // the gtest_stack_trace_depth flag.  The skip_count parameter
2290 // specifies the number of top frames to be skipped, which doesn't
2291 // count against the number of frames to be included.
2292 //
2293 // For example, if Foo() calls Bar(), which in turn calls
2294 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2295 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
CurrentOsStackTraceExceptTop(int skip_count)2296 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2297   return os_stack_trace_getter()->CurrentStackTrace(
2298       static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2299       skip_count + 1
2300       // Skips the user-specified number of frames plus this function
2301       // itself.
2302       );  // NOLINT
2303 }
2304 
2305 // Returns the current time in milliseconds.
GetTimeInMillis()2306 TimeInMillis GetTimeInMillis() {
2307 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2308   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2309   // http://analogous.blogspot.com/2005/04/epoch.html
2310   const TimeInMillis kJavaEpochToWinFileTimeDelta =
2311     static_cast<TimeInMillis>(116444736UL) * 100000UL;
2312   const DWORD kTenthMicrosInMilliSecond = 10000;
2313 
2314   SYSTEMTIME now_systime;
2315   FILETIME now_filetime;
2316   ULARGE_INTEGER now_int64;
2317   // FIXME: Shouldn't this just use
2318   //   GetSystemTimeAsFileTime()?
2319   GetSystemTime(&now_systime);
2320   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2321     now_int64.LowPart = now_filetime.dwLowDateTime;
2322     now_int64.HighPart = now_filetime.dwHighDateTime;
2323     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2324       kJavaEpochToWinFileTimeDelta;
2325     return now_int64.QuadPart;
2326   }
2327   return 0;
2328 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2329   __timeb64 now;
2330 
2331   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2332   // (deprecated function) there.
2333   // FIXME: Use GetTickCount()?  Or use
2334   //   SystemTimeToFileTime()
2335   GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
2336   _ftime64(&now);
2337   GTEST_DISABLE_MSC_DEPRECATED_POP_()
2338 
2339   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2340 #elif GTEST_HAS_GETTIMEOFDAY_
2341   struct timeval now;
2342   gettimeofday(&now, NULL);
2343   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2344 #else
2345 # error "Don't know how to get the current time on your system."
2346 #endif
2347 }
2348 
2349 // Utilities
2350 
2351 // class String.
2352 
2353 #if GTEST_OS_WINDOWS_MOBILE
2354 // Creates a UTF-16 wide string from the given ANSI string, allocating
2355 // memory using new. The caller is responsible for deleting the return
2356 // value using delete[]. Returns the wide string, or NULL if the
2357 // input is NULL.
AnsiToUtf16(const char * ansi)2358 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2359   if (!ansi) return NULL;
2360   const int length = strlen(ansi);
2361   const int unicode_length =
2362       MultiByteToWideChar(CP_ACP, 0, ansi, length,
2363                           NULL, 0);
2364   WCHAR* unicode = new WCHAR[unicode_length + 1];
2365   MultiByteToWideChar(CP_ACP, 0, ansi, length,
2366                       unicode, unicode_length);
2367   unicode[unicode_length] = 0;
2368   return unicode;
2369 }
2370 
2371 // Creates an ANSI string from the given wide string, allocating
2372 // memory using new. The caller is responsible for deleting the return
2373 // value using delete[]. Returns the ANSI string, or NULL if the
2374 // input is NULL.
Utf16ToAnsi(LPCWSTR utf16_str)2375 const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
2376   if (!utf16_str) return NULL;
2377   const int ansi_length =
2378       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2379                           NULL, 0, NULL, NULL);
2380   char* ansi = new char[ansi_length + 1];
2381   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2382                       ansi, ansi_length, NULL, NULL);
2383   ansi[ansi_length] = 0;
2384   return ansi;
2385 }
2386 
2387 #endif  // GTEST_OS_WINDOWS_MOBILE
2388 
2389 // Compares two C strings.  Returns true iff they have the same content.
2390 //
2391 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
2392 // C string is considered different to any non-NULL C string,
2393 // including the empty string.
CStringEquals(const char * lhs,const char * rhs)2394 bool String::CStringEquals(const char * lhs, const char * rhs) {
2395   if ( lhs == NULL ) return rhs == NULL;
2396 
2397   if ( rhs == NULL ) return false;
2398 
2399   return strcmp(lhs, rhs) == 0;
2400 }
2401 
2402 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2403 
2404 // Converts an array of wide chars to a narrow string using the UTF-8
2405 // encoding, and streams the result to the given Message object.
StreamWideCharsToMessage(const wchar_t * wstr,size_t length,Message * msg)2406 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2407                                      Message* msg) {
2408   for (size_t i = 0; i != length; ) {  // NOLINT
2409     if (wstr[i] != L'\0') {
2410       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2411       while (i != length && wstr[i] != L'\0')
2412         i++;
2413     } else {
2414       *msg << '\0';
2415       i++;
2416     }
2417   }
2418 }
2419 
2420 #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2421 
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)2422 void SplitString(const ::std::string& str, char delimiter,
2423                  ::std::vector< ::std::string>* dest) {
2424   ::std::vector< ::std::string> parsed;
2425   ::std::string::size_type pos = 0;
2426   while (::testing::internal::AlwaysTrue()) {
2427     const ::std::string::size_type colon = str.find(delimiter, pos);
2428     if (colon == ::std::string::npos) {
2429       parsed.push_back(str.substr(pos));
2430       break;
2431     } else {
2432       parsed.push_back(str.substr(pos, colon - pos));
2433       pos = colon + 1;
2434     }
2435   }
2436   dest->swap(parsed);
2437 }
2438 
2439 }  // namespace internal
2440 
2441 // Constructs an empty Message.
2442 // We allocate the stringstream separately because otherwise each use of
2443 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2444 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2445 // the stack space.
Message()2446 Message::Message() : ss_(new ::std::stringstream) {
2447   // By default, we want there to be enough precision when printing
2448   // a double to a Message.
2449   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2450 }
2451 
2452 // These two overloads allow streaming a wide C string to a Message
2453 // using the UTF-8 encoding.
operator <<(const wchar_t * wide_c_str)2454 Message& Message::operator <<(const wchar_t* wide_c_str) {
2455   return *this << internal::String::ShowWideCString(wide_c_str);
2456 }
operator <<(wchar_t * wide_c_str)2457 Message& Message::operator <<(wchar_t* wide_c_str) {
2458   return *this << internal::String::ShowWideCString(wide_c_str);
2459 }
2460 
2461 #if GTEST_HAS_STD_WSTRING
2462 // Converts the given wide string to a narrow string using the UTF-8
2463 // encoding, and streams the result to this Message object.
operator <<(const::std::wstring & wstr)2464 Message& Message::operator <<(const ::std::wstring& wstr) {
2465   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2466   return *this;
2467 }
2468 #endif  // GTEST_HAS_STD_WSTRING
2469 
2470 #if GTEST_HAS_GLOBAL_WSTRING
2471 // Converts the given wide string to a narrow string using the UTF-8
2472 // encoding, and streams the result to this Message object.
operator <<(const::wstring & wstr)2473 Message& Message::operator <<(const ::wstring& wstr) {
2474   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2475   return *this;
2476 }
2477 #endif  // GTEST_HAS_GLOBAL_WSTRING
2478 
2479 // Gets the text streamed to this object so far as an std::string.
2480 // Each '\0' character in the buffer is replaced with "\\0".
GetString() const2481 std::string Message::GetString() const {
2482   return internal::StringStreamToString(ss_.get());
2483 }
2484 
2485 // AssertionResult constructors.
2486 // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult & other)2487 AssertionResult::AssertionResult(const AssertionResult& other)
2488     : success_(other.success_),
2489       message_(other.message_.get() != NULL ?
2490                new ::std::string(*other.message_) :
2491                static_cast< ::std::string*>(NULL)) {
2492 }
2493 
2494 // Swaps two AssertionResults.
swap(AssertionResult & other)2495 void AssertionResult::swap(AssertionResult& other) {
2496   using std::swap;
2497   swap(success_, other.success_);
2498   swap(message_, other.message_);
2499 }
2500 
2501 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
operator !() const2502 AssertionResult AssertionResult::operator!() const {
2503   AssertionResult negation(!success_);
2504   if (message_.get() != NULL)
2505     negation << *message_;
2506   return negation;
2507 }
2508 
2509 // Makes a successful assertion result.
AssertionSuccess()2510 AssertionResult AssertionSuccess() {
2511   return AssertionResult(true);
2512 }
2513 
2514 // Makes a failed assertion result.
AssertionFailure()2515 AssertionResult AssertionFailure() {
2516   return AssertionResult(false);
2517 }
2518 
2519 // Makes a failed assertion result with the given failure message.
2520 // Deprecated; use AssertionFailure() << message.
AssertionFailure(const Message & message)2521 AssertionResult AssertionFailure(const Message& message) {
2522   return AssertionFailure() << message;
2523 }
2524 
2525 namespace internal {
2526 
2527 namespace edit_distance {
CalculateOptimalEdits(const std::vector<size_t> & left,const std::vector<size_t> & right)2528 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2529                                             const std::vector<size_t>& right) {
2530   std::vector<std::vector<double> > costs(
2531       left.size() + 1, std::vector<double>(right.size() + 1));
2532   std::vector<std::vector<EditType> > best_move(
2533       left.size() + 1, std::vector<EditType>(right.size() + 1));
2534 
2535   // Populate for empty right.
2536   for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2537     costs[l_i][0] = static_cast<double>(l_i);
2538     best_move[l_i][0] = kRemove;
2539   }
2540   // Populate for empty left.
2541   for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2542     costs[0][r_i] = static_cast<double>(r_i);
2543     best_move[0][r_i] = kAdd;
2544   }
2545 
2546   for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2547     for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2548       if (left[l_i] == right[r_i]) {
2549         // Found a match. Consume it.
2550         costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2551         best_move[l_i + 1][r_i + 1] = kMatch;
2552         continue;
2553       }
2554 
2555       const double add = costs[l_i + 1][r_i];
2556       const double remove = costs[l_i][r_i + 1];
2557       const double replace = costs[l_i][r_i];
2558       if (add < remove && add < replace) {
2559         costs[l_i + 1][r_i + 1] = add + 1;
2560         best_move[l_i + 1][r_i + 1] = kAdd;
2561       } else if (remove < add && remove < replace) {
2562         costs[l_i + 1][r_i + 1] = remove + 1;
2563         best_move[l_i + 1][r_i + 1] = kRemove;
2564       } else {
2565         // We make replace a little more expensive than add/remove to lower
2566         // their priority.
2567         costs[l_i + 1][r_i + 1] = replace + 1.00001;
2568         best_move[l_i + 1][r_i + 1] = kReplace;
2569       }
2570     }
2571   }
2572 
2573   // Reconstruct the best path. We do it in reverse order.
2574   std::vector<EditType> best_path;
2575   for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2576     EditType move = best_move[l_i][r_i];
2577     best_path.push_back(move);
2578     l_i -= move != kAdd;
2579     r_i -= move != kRemove;
2580   }
2581   std::reverse(best_path.begin(), best_path.end());
2582   return best_path;
2583 }
2584 
2585 namespace {
2586 
2587 // Helper class to convert string into ids with deduplication.
2588 class InternalStrings {
2589  public:
GetId(const std::string & str)2590   size_t GetId(const std::string& str) {
2591     IdMap::iterator it = ids_.find(str);
2592     if (it != ids_.end()) return it->second;
2593     size_t id = ids_.size();
2594     return ids_[str] = id;
2595   }
2596 
2597  private:
2598   typedef std::map<std::string, size_t> IdMap;
2599   IdMap ids_;
2600 };
2601 
2602 }  // namespace
2603 
CalculateOptimalEdits(const std::vector<std::string> & left,const std::vector<std::string> & right)2604 std::vector<EditType> CalculateOptimalEdits(
2605     const std::vector<std::string>& left,
2606     const std::vector<std::string>& right) {
2607   std::vector<size_t> left_ids, right_ids;
2608   {
2609     InternalStrings intern_table;
2610     for (size_t i = 0; i < left.size(); ++i) {
2611       left_ids.push_back(intern_table.GetId(left[i]));
2612     }
2613     for (size_t i = 0; i < right.size(); ++i) {
2614       right_ids.push_back(intern_table.GetId(right[i]));
2615     }
2616   }
2617   return CalculateOptimalEdits(left_ids, right_ids);
2618 }
2619 
2620 namespace {
2621 
2622 // Helper class that holds the state for one hunk and prints it out to the
2623 // stream.
2624 // It reorders adds/removes when possible to group all removes before all
2625 // adds. It also adds the hunk header before printint into the stream.
2626 class Hunk {
2627  public:
Hunk(size_t left_start,size_t right_start)2628   Hunk(size_t left_start, size_t right_start)
2629       : left_start_(left_start),
2630         right_start_(right_start),
2631         adds_(),
2632         removes_(),
2633         common_() {}
2634 
PushLine(char edit,const char * line)2635   void PushLine(char edit, const char* line) {
2636     switch (edit) {
2637       case ' ':
2638         ++common_;
2639         FlushEdits();
2640         hunk_.push_back(std::make_pair(' ', line));
2641         break;
2642       case '-':
2643         ++removes_;
2644         hunk_removes_.push_back(std::make_pair('-', line));
2645         break;
2646       case '+':
2647         ++adds_;
2648         hunk_adds_.push_back(std::make_pair('+', line));
2649         break;
2650     }
2651   }
2652 
PrintTo(std::ostream * os)2653   void PrintTo(std::ostream* os) {
2654     PrintHeader(os);
2655     FlushEdits();
2656     for (std::list<std::pair<char, const char*> >::const_iterator it =
2657              hunk_.begin();
2658          it != hunk_.end(); ++it) {
2659       *os << it->first << it->second << "\n";
2660     }
2661   }
2662 
has_edits() const2663   bool has_edits() const { return adds_ || removes_; }
2664 
2665  private:
FlushEdits()2666   void FlushEdits() {
2667     hunk_.splice(hunk_.end(), hunk_removes_);
2668     hunk_.splice(hunk_.end(), hunk_adds_);
2669   }
2670 
2671   // Print a unified diff header for one hunk.
2672   // The format is
2673   //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2674   // where the left/right parts are omitted if unnecessary.
PrintHeader(std::ostream * ss) const2675   void PrintHeader(std::ostream* ss) const {
2676     *ss << "@@ ";
2677     if (removes_) {
2678       *ss << "-" << left_start_ << "," << (removes_ + common_);
2679     }
2680     if (removes_ && adds_) {
2681       *ss << " ";
2682     }
2683     if (adds_) {
2684       *ss << "+" << right_start_ << "," << (adds_ + common_);
2685     }
2686     *ss << " @@\n";
2687   }
2688 
2689   size_t left_start_, right_start_;
2690   size_t adds_, removes_, common_;
2691   std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2692 };
2693 
2694 }  // namespace
2695 
2696 // Create a list of diff hunks in Unified diff format.
2697 // Each hunk has a header generated by PrintHeader above plus a body with
2698 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
2699 // addition.
2700 // 'context' represents the desired unchanged prefix/suffix around the diff.
2701 // If two hunks are close enough that their contexts overlap, then they are
2702 // joined into one hunk.
CreateUnifiedDiff(const std::vector<std::string> & left,const std::vector<std::string> & right,size_t context)2703 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2704                               const std::vector<std::string>& right,
2705                               size_t context) {
2706   const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2707 
2708   size_t l_i = 0, r_i = 0, edit_i = 0;
2709   std::stringstream ss;
2710   while (edit_i < edits.size()) {
2711     // Find first edit.
2712     while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2713       ++l_i;
2714       ++r_i;
2715       ++edit_i;
2716     }
2717 
2718     // Find the first line to include in the hunk.
2719     const size_t prefix_context = std::min(l_i, context);
2720     Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2721     for (size_t i = prefix_context; i > 0; --i) {
2722       hunk.PushLine(' ', left[l_i - i].c_str());
2723     }
2724 
2725     // Iterate the edits until we found enough suffix for the hunk or the input
2726     // is over.
2727     size_t n_suffix = 0;
2728     for (; edit_i < edits.size(); ++edit_i) {
2729       if (n_suffix >= context) {
2730         // Continue only if the next hunk is very close.
2731         std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2732         while (it != edits.end() && *it == kMatch) ++it;
2733         if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2734           // There is no next edit or it is too far away.
2735           break;
2736         }
2737       }
2738 
2739       EditType edit = edits[edit_i];
2740       // Reset count when a non match is found.
2741       n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2742 
2743       if (edit == kMatch || edit == kRemove || edit == kReplace) {
2744         hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2745       }
2746       if (edit == kAdd || edit == kReplace) {
2747         hunk.PushLine('+', right[r_i].c_str());
2748       }
2749 
2750       // Advance indices, depending on edit type.
2751       l_i += edit != kAdd;
2752       r_i += edit != kRemove;
2753     }
2754 
2755     if (!hunk.has_edits()) {
2756       // We are done. We don't want this hunk.
2757       break;
2758     }
2759 
2760     hunk.PrintTo(&ss);
2761   }
2762   return ss.str();
2763 }
2764 
2765 }  // namespace edit_distance
2766 
2767 namespace {
2768 
2769 // The string representation of the values received in EqFailure() are already
2770 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2771 // characters the same.
SplitEscapedString(const std::string & str)2772 std::vector<std::string> SplitEscapedString(const std::string& str) {
2773   std::vector<std::string> lines;
2774   size_t start = 0, end = str.size();
2775   if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2776     ++start;
2777     --end;
2778   }
2779   bool escaped = false;
2780   for (size_t i = start; i + 1 < end; ++i) {
2781     if (escaped) {
2782       escaped = false;
2783       if (str[i] == 'n') {
2784         lines.push_back(str.substr(start, i - start - 1));
2785         start = i + 1;
2786       }
2787     } else {
2788       escaped = str[i] == '\\';
2789     }
2790   }
2791   lines.push_back(str.substr(start, end - start));
2792   return lines;
2793 }
2794 
2795 }  // namespace
2796 
2797 // Constructs and returns the message for an equality assertion
2798 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2799 //
2800 // The first four parameters are the expressions used in the assertion
2801 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
2802 // where foo is 5 and bar is 6, we have:
2803 //
2804 //   lhs_expression: "foo"
2805 //   rhs_expression: "bar"
2806 //   lhs_value:      "5"
2807 //   rhs_value:      "6"
2808 //
2809 // The ignoring_case parameter is true iff the assertion is a
2810 // *_STRCASEEQ*.  When it's true, the string "Ignoring case" will
2811 // 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)2812 AssertionResult EqFailure(const char* lhs_expression,
2813                           const char* rhs_expression,
2814                           const std::string& lhs_value,
2815                           const std::string& rhs_value,
2816                           bool ignoring_case) {
2817   Message msg;
2818   msg << "Expected equality of these values:";
2819   msg << "\n  " << lhs_expression;
2820   if (lhs_value != lhs_expression) {
2821     msg << "\n    Which is: " << lhs_value;
2822   }
2823   msg << "\n  " << rhs_expression;
2824   if (rhs_value != rhs_expression) {
2825     msg << "\n    Which is: " << rhs_value;
2826   }
2827 
2828   if (ignoring_case) {
2829     msg << "\nIgnoring case";
2830   }
2831 
2832   if (!lhs_value.empty() && !rhs_value.empty()) {
2833     const std::vector<std::string> lhs_lines =
2834         SplitEscapedString(lhs_value);
2835     const std::vector<std::string> rhs_lines =
2836         SplitEscapedString(rhs_value);
2837     if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2838       msg << "\nWith diff:\n"
2839           << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
2840     }
2841   }
2842 
2843   return AssertionFailure() << msg;
2844 }
2845 
2846 // 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)2847 std::string GetBoolAssertionFailureMessage(
2848     const AssertionResult& assertion_result,
2849     const char* expression_text,
2850     const char* actual_predicate_value,
2851     const char* expected_predicate_value) {
2852   const char* actual_message = assertion_result.message();
2853   Message msg;
2854   msg << "Value of: " << expression_text
2855       << "\n  Actual: " << actual_predicate_value;
2856   if (actual_message[0] != '\0')
2857     msg << " (" << actual_message << ")";
2858   msg << "\nExpected: " << expected_predicate_value;
2859   return msg.GetString();
2860 }
2861 
2862 // 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)2863 AssertionResult DoubleNearPredFormat(const char* expr1,
2864                                      const char* expr2,
2865                                      const char* abs_error_expr,
2866                                      double val1,
2867                                      double val2,
2868                                      double abs_error) {
2869   const double diff = fabs(val1 - val2);
2870   if (diff <= abs_error) return AssertionSuccess();
2871 
2872   // FIXME: do not print the value of an expression if it's
2873   // already a literal.
2874   return AssertionFailure()
2875       << "The difference between " << expr1 << " and " << expr2
2876       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2877       << expr1 << " evaluates to " << val1 << ",\n"
2878       << expr2 << " evaluates to " << val2 << ", and\n"
2879       << abs_error_expr << " evaluates to " << abs_error << ".";
2880 }
2881 
2882 
2883 // Helper template for implementing FloatLE() and DoubleLE().
2884 template <typename RawType>
FloatingPointLE(const char * expr1,const char * expr2,RawType val1,RawType val2)2885 AssertionResult FloatingPointLE(const char* expr1,
2886                                 const char* expr2,
2887                                 RawType val1,
2888                                 RawType val2) {
2889   // Returns success if val1 is less than val2,
2890   if (val1 < val2) {
2891     return AssertionSuccess();
2892   }
2893 
2894   // or if val1 is almost equal to val2.
2895   const FloatingPoint<RawType> lhs(val1), rhs(val2);
2896   if (lhs.AlmostEquals(rhs)) {
2897     return AssertionSuccess();
2898   }
2899 
2900   // Note that the above two checks will both fail if either val1 or
2901   // val2 is NaN, as the IEEE floating-point standard requires that
2902   // any predicate involving a NaN must return false.
2903 
2904   ::std::stringstream val1_ss;
2905   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2906           << val1;
2907 
2908   ::std::stringstream val2_ss;
2909   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2910           << val2;
2911 
2912   return AssertionFailure()
2913       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2914       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
2915       << StringStreamToString(&val2_ss);
2916 }
2917 
2918 }  // namespace internal
2919 
2920 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2921 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
FloatLE(const char * expr1,const char * expr2,float val1,float val2)2922 AssertionResult FloatLE(const char* expr1, const char* expr2,
2923                         float val1, float val2) {
2924   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2925 }
2926 
2927 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2928 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
DoubleLE(const char * expr1,const char * expr2,double val1,double val2)2929 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2930                          double val1, double val2) {
2931   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2932 }
2933 
2934 namespace internal {
2935 
2936 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2937 // arguments.
CmpHelperEQ(const char * lhs_expression,const char * rhs_expression,BiggestInt lhs,BiggestInt rhs)2938 AssertionResult CmpHelperEQ(const char* lhs_expression,
2939                             const char* rhs_expression,
2940                             BiggestInt lhs,
2941                             BiggestInt rhs) {
2942   if (lhs == rhs) {
2943     return AssertionSuccess();
2944   }
2945 
2946   return EqFailure(lhs_expression,
2947                    rhs_expression,
2948                    FormatForComparisonFailureMessage(lhs, rhs),
2949                    FormatForComparisonFailureMessage(rhs, lhs),
2950                    false);
2951 }
2952 
2953 // A macro for implementing the helper functions needed to implement
2954 // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
2955 // just to avoid copy-and-paste of similar code.
2956 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2957 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2958                                    BiggestInt val1, BiggestInt val2) {\
2959   if (val1 op val2) {\
2960     return AssertionSuccess();\
2961   } else {\
2962     return AssertionFailure() \
2963         << "Expected: (" << expr1 << ") " #op " (" << expr2\
2964         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2965         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2966   }\
2967 }
2968 
2969 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2970 // enum arguments.
2971 GTEST_IMPL_CMP_HELPER_(NE, !=)
2972 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2973 // enum arguments.
2974 GTEST_IMPL_CMP_HELPER_(LE, <=)
2975 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2976 // enum arguments.
2977 GTEST_IMPL_CMP_HELPER_(LT, < )
2978 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2979 // enum arguments.
2980 GTEST_IMPL_CMP_HELPER_(GE, >=)
2981 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2982 // enum arguments.
2983 GTEST_IMPL_CMP_HELPER_(GT, > )
2984 
2985 #undef GTEST_IMPL_CMP_HELPER_
2986 
2987 // The helper function for {ASSERT|EXPECT}_STREQ.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)2988 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2989                                const char* rhs_expression,
2990                                const char* lhs,
2991                                const char* rhs) {
2992   if (String::CStringEquals(lhs, rhs)) {
2993     return AssertionSuccess();
2994   }
2995 
2996   return EqFailure(lhs_expression,
2997                    rhs_expression,
2998                    PrintToString(lhs),
2999                    PrintToString(rhs),
3000                    false);
3001 }
3002 
3003 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)3004 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
3005                                    const char* rhs_expression,
3006                                    const char* lhs,
3007                                    const char* rhs) {
3008   if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
3009     return AssertionSuccess();
3010   }
3011 
3012   return EqFailure(lhs_expression,
3013                    rhs_expression,
3014                    PrintToString(lhs),
3015                    PrintToString(rhs),
3016                    true);
3017 }
3018 
3019 // The helper function for {ASSERT|EXPECT}_STRNE.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)3020 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3021                                const char* s2_expression,
3022                                const char* s1,
3023                                const char* s2) {
3024   if (!String::CStringEquals(s1, s2)) {
3025     return AssertionSuccess();
3026   } else {
3027     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3028                               << s2_expression << "), actual: \""
3029                               << s1 << "\" vs \"" << s2 << "\"";
3030   }
3031 }
3032 
3033 // The helper function for {ASSERT|EXPECT}_STRCASENE.
CmpHelperSTRCASENE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)3034 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
3035                                    const char* s2_expression,
3036                                    const char* s1,
3037                                    const char* s2) {
3038   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3039     return AssertionSuccess();
3040   } else {
3041     return AssertionFailure()
3042         << "Expected: (" << s1_expression << ") != ("
3043         << s2_expression << ") (ignoring case), actual: \""
3044         << s1 << "\" vs \"" << s2 << "\"";
3045   }
3046 }
3047 
3048 }  // namespace internal
3049 
3050 namespace {
3051 
3052 // Helper functions for implementing IsSubString() and IsNotSubstring().
3053 
3054 // This group of overloaded functions return true iff needle is a
3055 // substring of haystack.  NULL is considered a substring of itself
3056 // only.
3057 
IsSubstringPred(const char * needle,const char * haystack)3058 bool IsSubstringPred(const char* needle, const char* haystack) {
3059   if (needle == NULL || haystack == NULL)
3060     return needle == haystack;
3061 
3062   return strstr(haystack, needle) != NULL;
3063 }
3064 
IsSubstringPred(const wchar_t * needle,const wchar_t * haystack)3065 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3066   if (needle == NULL || haystack == NULL)
3067     return needle == haystack;
3068 
3069   return wcsstr(haystack, needle) != NULL;
3070 }
3071 
3072 // StringType here can be either ::std::string or ::std::wstring.
3073 template <typename StringType>
IsSubstringPred(const StringType & needle,const StringType & haystack)3074 bool IsSubstringPred(const StringType& needle,
3075                      const StringType& haystack) {
3076   return haystack.find(needle) != StringType::npos;
3077 }
3078 
3079 // This function implements either IsSubstring() or IsNotSubstring(),
3080 // depending on the value of the expected_to_be_substring parameter.
3081 // StringType here can be const char*, const wchar_t*, ::std::string,
3082 // or ::std::wstring.
3083 template <typename StringType>
IsSubstringImpl(bool expected_to_be_substring,const char * needle_expr,const char * haystack_expr,const StringType & needle,const StringType & haystack)3084 AssertionResult IsSubstringImpl(
3085     bool expected_to_be_substring,
3086     const char* needle_expr, const char* haystack_expr,
3087     const StringType& needle, const StringType& haystack) {
3088   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3089     return AssertionSuccess();
3090 
3091   const bool is_wide_string = sizeof(needle[0]) > 1;
3092   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3093   return AssertionFailure()
3094       << "Value of: " << needle_expr << "\n"
3095       << "  Actual: " << begin_string_quote << needle << "\"\n"
3096       << "Expected: " << (expected_to_be_substring ? "" : "not ")
3097       << "a substring of " << haystack_expr << "\n"
3098       << "Which is: " << begin_string_quote << haystack << "\"";
3099 }
3100 
3101 }  // namespace
3102 
3103 // IsSubstring() and IsNotSubstring() check whether needle is a
3104 // substring of haystack (NULL is considered a substring of itself
3105 // only), and return an appropriate error message when they fail.
3106 
IsSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3107 AssertionResult IsSubstring(
3108     const char* needle_expr, const char* haystack_expr,
3109     const char* needle, const char* haystack) {
3110   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3111 }
3112 
IsSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3113 AssertionResult IsSubstring(
3114     const char* needle_expr, const char* haystack_expr,
3115     const wchar_t* needle, const wchar_t* haystack) {
3116   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3117 }
3118 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3119 AssertionResult IsNotSubstring(
3120     const char* needle_expr, const char* haystack_expr,
3121     const char* needle, const char* haystack) {
3122   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3123 }
3124 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3125 AssertionResult IsNotSubstring(
3126     const char* needle_expr, const char* haystack_expr,
3127     const wchar_t* needle, const wchar_t* haystack) {
3128   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3129 }
3130 
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3131 AssertionResult IsSubstring(
3132     const char* needle_expr, const char* haystack_expr,
3133     const ::std::string& needle, const ::std::string& haystack) {
3134   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3135 }
3136 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3137 AssertionResult IsNotSubstring(
3138     const char* needle_expr, const char* haystack_expr,
3139     const ::std::string& needle, const ::std::string& haystack) {
3140   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3141 }
3142 
3143 #if GTEST_HAS_STD_WSTRING
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3144 AssertionResult IsSubstring(
3145     const char* needle_expr, const char* haystack_expr,
3146     const ::std::wstring& needle, const ::std::wstring& haystack) {
3147   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3148 }
3149 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3150 AssertionResult IsNotSubstring(
3151     const char* needle_expr, const char* haystack_expr,
3152     const ::std::wstring& needle, const ::std::wstring& haystack) {
3153   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3154 }
3155 #endif  // GTEST_HAS_STD_WSTRING
3156 
3157 namespace internal {
3158 
3159 #if GTEST_OS_WINDOWS
3160 
3161 namespace {
3162 
3163 // Helper function for IsHRESULT{SuccessFailure} predicates
HRESULTFailureHelper(const char * expr,const char * expected,long hr)3164 AssertionResult HRESULTFailureHelper(const char* expr,
3165                                      const char* expected,
3166                                      long hr) {  // NOLINT
3167 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
3168 
3169   // Windows CE doesn't support FormatMessage.
3170   const char error_text[] = "";
3171 
3172 # else
3173 
3174   // Looks up the human-readable system message for the HRESULT code
3175   // and since we're not passing any params to FormatMessage, we don't
3176   // want inserts expanded.
3177   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3178                        FORMAT_MESSAGE_IGNORE_INSERTS;
3179   const DWORD kBufSize = 4096;
3180   // Gets the system's human readable message string for this HRESULT.
3181   char error_text[kBufSize] = { '\0' };
3182   DWORD message_length = ::FormatMessageA(kFlags,
3183                                           0,  // no source, we're asking system
3184                                           hr,  // the error
3185                                           0,  // no line width restrictions
3186                                           error_text,  // output buffer
3187                                           kBufSize,  // buf size
3188                                           NULL);  // no arguments for inserts
3189   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3190   for (; message_length && IsSpace(error_text[message_length - 1]);
3191           --message_length) {
3192     error_text[message_length - 1] = '\0';
3193   }
3194 
3195 # endif  // GTEST_OS_WINDOWS_MOBILE
3196 
3197   const std::string error_hex("0x" + String::FormatHexInt(hr));
3198   return ::testing::AssertionFailure()
3199       << "Expected: " << expr << " " << expected << ".\n"
3200       << "  Actual: " << error_hex << " " << error_text << "\n";
3201 }
3202 
3203 }  // namespace
3204 
IsHRESULTSuccess(const char * expr,long hr)3205 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
3206   if (SUCCEEDED(hr)) {
3207     return AssertionSuccess();
3208   }
3209   return HRESULTFailureHelper(expr, "succeeds", hr);
3210 }
3211 
IsHRESULTFailure(const char * expr,long hr)3212 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
3213   if (FAILED(hr)) {
3214     return AssertionSuccess();
3215   }
3216   return HRESULTFailureHelper(expr, "fails", hr);
3217 }
3218 
3219 #endif  // GTEST_OS_WINDOWS
3220 
3221 // Utility functions for encoding Unicode text (wide strings) in
3222 // UTF-8.
3223 
3224 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
3225 // like this:
3226 //
3227 // Code-point length   Encoding
3228 //   0 -  7 bits       0xxxxxxx
3229 //   8 - 11 bits       110xxxxx 10xxxxxx
3230 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
3231 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3232 
3233 // The maximum code-point a one-byte UTF-8 sequence can represent.
3234 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
3235 
3236 // The maximum code-point a two-byte UTF-8 sequence can represent.
3237 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
3238 
3239 // The maximum code-point a three-byte UTF-8 sequence can represent.
3240 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3241 
3242 // The maximum code-point a four-byte UTF-8 sequence can represent.
3243 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3244 
3245 // Chops off the n lowest bits from a bit pattern.  Returns the n
3246 // lowest bits.  As a side effect, the original bit pattern will be
3247 // shifted to the right by n bits.
ChopLowBits(UInt32 * bits,int n)3248 inline UInt32 ChopLowBits(UInt32* bits, int n) {
3249   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
3250   *bits >>= n;
3251   return low_bits;
3252 }
3253 
3254 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
3255 // code_point parameter is of type UInt32 because wchar_t may not be
3256 // wide enough to contain a code point.
3257 // If the code_point is not a valid Unicode code point
3258 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3259 // to "(Invalid Unicode 0xXXXXXXXX)".
CodePointToUtf8(UInt32 code_point)3260 std::string CodePointToUtf8(UInt32 code_point) {
3261   if (code_point > kMaxCodePoint4) {
3262     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
3263   }
3264 
3265   char str[5];  // Big enough for the largest valid code point.
3266   if (code_point <= kMaxCodePoint1) {
3267     str[1] = '\0';
3268     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
3269   } else if (code_point <= kMaxCodePoint2) {
3270     str[2] = '\0';
3271     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3272     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
3273   } else if (code_point <= kMaxCodePoint3) {
3274     str[3] = '\0';
3275     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3276     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3277     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
3278   } else {  // code_point <= kMaxCodePoint4
3279     str[4] = '\0';
3280     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3281     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3282     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3283     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
3284   }
3285   return str;
3286 }
3287 
3288 // The following two functions only make sense if the system
3289 // uses UTF-16 for wide string encoding. All supported systems
3290 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
3291 
3292 // Determines if the arguments constitute UTF-16 surrogate pair
3293 // and thus should be combined into a single Unicode code point
3294 // using CreateCodePointFromUtf16SurrogatePair.
IsUtf16SurrogatePair(wchar_t first,wchar_t second)3295 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3296   return sizeof(wchar_t) == 2 &&
3297       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3298 }
3299 
3300 // Creates a Unicode code point from UTF16 surrogate pair.
CreateCodePointFromUtf16SurrogatePair(wchar_t first,wchar_t second)3301 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3302                                                     wchar_t second) {
3303   const UInt32 mask = (1 << 10) - 1;
3304   return (sizeof(wchar_t) == 2) ?
3305       (((first & mask) << 10) | (second & mask)) + 0x10000 :
3306       // This function should not be called when the condition is
3307       // false, but we provide a sensible default in case it is.
3308       static_cast<UInt32>(first);
3309 }
3310 
3311 // Converts a wide string to a narrow string in UTF-8 encoding.
3312 // The wide string is assumed to have the following encoding:
3313 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
3314 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3315 // Parameter str points to a null-terminated wide string.
3316 // Parameter num_chars may additionally limit the number
3317 // of wchar_t characters processed. -1 is used when the entire string
3318 // should be processed.
3319 // If the string contains code points that are not valid Unicode code points
3320 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3321 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3322 // and contains invalid UTF-16 surrogate pairs, values in those pairs
3323 // will be encoded as individual Unicode characters from Basic Normal Plane.
WideStringToUtf8(const wchar_t * str,int num_chars)3324 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3325   if (num_chars == -1)
3326     num_chars = static_cast<int>(wcslen(str));
3327 
3328   ::std::stringstream stream;
3329   for (int i = 0; i < num_chars; ++i) {
3330     UInt32 unicode_code_point;
3331 
3332     if (str[i] == L'\0') {
3333       break;
3334     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3335       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3336                                                                  str[i + 1]);
3337       i++;
3338     } else {
3339       unicode_code_point = static_cast<UInt32>(str[i]);
3340     }
3341 
3342     stream << CodePointToUtf8(unicode_code_point);
3343   }
3344   return StringStreamToString(&stream);
3345 }
3346 
3347 // Converts a wide C string to an std::string using the UTF-8 encoding.
3348 // NULL will be converted to "(null)".
ShowWideCString(const wchar_t * wide_c_str)3349 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3350   if (wide_c_str == NULL)  return "(null)";
3351 
3352   return internal::WideStringToUtf8(wide_c_str, -1);
3353 }
3354 
3355 // Compares two wide C strings.  Returns true iff they have the same
3356 // content.
3357 //
3358 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
3359 // C string is considered different to any non-NULL C string,
3360 // including the empty string.
WideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3361 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3362   if (lhs == NULL) return rhs == NULL;
3363 
3364   if (rhs == NULL) return false;
3365 
3366   return wcscmp(lhs, rhs) == 0;
3367 }
3368 
3369 // Helper function for *_STREQ on wide strings.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const wchar_t * lhs,const wchar_t * rhs)3370 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3371                                const char* rhs_expression,
3372                                const wchar_t* lhs,
3373                                const wchar_t* rhs) {
3374   if (String::WideCStringEquals(lhs, rhs)) {
3375     return AssertionSuccess();
3376   }
3377 
3378   return EqFailure(lhs_expression,
3379                    rhs_expression,
3380                    PrintToString(lhs),
3381                    PrintToString(rhs),
3382                    false);
3383 }
3384 
3385 // Helper function for *_STRNE on wide strings.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const wchar_t * s1,const wchar_t * s2)3386 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3387                                const char* s2_expression,
3388                                const wchar_t* s1,
3389                                const wchar_t* s2) {
3390   if (!String::WideCStringEquals(s1, s2)) {
3391     return AssertionSuccess();
3392   }
3393 
3394   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3395                             << s2_expression << "), actual: "
3396                             << PrintToString(s1)
3397                             << " vs " << PrintToString(s2);
3398 }
3399 
3400 // Compares two C strings, ignoring case.  Returns true iff they have
3401 // the same content.
3402 //
3403 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
3404 // NULL C string is considered different to any non-NULL C string,
3405 // including the empty string.
CaseInsensitiveCStringEquals(const char * lhs,const char * rhs)3406 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3407   if (lhs == NULL)
3408     return rhs == NULL;
3409   if (rhs == NULL)
3410     return false;
3411   return posix::StrCaseCmp(lhs, rhs) == 0;
3412 }
3413 
3414   // Compares two wide C strings, ignoring case.  Returns true iff they
3415   // have the same content.
3416   //
3417   // Unlike wcscasecmp(), this function can handle NULL argument(s).
3418   // A NULL C string is considered different to any non-NULL wide C string,
3419   // including the empty string.
3420   // NB: The implementations on different platforms slightly differ.
3421   // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3422   // environment variable. On GNU platform this method uses wcscasecmp
3423   // which compares according to LC_CTYPE category of the current locale.
3424   // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3425   // current locale.
CaseInsensitiveWideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3426 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3427                                               const wchar_t* rhs) {
3428   if (lhs == NULL) return rhs == NULL;
3429 
3430   if (rhs == NULL) return false;
3431 
3432 #if GTEST_OS_WINDOWS
3433   return _wcsicmp(lhs, rhs) == 0;
3434 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3435   return wcscasecmp(lhs, rhs) == 0;
3436 #else
3437   // Android, Mac OS X and Cygwin don't define wcscasecmp.
3438   // Other unknown OSes may not define it either.
3439   wint_t left, right;
3440   do {
3441     left = towlower(*lhs++);
3442     right = towlower(*rhs++);
3443   } while (left && left == right);
3444   return left == right;
3445 #endif  // OS selector
3446 }
3447 
3448 // Returns true iff str ends with the given suffix, ignoring case.
3449 // Any string is considered to end with an empty suffix.
EndsWithCaseInsensitive(const std::string & str,const std::string & suffix)3450 bool String::EndsWithCaseInsensitive(
3451     const std::string& str, const std::string& suffix) {
3452   const size_t str_len = str.length();
3453   const size_t suffix_len = suffix.length();
3454   return (str_len >= suffix_len) &&
3455          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3456                                       suffix.c_str());
3457 }
3458 
3459 // Formats an int value as "%02d".
FormatIntWidth2(int value)3460 std::string String::FormatIntWidth2(int value) {
3461   std::stringstream ss;
3462   ss << std::setfill('0') << std::setw(2) << value;
3463   return ss.str();
3464 }
3465 
3466 // Formats an int value as "%X".
FormatHexInt(int value)3467 std::string String::FormatHexInt(int value) {
3468   std::stringstream ss;
3469   ss << std::hex << std::uppercase << value;
3470   return ss.str();
3471 }
3472 
3473 // Formats a byte as "%02X".
FormatByte(unsigned char value)3474 std::string String::FormatByte(unsigned char value) {
3475   std::stringstream ss;
3476   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3477      << static_cast<unsigned int>(value);
3478   return ss.str();
3479 }
3480 
3481 // Converts the buffer in a stringstream to an std::string, converting NUL
3482 // bytes to "\\0" along the way.
StringStreamToString(::std::stringstream * ss)3483 std::string StringStreamToString(::std::stringstream* ss) {
3484   const ::std::string& str = ss->str();
3485   const char* const start = str.c_str();
3486   const char* const end = start + str.length();
3487 
3488   std::string result;
3489   result.reserve(2 * (end - start));
3490   for (const char* ch = start; ch != end; ++ch) {
3491     if (*ch == '\0') {
3492       result += "\\0";  // Replaces NUL with "\\0";
3493     } else {
3494       result += *ch;
3495     }
3496   }
3497 
3498   return result;
3499 }
3500 
3501 // Appends the user-supplied message to the Google-Test-generated message.
AppendUserMessage(const std::string & gtest_msg,const Message & user_msg)3502 std::string AppendUserMessage(const std::string& gtest_msg,
3503                               const Message& user_msg) {
3504   // Appends the user message if it's non-empty.
3505   const std::string user_msg_string = user_msg.GetString();
3506   if (user_msg_string.empty()) {
3507     return gtest_msg;
3508   }
3509 
3510   return gtest_msg + "\n" + user_msg_string;
3511 }
3512 
3513 }  // namespace internal
3514 
3515 // class TestResult
3516 
3517 // Creates an empty TestResult.
TestResult()3518 TestResult::TestResult()
3519     : death_test_count_(0),
3520       elapsed_time_(0) {
3521 }
3522 
3523 // D'tor.
~TestResult()3524 TestResult::~TestResult() {
3525 }
3526 
3527 // Returns the i-th test part result among all the results. i can
3528 // range from 0 to total_part_count() - 1. If i is not in that range,
3529 // aborts the program.
GetTestPartResult(int i) const3530 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3531   if (i < 0 || i >= total_part_count())
3532     internal::posix::Abort();
3533   return test_part_results_.at(i);
3534 }
3535 
3536 // Returns the i-th test property. i can range from 0 to
3537 // test_property_count() - 1. If i is not in that range, aborts the
3538 // program.
GetTestProperty(int i) const3539 const TestProperty& TestResult::GetTestProperty(int i) const {
3540   if (i < 0 || i >= test_property_count())
3541     internal::posix::Abort();
3542   return test_properties_.at(i);
3543 }
3544 
3545 // Clears the test part results.
ClearTestPartResults()3546 void TestResult::ClearTestPartResults() {
3547   test_part_results_.clear();
3548 }
3549 
3550 // Adds a test part result to the list.
AddTestPartResult(const TestPartResult & test_part_result)3551 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3552   test_part_results_.push_back(test_part_result);
3553 }
3554 
3555 // Adds a test property to the list. If a property with the same key as the
3556 // supplied property is already represented, the value of this test_property
3557 // replaces the old value for that key.
RecordProperty(const std::string & xml_element,const TestProperty & test_property)3558 void TestResult::RecordProperty(const std::string& xml_element,
3559                                 const TestProperty& test_property) {
3560   if (!ValidateTestProperty(xml_element, test_property)) {
3561     return;
3562   }
3563   internal::MutexLock lock(&test_properites_mutex_);
3564   const std::vector<TestProperty>::iterator property_with_matching_key =
3565       std::find_if(test_properties_.begin(), test_properties_.end(),
3566                    internal::TestPropertyKeyIs(test_property.key()));
3567   if (property_with_matching_key == test_properties_.end()) {
3568     test_properties_.push_back(test_property);
3569     return;
3570   }
3571   property_with_matching_key->SetValue(test_property.value());
3572 }
3573 
3574 // The list of reserved attributes used in the <testsuites> element of XML
3575 // output.
3576 static const char* const kReservedTestSuitesAttributes[] = {
3577   "disabled",
3578   "errors",
3579   "failures",
3580   "name",
3581   "random_seed",
3582   "tests",
3583   "time",
3584   "timestamp"
3585 };
3586 
3587 // The list of reserved attributes used in the <testsuite> element of XML
3588 // output.
3589 static const char* const kReservedTestSuiteAttributes[] = {
3590   "disabled",
3591   "errors",
3592   "failures",
3593   "name",
3594   "tests",
3595   "time"
3596 };
3597 
3598 // The list of reserved attributes used in the <testcase> element of XML output.
3599 static const char* const kReservedTestCaseAttributes[] = {
3600     "classname",  "name",        "status", "time",
3601     "type_param", "value_param", "file",   "line"};
3602 
3603 template <int kSize>
ArrayAsVector(const char * const (& array)[kSize])3604 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3605   return std::vector<std::string>(array, array + kSize);
3606 }
3607 
GetReservedAttributesForElement(const std::string & xml_element)3608 static std::vector<std::string> GetReservedAttributesForElement(
3609     const std::string& xml_element) {
3610   if (xml_element == "testsuites") {
3611     return ArrayAsVector(kReservedTestSuitesAttributes);
3612   } else if (xml_element == "testsuite") {
3613     return ArrayAsVector(kReservedTestSuiteAttributes);
3614   } else if (xml_element == "testcase") {
3615     return ArrayAsVector(kReservedTestCaseAttributes);
3616   } else {
3617     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3618   }
3619   // This code is unreachable but some compilers may not realizes that.
3620   return std::vector<std::string>();
3621 }
3622 
FormatWordList(const std::vector<std::string> & words)3623 static std::string FormatWordList(const std::vector<std::string>& words) {
3624   Message word_list;
3625   for (size_t i = 0; i < words.size(); ++i) {
3626     if (i > 0 && words.size() > 2) {
3627       word_list << ", ";
3628     }
3629     if (i == words.size() - 1) {
3630       word_list << "and ";
3631     }
3632     word_list << "'" << words[i] << "'";
3633   }
3634   return word_list.GetString();
3635 }
3636 
ValidateTestPropertyName(const std::string & property_name,const std::vector<std::string> & reserved_names)3637 static bool ValidateTestPropertyName(
3638     const std::string& property_name,
3639     const std::vector<std::string>& reserved_names) {
3640   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3641           reserved_names.end()) {
3642     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3643                   << " (" << FormatWordList(reserved_names)
3644                   << " are reserved by " << GTEST_NAME_ << ")";
3645     return false;
3646   }
3647   return true;
3648 }
3649 
3650 // Adds a failure if the key is a reserved attribute of the element named
3651 // xml_element.  Returns true if the property is valid.
ValidateTestProperty(const std::string & xml_element,const TestProperty & test_property)3652 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3653                                       const TestProperty& test_property) {
3654   return ValidateTestPropertyName(test_property.key(),
3655                                   GetReservedAttributesForElement(xml_element));
3656 }
3657 
3658 // Clears the object.
Clear()3659 void TestResult::Clear() {
3660   test_part_results_.clear();
3661   test_properties_.clear();
3662   death_test_count_ = 0;
3663   elapsed_time_ = 0;
3664 }
3665 
3666 // Returns true iff the test failed.
Failed() const3667 bool TestResult::Failed() const {
3668   for (int i = 0; i < total_part_count(); ++i) {
3669     if (GetTestPartResult(i).failed())
3670       return true;
3671   }
3672   return false;
3673 }
3674 
3675 // Returns true iff the test part fatally failed.
TestPartFatallyFailed(const TestPartResult & result)3676 static bool TestPartFatallyFailed(const TestPartResult& result) {
3677   return result.fatally_failed();
3678 }
3679 
3680 // Returns true iff the test fatally failed.
HasFatalFailure() const3681 bool TestResult::HasFatalFailure() const {
3682   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3683 }
3684 
3685 // Returns true iff the test part non-fatally failed.
TestPartNonfatallyFailed(const TestPartResult & result)3686 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3687   return result.nonfatally_failed();
3688 }
3689 
3690 // Returns true iff the test has a non-fatal failure.
HasNonfatalFailure() const3691 bool TestResult::HasNonfatalFailure() const {
3692   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3693 }
3694 
3695 // Gets the number of all test parts.  This is the sum of the number
3696 // of successful test parts and the number of failed test parts.
total_part_count() const3697 int TestResult::total_part_count() const {
3698   return static_cast<int>(test_part_results_.size());
3699 }
3700 
3701 // Returns the number of the test properties.
test_property_count() const3702 int TestResult::test_property_count() const {
3703   return static_cast<int>(test_properties_.size());
3704 }
3705 
3706 // class Test
3707 
3708 // Creates a Test object.
3709 
3710 // The c'tor saves the states of all flags.
Test()3711 Test::Test()
3712     : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3713 }
3714 
3715 // The d'tor restores the states of all flags.  The actual work is
3716 // done by the d'tor of the gtest_flag_saver_ field, and thus not
3717 // visible here.
~Test()3718 Test::~Test() {
3719 }
3720 
3721 // Sets up the test fixture.
3722 //
3723 // A sub-class may override this.
SetUp()3724 void Test::SetUp() {
3725 }
3726 
3727 // Tears down the test fixture.
3728 //
3729 // A sub-class may override this.
TearDown()3730 void Test::TearDown() {
3731 }
3732 
3733 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,const std::string & value)3734 void Test::RecordProperty(const std::string& key, const std::string& value) {
3735   UnitTest::GetInstance()->RecordProperty(key, value);
3736 }
3737 
3738 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,int value)3739 void Test::RecordProperty(const std::string& key, int value) {
3740   Message value_message;
3741   value_message << value;
3742   RecordProperty(key, value_message.GetString().c_str());
3743 }
3744 
3745 namespace internal {
3746 
ReportFailureInUnknownLocation(TestPartResult::Type result_type,const std::string & message)3747 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3748                                     const std::string& message) {
3749   // This function is a friend of UnitTest and as such has access to
3750   // AddTestPartResult.
3751   UnitTest::GetInstance()->AddTestPartResult(
3752       result_type,
3753       NULL,  // No info about the source file where the exception occurred.
3754       -1,    // We have no info on which line caused the exception.
3755       message,
3756       "");   // No stack trace, either.
3757 }
3758 
3759 }  // namespace internal
3760 
3761 // Google Test requires all tests in the same test case to use the same test
3762 // fixture class.  This function checks if the current test has the
3763 // same fixture class as the first test in the current test case.  If
3764 // yes, it returns true; otherwise it generates a Google Test failure and
3765 // returns false.
HasSameFixtureClass()3766 bool Test::HasSameFixtureClass() {
3767   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3768   const TestCase* const test_case = impl->current_test_case();
3769 
3770   // Info about the first test in the current test case.
3771   const TestInfo* const first_test_info = test_case->test_info_list()[0];
3772   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3773   const char* const first_test_name = first_test_info->name();
3774 
3775   // Info about the current test.
3776   const TestInfo* const this_test_info = impl->current_test_info();
3777   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3778   const char* const this_test_name = this_test_info->name();
3779 
3780   if (this_fixture_id != first_fixture_id) {
3781     // Is the first test defined using TEST?
3782     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3783     // Is this test defined using TEST?
3784     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3785 
3786     if (first_is_TEST || this_is_TEST) {
3787       // Both TEST and TEST_F appear in same test case, which is incorrect.
3788       // Tell the user how to fix this.
3789 
3790       // Gets the name of the TEST and the name of the TEST_F.  Note
3791       // that first_is_TEST and this_is_TEST cannot both be true, as
3792       // the fixture IDs are different for the two tests.
3793       const char* const TEST_name =
3794           first_is_TEST ? first_test_name : this_test_name;
3795       const char* const TEST_F_name =
3796           first_is_TEST ? this_test_name : first_test_name;
3797 
3798       ADD_FAILURE()
3799           << "All tests in the same test case must use the same test fixture\n"
3800           << "class, so mixing TEST_F and TEST in the same test case is\n"
3801           << "illegal.  In test case " << this_test_info->test_case_name()
3802           << ",\n"
3803           << "test " << TEST_F_name << " is defined using TEST_F but\n"
3804           << "test " << TEST_name << " is defined using TEST.  You probably\n"
3805           << "want to change the TEST to TEST_F or move it to another test\n"
3806           << "case.";
3807     } else {
3808       // Two fixture classes with the same name appear in two different
3809       // namespaces, which is not allowed. Tell the user how to fix this.
3810       ADD_FAILURE()
3811           << "All tests in the same test case must use the same test fixture\n"
3812           << "class.  However, in test case "
3813           << this_test_info->test_case_name() << ",\n"
3814           << "you defined test " << first_test_name
3815           << " and test " << this_test_name << "\n"
3816           << "using two different test fixture classes.  This can happen if\n"
3817           << "the two classes are from different namespaces or translation\n"
3818           << "units and have the same name.  You should probably rename one\n"
3819           << "of the classes to put the tests into different test cases.";
3820     }
3821     return false;
3822   }
3823 
3824   return true;
3825 }
3826 
3827 #if GTEST_HAS_SEH
3828 
3829 // Adds an "exception thrown" fatal failure to the current test.  This
3830 // function returns its result via an output parameter pointer because VC++
3831 // prohibits creation of objects with destructors on stack in functions
3832 // using __try (see error C2712).
FormatSehExceptionMessage(DWORD exception_code,const char * location)3833 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3834                                               const char* location) {
3835   Message message;
3836   message << "SEH exception with code 0x" << std::setbase(16) <<
3837     exception_code << std::setbase(10) << " thrown in " << location << ".";
3838 
3839   return new std::string(message.GetString());
3840 }
3841 
3842 #endif  // GTEST_HAS_SEH
3843 
3844 namespace internal {
3845 
3846 #if GTEST_HAS_EXCEPTIONS
3847 
3848 // Adds an "exception thrown" fatal failure to the current test.
FormatCxxExceptionMessage(const char * description,const char * location)3849 static std::string FormatCxxExceptionMessage(const char* description,
3850                                              const char* location) {
3851   Message message;
3852   if (description != NULL) {
3853     message << "C++ exception with description \"" << description << "\"";
3854   } else {
3855     message << "Unknown C++ exception";
3856   }
3857   message << " thrown in " << location << ".";
3858 
3859   return message.GetString();
3860 }
3861 
3862 static std::string PrintTestPartResultToString(
3863     const TestPartResult& test_part_result);
3864 
GoogleTestFailureException(const TestPartResult & failure)3865 GoogleTestFailureException::GoogleTestFailureException(
3866     const TestPartResult& failure)
3867     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3868 
3869 #endif  // GTEST_HAS_EXCEPTIONS
3870 
3871 // We put these helper functions in the internal namespace as IBM's xlC
3872 // compiler rejects the code if they were declared static.
3873 
3874 // Runs the given method and handles SEH exceptions it throws, when
3875 // SEH is supported; returns the 0-value for type Result in case of an
3876 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
3877 // exceptions in the same function.  Therefore, we provide a separate
3878 // wrapper function for handling SEH exceptions.)
3879 template <class T, typename Result>
HandleSehExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3880 Result HandleSehExceptionsInMethodIfSupported(
3881     T* object, Result (T::*method)(), const char* location) {
3882 #if GTEST_HAS_SEH
3883   __try {
3884     return (object->*method)();
3885   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
3886       GetExceptionCode())) {
3887     // We create the exception message on the heap because VC++ prohibits
3888     // creation of objects with destructors on stack in functions using __try
3889     // (see error C2712).
3890     std::string* exception_message = FormatSehExceptionMessage(
3891         GetExceptionCode(), location);
3892     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3893                                              *exception_message);
3894     delete exception_message;
3895     return static_cast<Result>(0);
3896   }
3897 #else
3898   (void)location;
3899   return (object->*method)();
3900 #endif  // GTEST_HAS_SEH
3901 }
3902 
3903 // Runs the given method and catches and reports C++ and/or SEH-style
3904 // exceptions, if they are supported; returns the 0-value for type
3905 // Result in case of an SEH exception.
3906 template <class T, typename Result>
HandleExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3907 Result HandleExceptionsInMethodIfSupported(
3908     T* object, Result (T::*method)(), const char* location) {
3909   // NOTE: The user code can affect the way in which Google Test handles
3910   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3911   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3912   // after the exception is caught and either report or re-throw the
3913   // exception based on the flag's value:
3914   //
3915   // try {
3916   //   // Perform the test method.
3917   // } catch (...) {
3918   //   if (GTEST_FLAG(catch_exceptions))
3919   //     // Report the exception as failure.
3920   //   else
3921   //     throw;  // Re-throws the original exception.
3922   // }
3923   //
3924   // However, the purpose of this flag is to allow the program to drop into
3925   // the debugger when the exception is thrown. On most platforms, once the
3926   // control enters the catch block, the exception origin information is
3927   // lost and the debugger will stop the program at the point of the
3928   // re-throw in this function -- instead of at the point of the original
3929   // throw statement in the code under test.  For this reason, we perform
3930   // the check early, sacrificing the ability to affect Google Test's
3931   // exception handling in the method where the exception is thrown.
3932   if (internal::GetUnitTestImpl()->catch_exceptions()) {
3933 #if GTEST_HAS_EXCEPTIONS
3934     try {
3935       return HandleSehExceptionsInMethodIfSupported(object, method, location);
3936     } catch (const AssertionException&) {  // NOLINT
3937       // This failure was reported already.
3938     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
3939       // This exception type can only be thrown by a failed Google
3940       // Test assertion with the intention of letting another testing
3941       // framework catch it.  Therefore we just re-throw it.
3942       throw;
3943     } catch (const std::exception& e) {  // NOLINT
3944       internal::ReportFailureInUnknownLocation(
3945           TestPartResult::kFatalFailure,
3946           FormatCxxExceptionMessage(e.what(), location));
3947     } catch (...) {  // NOLINT
3948       internal::ReportFailureInUnknownLocation(
3949           TestPartResult::kFatalFailure,
3950           FormatCxxExceptionMessage(NULL, location));
3951     }
3952     return static_cast<Result>(0);
3953 #else
3954     return HandleSehExceptionsInMethodIfSupported(object, method, location);
3955 #endif  // GTEST_HAS_EXCEPTIONS
3956   } else {
3957     return (object->*method)();
3958   }
3959 }
3960 
3961 }  // namespace internal
3962 
3963 // Runs the test and updates the test result.
Run()3964 void Test::Run() {
3965   if (!HasSameFixtureClass()) return;
3966 
3967   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3968   impl->os_stack_trace_getter()->UponLeavingGTest();
3969   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3970   // We will run the test only if SetUp() was successful.
3971   if (!HasFatalFailure()) {
3972     impl->os_stack_trace_getter()->UponLeavingGTest();
3973     internal::HandleExceptionsInMethodIfSupported(
3974         this, &Test::TestBody, "the test body");
3975   }
3976 
3977   // However, we want to clean up as much as possible.  Hence we will
3978   // always call TearDown(), even if SetUp() or the test body has
3979   // failed.
3980   impl->os_stack_trace_getter()->UponLeavingGTest();
3981   internal::HandleExceptionsInMethodIfSupported(
3982       this, &Test::TearDown, "TearDown()");
3983 }
3984 
3985 // Returns true iff the current test has a fatal failure.
HasFatalFailure()3986 bool Test::HasFatalFailure() {
3987   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3988 }
3989 
3990 // Returns true iff the current test has a non-fatal failure.
HasNonfatalFailure()3991 bool Test::HasNonfatalFailure() {
3992   return internal::GetUnitTestImpl()->current_test_result()->
3993       HasNonfatalFailure();
3994 }
3995 
3996 // class TestInfo
3997 
3998 // Constructs a TestInfo object. It assumes ownership of the test factory
3999 // object.
TestInfo(const std::string & a_test_case_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)4000 TestInfo::TestInfo(const std::string& a_test_case_name,
4001                    const std::string& a_name,
4002                    const char* a_type_param,
4003                    const char* a_value_param,
4004                    internal::CodeLocation a_code_location,
4005                    internal::TypeId fixture_class_id,
4006                    internal::TestFactoryBase* factory)
4007     : test_case_name_(a_test_case_name),
4008       name_(a_name),
4009       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
4010       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
4011       location_(a_code_location),
4012       fixture_class_id_(fixture_class_id),
4013       should_run_(false),
4014       is_disabled_(false),
4015       matches_filter_(false),
4016       factory_(factory),
4017       result_() {}
4018 
4019 // Destructs a TestInfo object.
~TestInfo()4020 TestInfo::~TestInfo() { delete factory_; }
4021 
4022 namespace internal {
4023 
4024 // Creates a new TestInfo object and registers it with Google Test;
4025 // returns the created object.
4026 //
4027 // Arguments:
4028 //
4029 //   test_case_name:   name of the test case
4030 //   name:             name of the test
4031 //   type_param:       the name of the test's type parameter, or NULL if
4032 //                     this is not a typed or a type-parameterized test.
4033 //   value_param:      text representation of the test's value parameter,
4034 //                     or NULL if this is not a value-parameterized test.
4035 //   code_location:    code location where the test is defined
4036 //   fixture_class_id: ID of the test fixture class
4037 //   set_up_tc:        pointer to the function that sets up the test case
4038 //   tear_down_tc:     pointer to the function that tears down the test case
4039 //   factory:          pointer to the factory that creates a test object.
4040 //                     The newly created TestInfo instance will assume
4041 //                     ownership of the factory object.
MakeAndRegisterTestInfo(const char * test_case_name,const char * name,const char * type_param,const char * value_param,CodeLocation code_location,TypeId fixture_class_id,SetUpTestCaseFunc set_up_tc,TearDownTestCaseFunc tear_down_tc,TestFactoryBase * factory)4042 TestInfo* MakeAndRegisterTestInfo(
4043     const char* test_case_name,
4044     const char* name,
4045     const char* type_param,
4046     const char* value_param,
4047     CodeLocation code_location,
4048     TypeId fixture_class_id,
4049     SetUpTestCaseFunc set_up_tc,
4050     TearDownTestCaseFunc tear_down_tc,
4051     TestFactoryBase* factory) {
4052   TestInfo* const test_info =
4053       new TestInfo(test_case_name, name, type_param, value_param,
4054                    code_location, fixture_class_id, factory);
4055   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4056   return test_info;
4057 }
4058 
ReportInvalidTestCaseType(const char * test_case_name,CodeLocation code_location)4059 void ReportInvalidTestCaseType(const char* test_case_name,
4060                                CodeLocation code_location) {
4061   Message errors;
4062   errors
4063       << "Attempted redefinition of test case " << test_case_name << ".\n"
4064       << "All tests in the same test case must use the same test fixture\n"
4065       << "class.  However, in test case " << test_case_name << ", you tried\n"
4066       << "to define a test using a fixture class different from the one\n"
4067       << "used earlier. This can happen if the two fixture classes are\n"
4068       << "from different namespaces and have the same name. You should\n"
4069       << "probably rename one of the classes to put the tests into different\n"
4070       << "test cases.";
4071 
4072   GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
4073                                           code_location.line)
4074                     << " " << errors.GetString();
4075 }
4076 }  // namespace internal
4077 
4078 namespace {
4079 
4080 // A predicate that checks the test name of a TestInfo against a known
4081 // value.
4082 //
4083 // This is used for implementation of the TestCase class only.  We put
4084 // it in the anonymous namespace to prevent polluting the outer
4085 // namespace.
4086 //
4087 // TestNameIs is copyable.
4088 class TestNameIs {
4089  public:
4090   // Constructor.
4091   //
4092   // TestNameIs has NO default constructor.
TestNameIs(const char * name)4093   explicit TestNameIs(const char* name)
4094       : name_(name) {}
4095 
4096   // Returns true iff the test name of test_info matches name_.
operator ()(const TestInfo * test_info) const4097   bool operator()(const TestInfo * test_info) const {
4098     return test_info && test_info->name() == name_;
4099   }
4100 
4101  private:
4102   std::string name_;
4103 };
4104 
4105 }  // namespace
4106 
4107 namespace internal {
4108 
4109 // This method expands all parameterized tests registered with macros TEST_P
4110 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
4111 // This will be done just once during the program runtime.
RegisterParameterizedTests()4112 void UnitTestImpl::RegisterParameterizedTests() {
4113   if (!parameterized_tests_registered_) {
4114     parameterized_test_registry_.RegisterTests();
4115     parameterized_tests_registered_ = true;
4116   }
4117 }
4118 
4119 }  // namespace internal
4120 
4121 // Creates the test object, runs it, records its result, and then
4122 // deletes it.
Run()4123 void TestInfo::Run() {
4124   if (!should_run_) return;
4125 
4126   // Tells UnitTest where to store test result.
4127   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4128   impl->set_current_test_info(this);
4129 
4130   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4131 
4132   // Notifies the unit test event listeners that a test is about to start.
4133   repeater->OnTestStart(*this);
4134 
4135   const TimeInMillis start = internal::GetTimeInMillis();
4136 
4137   impl->os_stack_trace_getter()->UponLeavingGTest();
4138 
4139   // Creates the test object.
4140   Test* const test = internal::HandleExceptionsInMethodIfSupported(
4141       factory_, &internal::TestFactoryBase::CreateTest,
4142       "the test fixture's constructor");
4143 
4144   // Runs the test if the constructor didn't generate a fatal failure.
4145   // Note that the object will not be null
4146   if (!Test::HasFatalFailure()) {
4147     // This doesn't throw as all user code that can throw are wrapped into
4148     // exception handling code.
4149     test->Run();
4150   }
4151 
4152     // Deletes the test object.
4153     impl->os_stack_trace_getter()->UponLeavingGTest();
4154     internal::HandleExceptionsInMethodIfSupported(
4155         test, &Test::DeleteSelf_, "the test fixture's destructor");
4156 
4157   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4158 
4159   // Notifies the unit test event listener that a test has just finished.
4160   repeater->OnTestEnd(*this);
4161 
4162   // Tells UnitTest to stop associating assertion results to this
4163   // test.
4164   impl->set_current_test_info(NULL);
4165 }
4166 
4167 // class TestCase
4168 
4169 // Gets the number of successful tests in this test case.
successful_test_count() const4170 int TestCase::successful_test_count() const {
4171   return CountIf(test_info_list_, TestPassed);
4172 }
4173 
4174 // Gets the number of failed tests in this test case.
failed_test_count() const4175 int TestCase::failed_test_count() const {
4176   return CountIf(test_info_list_, TestFailed);
4177 }
4178 
4179 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const4180 int TestCase::reportable_disabled_test_count() const {
4181   return CountIf(test_info_list_, TestReportableDisabled);
4182 }
4183 
4184 // Gets the number of disabled tests in this test case.
disabled_test_count() const4185 int TestCase::disabled_test_count() const {
4186   return CountIf(test_info_list_, TestDisabled);
4187 }
4188 
4189 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const4190 int TestCase::reportable_test_count() const {
4191   return CountIf(test_info_list_, TestReportable);
4192 }
4193 
4194 // Get the number of tests in this test case that should run.
test_to_run_count() const4195 int TestCase::test_to_run_count() const {
4196   return CountIf(test_info_list_, ShouldRunTest);
4197 }
4198 
4199 // Gets the number of all tests.
total_test_count() const4200 int TestCase::total_test_count() const {
4201   return static_cast<int>(test_info_list_.size());
4202 }
4203 
4204 // Creates a TestCase with the given name.
4205 //
4206 // Arguments:
4207 //
4208 //   name:         name of the test case
4209 //   a_type_param: the name of the test case's type parameter, or NULL if
4210 //                 this is not a typed or a type-parameterized test case.
4211 //   set_up_tc:    pointer to the function that sets up the test case
4212 //   tear_down_tc: pointer to the function that tears down the test case
TestCase(const char * a_name,const char * a_type_param,Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc)4213 TestCase::TestCase(const char* a_name, const char* a_type_param,
4214                    Test::SetUpTestCaseFunc set_up_tc,
4215                    Test::TearDownTestCaseFunc tear_down_tc)
4216     : name_(a_name),
4217       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
4218       set_up_tc_(set_up_tc),
4219       tear_down_tc_(tear_down_tc),
4220       should_run_(false),
4221       elapsed_time_(0) {
4222 }
4223 
4224 // Destructor of TestCase.
~TestCase()4225 TestCase::~TestCase() {
4226   // Deletes every Test in the collection.
4227   ForEach(test_info_list_, internal::Delete<TestInfo>);
4228 }
4229 
4230 // Returns the i-th test among all the tests. i can range from 0 to
4231 // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const4232 const TestInfo* TestCase::GetTestInfo(int i) const {
4233   const int index = GetElementOr(test_indices_, i, -1);
4234   return index < 0 ? NULL : test_info_list_[index];
4235 }
4236 
4237 // Returns the i-th test among all the tests. i can range from 0 to
4238 // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)4239 TestInfo* TestCase::GetMutableTestInfo(int i) {
4240   const int index = GetElementOr(test_indices_, i, -1);
4241   return index < 0 ? NULL : test_info_list_[index];
4242 }
4243 
4244 // Adds a test to this test case.  Will delete the test upon
4245 // destruction of the TestCase object.
AddTestInfo(TestInfo * test_info)4246 void TestCase::AddTestInfo(TestInfo * test_info) {
4247   test_info_list_.push_back(test_info);
4248   test_indices_.push_back(static_cast<int>(test_indices_.size()));
4249 }
4250 
4251 // Runs every test in this TestCase.
Run()4252 void TestCase::Run() {
4253   if (!should_run_) return;
4254 
4255   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4256   impl->set_current_test_case(this);
4257 
4258   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4259 
4260   repeater->OnTestCaseStart(*this);
4261   impl->os_stack_trace_getter()->UponLeavingGTest();
4262   internal::HandleExceptionsInMethodIfSupported(
4263       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
4264 
4265   const internal::TimeInMillis start = internal::GetTimeInMillis();
4266   for (int i = 0; i < total_test_count(); i++) {
4267     GetMutableTestInfo(i)->Run();
4268   }
4269   elapsed_time_ = internal::GetTimeInMillis() - start;
4270 
4271   impl->os_stack_trace_getter()->UponLeavingGTest();
4272   internal::HandleExceptionsInMethodIfSupported(
4273       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
4274 
4275   repeater->OnTestCaseEnd(*this);
4276   impl->set_current_test_case(NULL);
4277 }
4278 
4279 // Clears the results of all tests in this test case.
ClearResult()4280 void TestCase::ClearResult() {
4281   ad_hoc_test_result_.Clear();
4282   ForEach(test_info_list_, TestInfo::ClearTestResult);
4283 }
4284 
4285 // Shuffles the tests in this test case.
ShuffleTests(internal::Random * random)4286 void TestCase::ShuffleTests(internal::Random* random) {
4287   Shuffle(random, &test_indices_);
4288 }
4289 
4290 // Restores the test order to before the first shuffle.
UnshuffleTests()4291 void TestCase::UnshuffleTests() {
4292   for (size_t i = 0; i < test_indices_.size(); i++) {
4293     test_indices_[i] = static_cast<int>(i);
4294   }
4295 }
4296 
4297 // Formats a countable noun.  Depending on its quantity, either the
4298 // singular form or the plural form is used. e.g.
4299 //
4300 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4301 // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)4302 static std::string FormatCountableNoun(int count,
4303                                        const char * singular_form,
4304                                        const char * plural_form) {
4305   return internal::StreamableToString(count) + " " +
4306       (count == 1 ? singular_form : plural_form);
4307 }
4308 
4309 // Formats the count of tests.
FormatTestCount(int test_count)4310 static std::string FormatTestCount(int test_count) {
4311   return FormatCountableNoun(test_count, "test", "tests");
4312 }
4313 
4314 // Formats the count of test cases.
FormatTestCaseCount(int test_case_count)4315 static std::string FormatTestCaseCount(int test_case_count) {
4316   return FormatCountableNoun(test_case_count, "test case", "test cases");
4317 }
4318 
4319 // Converts a TestPartResult::Type enum to human-friendly string
4320 // representation.  Both kNonFatalFailure and kFatalFailure are translated
4321 // to "Failure", as the user usually doesn't care about the difference
4322 // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)4323 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4324   switch (type) {
4325     case TestPartResult::kSuccess:
4326       return "Success";
4327 
4328     case TestPartResult::kNonFatalFailure:
4329     case TestPartResult::kFatalFailure:
4330 #ifdef _MSC_VER
4331       return "error: ";
4332 #else
4333       return "Failure\n";
4334 #endif
4335     default:
4336       return "Unknown result type";
4337   }
4338 }
4339 
4340 namespace internal {
4341 
4342 // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)4343 static std::string PrintTestPartResultToString(
4344     const TestPartResult& test_part_result) {
4345   return (Message()
4346           << internal::FormatFileLocation(test_part_result.file_name(),
4347                                           test_part_result.line_number())
4348           << " " << TestPartResultTypeToString(test_part_result.type())
4349           << test_part_result.message()).GetString();
4350 }
4351 
4352 // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)4353 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4354   const std::string& result =
4355       PrintTestPartResultToString(test_part_result);
4356   printf("%s\n", result.c_str());
4357   fflush(stdout);
4358   // If the test program runs in Visual Studio or a debugger, the
4359   // following statements add the test part result message to the Output
4360   // window such that the user can double-click on it to jump to the
4361   // corresponding source code location; otherwise they do nothing.
4362 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4363   // We don't call OutputDebugString*() on Windows Mobile, as printing
4364   // to stdout is done by OutputDebugString() there already - we don't
4365   // want the same message printed twice.
4366   ::OutputDebugStringA(result.c_str());
4367   ::OutputDebugStringA("\n");
4368 #endif
4369 }
4370 
4371 // class PrettyUnitTestResultPrinter
4372 
4373 enum GTestColor {
4374   COLOR_DEFAULT,
4375   COLOR_RED,
4376   COLOR_GREEN,
4377   COLOR_YELLOW
4378 };
4379 
4380 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4381     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4382 
4383 // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)4384 static WORD GetColorAttribute(GTestColor color) {
4385   switch (color) {
4386     case COLOR_RED:    return FOREGROUND_RED;
4387     case COLOR_GREEN:  return FOREGROUND_GREEN;
4388     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4389     default:           return 0;
4390   }
4391 }
4392 
GetBitOffset(WORD color_mask)4393 static int GetBitOffset(WORD color_mask) {
4394   if (color_mask == 0) return 0;
4395 
4396   int bitOffset = 0;
4397   while ((color_mask & 1) == 0) {
4398     color_mask >>= 1;
4399     ++bitOffset;
4400   }
4401   return bitOffset;
4402 }
4403 
GetNewColor(GTestColor color,WORD old_color_attrs)4404 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
4405   // Let's reuse the BG
4406   static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4407                                       BACKGROUND_RED | BACKGROUND_INTENSITY;
4408   static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4409                                       FOREGROUND_RED | FOREGROUND_INTENSITY;
4410   const WORD existing_bg = old_color_attrs & background_mask;
4411 
4412   WORD new_color =
4413       GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4414   static const int bg_bitOffset = GetBitOffset(background_mask);
4415   static const int fg_bitOffset = GetBitOffset(foreground_mask);
4416 
4417   if (((new_color & background_mask) >> bg_bitOffset) ==
4418       ((new_color & foreground_mask) >> fg_bitOffset)) {
4419     new_color ^= FOREGROUND_INTENSITY;  // invert intensity
4420   }
4421   return new_color;
4422 }
4423 
4424 #else
4425 
4426 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
4427 // an invalid input.
GetAnsiColorCode(GTestColor color)4428 static const char* GetAnsiColorCode(GTestColor color) {
4429   switch (color) {
4430     case COLOR_RED:     return "1";
4431     case COLOR_GREEN:   return "2";
4432     case COLOR_YELLOW:  return "3";
4433     default:            return NULL;
4434   };
4435 }
4436 
4437 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4438 
4439 // Returns true iff Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)4440 bool ShouldUseColor(bool stdout_is_tty) {
4441   const char* const gtest_color = GTEST_FLAG(color).c_str();
4442 
4443   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4444 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
4445     // On Windows the TERM variable is usually not set, but the
4446     // console there does support colors.
4447     return stdout_is_tty;
4448 #else
4449     // On non-Windows platforms, we rely on the TERM variable.
4450     const char* const term = posix::GetEnv("TERM");
4451     const bool term_supports_color =
4452         String::CStringEquals(term, "xterm") ||
4453         String::CStringEquals(term, "xterm-color") ||
4454         String::CStringEquals(term, "xterm-256color") ||
4455         String::CStringEquals(term, "screen") ||
4456         String::CStringEquals(term, "screen-256color") ||
4457         String::CStringEquals(term, "tmux") ||
4458         String::CStringEquals(term, "tmux-256color") ||
4459         String::CStringEquals(term, "rxvt-unicode") ||
4460         String::CStringEquals(term, "rxvt-unicode-256color") ||
4461         String::CStringEquals(term, "linux") ||
4462         String::CStringEquals(term, "cygwin");
4463     return stdout_is_tty && term_supports_color;
4464 #endif  // GTEST_OS_WINDOWS
4465   }
4466 
4467   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4468       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4469       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4470       String::CStringEquals(gtest_color, "1");
4471   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
4472   // value is neither one of these nor "auto", we treat it as "no" to
4473   // be conservative.
4474 }
4475 
4476 // Helpers for printing colored strings to stdout. Note that on Windows, we
4477 // cannot simply emit special characters and have the terminal change colors.
4478 // This routine must actually emit the characters rather than return a string
4479 // that would be colored when printed, as can be done on Linux.
ColoredPrintf(GTestColor color,const char * fmt,...)4480 static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4481   va_list args;
4482   va_start(args, fmt);
4483 
4484 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
4485     GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4486   const bool use_color = AlwaysFalse();
4487 #else
4488   static const bool in_color_mode =
4489       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4490   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4491 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4492   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4493 
4494   if (!use_color) {
4495     vprintf(fmt, args);
4496     va_end(args);
4497     return;
4498   }
4499 
4500 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4501     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4502   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4503 
4504   // Gets the current text color.
4505   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4506   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4507   const WORD old_color_attrs = buffer_info.wAttributes;
4508   const WORD new_color = GetNewColor(color, old_color_attrs);
4509 
4510   // We need to flush the stream buffers into the console before each
4511   // SetConsoleTextAttribute call lest it affect the text that is already
4512   // printed but has not yet reached the console.
4513   fflush(stdout);
4514   SetConsoleTextAttribute(stdout_handle, new_color);
4515 
4516   vprintf(fmt, args);
4517 
4518   fflush(stdout);
4519   // Restores the text color.
4520   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4521 #else
4522   printf("\033[0;3%sm", GetAnsiColorCode(color));
4523   vprintf(fmt, args);
4524   printf("\033[m");  // Resets the terminal to default.
4525 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4526   va_end(args);
4527 }
4528 
4529 // Text printed in Google Test's text output and --gtest_list_tests
4530 // output to label the type parameter and value parameter for a test.
4531 static const char kTypeParamLabel[] = "TypeParam";
4532 static const char kValueParamLabel[] = "GetParam()";
4533 
PrintFullTestCommentIfPresent(const TestInfo & test_info)4534 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4535   const char* const type_param = test_info.type_param();
4536   const char* const value_param = test_info.value_param();
4537 
4538   if (type_param != NULL || value_param != NULL) {
4539     printf(", where ");
4540     if (type_param != NULL) {
4541       printf("%s = %s", kTypeParamLabel, type_param);
4542       if (value_param != NULL)
4543         printf(" and ");
4544     }
4545     if (value_param != NULL) {
4546       printf("%s = %s", kValueParamLabel, value_param);
4547     }
4548   }
4549 }
4550 
4551 // This class implements the TestEventListener interface.
4552 //
4553 // Class PrettyUnitTestResultPrinter is copyable.
4554 class PrettyUnitTestResultPrinter : public TestEventListener {
4555  public:
PrettyUnitTestResultPrinter()4556   PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_case,const char * test)4557   static void PrintTestName(const char * test_case, const char * test) {
4558     printf("%s.%s", test_case, test);
4559   }
4560 
4561   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)4562   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4563   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4564   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
OnEnvironmentsSetUpEnd(const UnitTest &)4565   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4566   virtual void OnTestCaseStart(const TestCase& test_case);
4567   virtual void OnTestStart(const TestInfo& test_info);
4568   virtual void OnTestPartResult(const TestPartResult& result);
4569   virtual void OnTestEnd(const TestInfo& test_info);
4570   virtual void OnTestCaseEnd(const TestCase& test_case);
4571   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
OnEnvironmentsTearDownEnd(const UnitTest &)4572   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4573   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
OnTestProgramEnd(const UnitTest &)4574   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4575 
4576  private:
4577   static void PrintFailedTests(const UnitTest& unit_test);
4578 };
4579 
4580   // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)4581 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4582     const UnitTest& unit_test, int iteration) {
4583   if (GTEST_FLAG(repeat) != 1)
4584     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4585 
4586   const char* const filter = GTEST_FLAG(filter).c_str();
4587 
4588   // Prints the filter if it's not *.  This reminds the user that some
4589   // tests may be skipped.
4590   if (!String::CStringEquals(filter, kUniversalFilter)) {
4591     ColoredPrintf(COLOR_YELLOW,
4592                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
4593   }
4594 
4595   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4596     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4597     ColoredPrintf(COLOR_YELLOW,
4598                   "Note: This is test shard %d of %s.\n",
4599                   static_cast<int>(shard_index) + 1,
4600                   internal::posix::GetEnv(kTestTotalShards));
4601   }
4602 
4603   if (GTEST_FLAG(shuffle)) {
4604     ColoredPrintf(COLOR_YELLOW,
4605                   "Note: Randomizing tests' orders with a seed of %d .\n",
4606                   unit_test.random_seed());
4607   }
4608 
4609   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4610   printf("Running %s from %s.\n",
4611          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4612          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4613   fflush(stdout);
4614 }
4615 
OnEnvironmentsSetUpStart(const UnitTest &)4616 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4617     const UnitTest& /*unit_test*/) {
4618   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4619   printf("Global test environment set-up.\n");
4620   fflush(stdout);
4621 }
4622 
OnTestCaseStart(const TestCase & test_case)4623 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4624   const std::string counts =
4625       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4626   ColoredPrintf(COLOR_GREEN, "[----------] ");
4627   printf("%s from %s", counts.c_str(), test_case.name());
4628   if (test_case.type_param() == NULL) {
4629     printf("\n");
4630   } else {
4631     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4632   }
4633   fflush(stdout);
4634 }
4635 
OnTestStart(const TestInfo & test_info)4636 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4637   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
4638   PrintTestName(test_info.test_case_name(), test_info.name());
4639   printf("\n");
4640   fflush(stdout);
4641 }
4642 
4643 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)4644 void PrettyUnitTestResultPrinter::OnTestPartResult(
4645     const TestPartResult& result) {
4646   // If the test part succeeded, we don't need to do anything.
4647   if (result.type() == TestPartResult::kSuccess)
4648     return;
4649 
4650   // Print failure message from the assertion (e.g. expected this and got that).
4651   PrintTestPartResult(result);
4652   fflush(stdout);
4653 }
4654 
OnTestEnd(const TestInfo & test_info)4655 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4656   if (test_info.result()->Passed()) {
4657     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
4658   } else {
4659     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4660   }
4661   PrintTestName(test_info.test_case_name(), test_info.name());
4662   if (test_info.result()->Failed())
4663     PrintFullTestCommentIfPresent(test_info);
4664 
4665   if (GTEST_FLAG(print_time)) {
4666     printf(" (%s ms)\n", internal::StreamableToString(
4667            test_info.result()->elapsed_time()).c_str());
4668   } else {
4669     printf("\n");
4670   }
4671   fflush(stdout);
4672 }
4673 
OnTestCaseEnd(const TestCase & test_case)4674 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4675   if (!GTEST_FLAG(print_time)) return;
4676 
4677   const std::string counts =
4678       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4679   ColoredPrintf(COLOR_GREEN, "[----------] ");
4680   printf("%s from %s (%s ms total)\n\n",
4681          counts.c_str(), test_case.name(),
4682          internal::StreamableToString(test_case.elapsed_time()).c_str());
4683   fflush(stdout);
4684 }
4685 
OnEnvironmentsTearDownStart(const UnitTest &)4686 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4687     const UnitTest& /*unit_test*/) {
4688   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4689   printf("Global test environment tear-down\n");
4690   fflush(stdout);
4691 }
4692 
4693 // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)4694 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4695   const int failed_test_count = unit_test.failed_test_count();
4696   if (failed_test_count == 0) {
4697     return;
4698   }
4699 
4700   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4701     const TestCase& test_case = *unit_test.GetTestCase(i);
4702     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4703       continue;
4704     }
4705     for (int j = 0; j < test_case.total_test_count(); ++j) {
4706       const TestInfo& test_info = *test_case.GetTestInfo(j);
4707       if (!test_info.should_run() || test_info.result()->Passed()) {
4708         continue;
4709       }
4710       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4711       printf("%s.%s", test_case.name(), test_info.name());
4712       PrintFullTestCommentIfPresent(test_info);
4713       printf("\n");
4714     }
4715   }
4716 }
4717 
OnTestIterationEnd(const UnitTest & unit_test,int)4718 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4719                                                      int /*iteration*/) {
4720   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4721   printf("%s from %s ran.",
4722          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4723          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4724   if (GTEST_FLAG(print_time)) {
4725     printf(" (%s ms total)",
4726            internal::StreamableToString(unit_test.elapsed_time()).c_str());
4727   }
4728   printf("\n");
4729   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
4730   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4731 
4732   int num_failures = unit_test.failed_test_count();
4733   if (!unit_test.Passed()) {
4734     const int failed_test_count = unit_test.failed_test_count();
4735     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
4736     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4737     PrintFailedTests(unit_test);
4738     printf("\n%2d FAILED %s\n", num_failures,
4739                         num_failures == 1 ? "TEST" : "TESTS");
4740   }
4741 
4742   int num_disabled = unit_test.reportable_disabled_test_count();
4743   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4744     if (!num_failures) {
4745       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
4746     }
4747     ColoredPrintf(COLOR_YELLOW,
4748                   "  YOU HAVE %d DISABLED %s\n\n",
4749                   num_disabled,
4750                   num_disabled == 1 ? "TEST" : "TESTS");
4751   }
4752   // Ensure that Google Test output is printed before, e.g., heapchecker output.
4753   fflush(stdout);
4754 }
4755 
4756 // End PrettyUnitTestResultPrinter
4757 
4758 // class TestEventRepeater
4759 //
4760 // This class forwards events to other event listeners.
4761 class TestEventRepeater : public TestEventListener {
4762  public:
TestEventRepeater()4763   TestEventRepeater() : forwarding_enabled_(true) {}
4764   virtual ~TestEventRepeater();
4765   void Append(TestEventListener *listener);
4766   TestEventListener* Release(TestEventListener* listener);
4767 
4768   // Controls whether events will be forwarded to listeners_. Set to false
4769   // in death test child processes.
forwarding_enabled() const4770   bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)4771   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4772 
4773   virtual void OnTestProgramStart(const UnitTest& unit_test);
4774   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4775   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4776   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4777   virtual void OnTestCaseStart(const TestCase& test_case);
4778   virtual void OnTestStart(const TestInfo& test_info);
4779   virtual void OnTestPartResult(const TestPartResult& result);
4780   virtual void OnTestEnd(const TestInfo& test_info);
4781   virtual void OnTestCaseEnd(const TestCase& test_case);
4782   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4783   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4784   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4785   virtual void OnTestProgramEnd(const UnitTest& unit_test);
4786 
4787  private:
4788   // Controls whether events will be forwarded to listeners_. Set to false
4789   // in death test child processes.
4790   bool forwarding_enabled_;
4791   // The list of listeners that receive events.
4792   std::vector<TestEventListener*> listeners_;
4793 
4794   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4795 };
4796 
~TestEventRepeater()4797 TestEventRepeater::~TestEventRepeater() {
4798   ForEach(listeners_, Delete<TestEventListener>);
4799 }
4800 
Append(TestEventListener * listener)4801 void TestEventRepeater::Append(TestEventListener *listener) {
4802   listeners_.push_back(listener);
4803 }
4804 
4805 // FIXME: Factor the search functionality into Vector::Find.
Release(TestEventListener * listener)4806 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4807   for (size_t i = 0; i < listeners_.size(); ++i) {
4808     if (listeners_[i] == listener) {
4809       listeners_.erase(listeners_.begin() + i);
4810       return listener;
4811     }
4812   }
4813 
4814   return NULL;
4815 }
4816 
4817 // Since most methods are very similar, use macros to reduce boilerplate.
4818 // This defines a member that forwards the call to all listeners.
4819 #define GTEST_REPEATER_METHOD_(Name, Type) \
4820 void TestEventRepeater::Name(const Type& parameter) { \
4821   if (forwarding_enabled_) { \
4822     for (size_t i = 0; i < listeners_.size(); i++) { \
4823       listeners_[i]->Name(parameter); \
4824     } \
4825   } \
4826 }
4827 // This defines a member that forwards the call to all listeners in reverse
4828 // order.
4829 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4830 void TestEventRepeater::Name(const Type& parameter) { \
4831   if (forwarding_enabled_) { \
4832     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4833       listeners_[i]->Name(parameter); \
4834     } \
4835   } \
4836 }
4837 
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)4838 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4839 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4840 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4841 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4842 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4843 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4844 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4845 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4846 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4847 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4848 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4849 
4850 #undef GTEST_REPEATER_METHOD_
4851 #undef GTEST_REVERSE_REPEATER_METHOD_
4852 
4853 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4854                                              int iteration) {
4855   if (forwarding_enabled_) {
4856     for (size_t i = 0; i < listeners_.size(); i++) {
4857       listeners_[i]->OnTestIterationStart(unit_test, iteration);
4858     }
4859   }
4860 }
4861 
OnTestIterationEnd(const UnitTest & unit_test,int iteration)4862 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4863                                            int iteration) {
4864   if (forwarding_enabled_) {
4865     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4866       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4867     }
4868   }
4869 }
4870 
4871 // End TestEventRepeater
4872 
4873 // This class generates an XML output file.
4874 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4875  public:
4876   explicit XmlUnitTestResultPrinter(const char* output_file);
4877 
4878   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4879   void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases);
4880 
4881   // Prints an XML summary of all unit tests.
4882   static void PrintXmlTestsList(std::ostream* stream,
4883                                 const std::vector<TestCase*>& test_cases);
4884 
4885  private:
4886   // Is c a whitespace character that is normalized to a space character
4887   // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)4888   static bool IsNormalizableWhitespace(char c) {
4889     return c == 0x9 || c == 0xA || c == 0xD;
4890   }
4891 
4892   // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)4893   static bool IsValidXmlCharacter(char c) {
4894     return IsNormalizableWhitespace(c) || c >= 0x20;
4895   }
4896 
4897   // Returns an XML-escaped copy of the input string str.  If
4898   // is_attribute is true, the text is meant to appear as an attribute
4899   // value, and normalizable whitespace is preserved by replacing it
4900   // with character references.
4901   static std::string EscapeXml(const std::string& str, bool is_attribute);
4902 
4903   // Returns the given string with all characters invalid in XML removed.
4904   static std::string RemoveInvalidXmlCharacters(const std::string& str);
4905 
4906   // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)4907   static std::string EscapeXmlAttribute(const std::string& str) {
4908     return EscapeXml(str, true);
4909   }
4910 
4911   // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)4912   static std::string EscapeXmlText(const char* str) {
4913     return EscapeXml(str, false);
4914   }
4915 
4916   // Verifies that the given attribute belongs to the given element and
4917   // streams the attribute as XML.
4918   static void OutputXmlAttribute(std::ostream* stream,
4919                                  const std::string& element_name,
4920                                  const std::string& name,
4921                                  const std::string& value);
4922 
4923   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4924   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4925 
4926   // Streams an XML representation of a TestInfo object.
4927   static void OutputXmlTestInfo(::std::ostream* stream,
4928                                 const char* test_case_name,
4929                                 const TestInfo& test_info);
4930 
4931   // Prints an XML representation of a TestCase object
4932   static void PrintXmlTestCase(::std::ostream* stream,
4933                                const TestCase& test_case);
4934 
4935   // Prints an XML summary of unit_test to output stream out.
4936   static void PrintXmlUnitTest(::std::ostream* stream,
4937                                const UnitTest& unit_test);
4938 
4939   // Produces a string representing the test properties in a result as space
4940   // delimited XML attributes based on the property key="value" pairs.
4941   // When the std::string is not empty, it includes a space at the beginning,
4942   // to delimit this attribute from prior attributes.
4943   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4944 
4945   // Streams an XML representation of the test properties of a TestResult
4946   // object.
4947   static void OutputXmlTestProperties(std::ostream* stream,
4948                                       const TestResult& result);
4949 
4950   // The output file.
4951   const std::string output_file_;
4952 
4953   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4954 };
4955 
4956 // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)4957 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4958     : output_file_(output_file) {
4959   if (output_file_.empty()) {
4960     GTEST_LOG_(FATAL) << "XML output file may not be null";
4961   }
4962 }
4963 
4964 // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)4965 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4966                                                   int /*iteration*/) {
4967   FILE* xmlout = OpenFileForWriting(output_file_);
4968   std::stringstream stream;
4969   PrintXmlUnitTest(&stream, unit_test);
4970   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4971   fclose(xmlout);
4972 }
4973 
ListTestsMatchingFilter(const std::vector<TestCase * > & test_cases)4974 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
4975     const std::vector<TestCase*>& test_cases) {
4976   FILE* xmlout = OpenFileForWriting(output_file_);
4977   std::stringstream stream;
4978   PrintXmlTestsList(&stream, test_cases);
4979   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4980   fclose(xmlout);
4981 }
4982 
4983 // Returns an XML-escaped copy of the input string str.  If is_attribute
4984 // is true, the text is meant to appear as an attribute value, and
4985 // normalizable whitespace is preserved by replacing it with character
4986 // references.
4987 //
4988 // Invalid XML characters in str, if any, are stripped from the output.
4989 // It is expected that most, if not all, of the text processed by this
4990 // module will consist of ordinary English text.
4991 // If this module is ever modified to produce version 1.1 XML output,
4992 // most invalid characters can be retained using character references.
4993 // FIXME: It might be nice to have a minimally invasive, human-readable
4994 // escaping scheme for invalid characters, rather than dropping them.
EscapeXml(const std::string & str,bool is_attribute)4995 std::string XmlUnitTestResultPrinter::EscapeXml(
4996     const std::string& str, bool is_attribute) {
4997   Message m;
4998 
4999   for (size_t i = 0; i < str.size(); ++i) {
5000     const char ch = str[i];
5001     switch (ch) {
5002       case '<':
5003         m << "&lt;";
5004         break;
5005       case '>':
5006         m << "&gt;";
5007         break;
5008       case '&':
5009         m << "&amp;";
5010         break;
5011       case '\'':
5012         if (is_attribute)
5013           m << "&apos;";
5014         else
5015           m << '\'';
5016         break;
5017       case '"':
5018         if (is_attribute)
5019           m << "&quot;";
5020         else
5021           m << '"';
5022         break;
5023       default:
5024         if (IsValidXmlCharacter(ch)) {
5025           if (is_attribute && IsNormalizableWhitespace(ch))
5026             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5027               << ";";
5028           else
5029             m << ch;
5030         }
5031         break;
5032     }
5033   }
5034 
5035   return m.GetString();
5036 }
5037 
5038 // Returns the given string with all characters invalid in XML removed.
5039 // Currently invalid characters are dropped from the string. An
5040 // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)5041 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5042     const std::string& str) {
5043   std::string output;
5044   output.reserve(str.size());
5045   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5046     if (IsValidXmlCharacter(*it))
5047       output.push_back(*it);
5048 
5049   return output;
5050 }
5051 
5052 // The following routines generate an XML representation of a UnitTest
5053 // object.
5054 // GOOGLETEST_CM0009 DO NOT DELETE
5055 //
5056 // This is how Google Test concepts map to the DTD:
5057 //
5058 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
5059 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
5060 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
5061 //       <failure message="...">...</failure>
5062 //       <failure message="...">...</failure>
5063 //       <failure message="...">...</failure>
5064 //                                     <-- individual assertion failures
5065 //     </testcase>
5066 //   </testsuite>
5067 // </testsuites>
5068 
5069 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)5070 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5071   ::std::stringstream ss;
5072   ss << (static_cast<double>(ms) * 1e-3);
5073   return ss.str();
5074 }
5075 
PortableLocaltime(time_t seconds,struct tm * out)5076 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5077 #if defined(_MSC_VER)
5078   return localtime_s(out, &seconds) == 0;
5079 #elif defined(__MINGW32__) || defined(__MINGW64__)
5080   // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5081   // Windows' localtime(), which has a thread-local tm buffer.
5082   struct tm* tm_ptr = localtime(&seconds);  // NOLINT
5083   if (tm_ptr == NULL)
5084     return false;
5085   *out = *tm_ptr;
5086   return true;
5087 #else
5088   return localtime_r(&seconds, out) != NULL;
5089 #endif
5090 }
5091 
5092 // Converts the given epoch time in milliseconds to a date string in the ISO
5093 // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)5094 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5095   struct tm time_struct;
5096   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5097     return "";
5098   // YYYY-MM-DDThh:mm:ss
5099   return StreamableToString(time_struct.tm_year + 1900) + "-" +
5100       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5101       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5102       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5103       String::FormatIntWidth2(time_struct.tm_min) + ":" +
5104       String::FormatIntWidth2(time_struct.tm_sec);
5105 }
5106 
5107 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)5108 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5109                                                      const char* data) {
5110   const char* segment = data;
5111   *stream << "<![CDATA[";
5112   for (;;) {
5113     const char* const next_segment = strstr(segment, "]]>");
5114     if (next_segment != NULL) {
5115       stream->write(
5116           segment, static_cast<std::streamsize>(next_segment - segment));
5117       *stream << "]]>]]&gt;<![CDATA[";
5118       segment = next_segment + strlen("]]>");
5119     } else {
5120       *stream << segment;
5121       break;
5122     }
5123   }
5124   *stream << "]]>";
5125 }
5126 
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)5127 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5128     std::ostream* stream,
5129     const std::string& element_name,
5130     const std::string& name,
5131     const std::string& value) {
5132   const std::vector<std::string>& allowed_names =
5133       GetReservedAttributesForElement(element_name);
5134 
5135   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5136                    allowed_names.end())
5137       << "Attribute " << name << " is not allowed for element <" << element_name
5138       << ">.";
5139 
5140   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5141 }
5142 
5143 // Prints an XML representation of a TestInfo object.
5144 // FIXME: There is also value in printing properties with the plain printer.
OutputXmlTestInfo(::std::ostream * stream,const char * test_case_name,const TestInfo & test_info)5145 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5146                                                  const char* test_case_name,
5147                                                  const TestInfo& test_info) {
5148   const TestResult& result = *test_info.result();
5149   const std::string kTestcase = "testcase";
5150 
5151   if (test_info.is_in_another_shard()) {
5152     return;
5153   }
5154 
5155   *stream << "    <testcase";
5156   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
5157 
5158   if (test_info.value_param() != NULL) {
5159     OutputXmlAttribute(stream, kTestcase, "value_param",
5160                        test_info.value_param());
5161   }
5162   if (test_info.type_param() != NULL) {
5163     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
5164   }
5165   if (GTEST_FLAG(list_tests)) {
5166     OutputXmlAttribute(stream, kTestcase, "file", test_info.file());
5167     OutputXmlAttribute(stream, kTestcase, "line",
5168                        StreamableToString(test_info.line()));
5169     *stream << " />\n";
5170     return;
5171   }
5172 
5173   OutputXmlAttribute(stream, kTestcase, "status",
5174                      test_info.should_run() ? "run" : "notrun");
5175   OutputXmlAttribute(stream, kTestcase, "time",
5176                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
5177   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
5178 
5179   int failures = 0;
5180   for (int i = 0; i < result.total_part_count(); ++i) {
5181     const TestPartResult& part = result.GetTestPartResult(i);
5182     if (part.failed()) {
5183       if (++failures == 1) {
5184         *stream << ">\n";
5185       }
5186       const std::string location =
5187           internal::FormatCompilerIndependentFileLocation(part.file_name(),
5188                                                           part.line_number());
5189       const std::string summary = location + "\n" + part.summary();
5190       *stream << "      <failure message=\""
5191               << EscapeXmlAttribute(summary.c_str())
5192               << "\" type=\"\">";
5193       const std::string detail = location + "\n" + part.message();
5194       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5195       *stream << "</failure>\n";
5196     }
5197   }
5198 
5199   if (failures == 0 && result.test_property_count() == 0) {
5200     *stream << " />\n";
5201   } else {
5202     if (failures == 0) {
5203       *stream << ">\n";
5204     }
5205     OutputXmlTestProperties(stream, result);
5206     *stream << "    </testcase>\n";
5207   }
5208 }
5209 
5210 // Prints an XML representation of a TestCase object
PrintXmlTestCase(std::ostream * stream,const TestCase & test_case)5211 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
5212                                                 const TestCase& test_case) {
5213   const std::string kTestsuite = "testsuite";
5214   *stream << "  <" << kTestsuite;
5215   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
5216   OutputXmlAttribute(stream, kTestsuite, "tests",
5217                      StreamableToString(test_case.reportable_test_count()));
5218   if (!GTEST_FLAG(list_tests)) {
5219     OutputXmlAttribute(stream, kTestsuite, "failures",
5220                        StreamableToString(test_case.failed_test_count()));
5221     OutputXmlAttribute(
5222         stream, kTestsuite, "disabled",
5223         StreamableToString(test_case.reportable_disabled_test_count()));
5224     OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5225     OutputXmlAttribute(stream, kTestsuite, "time",
5226                        FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
5227     *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result());
5228   }
5229   *stream << ">\n";
5230   for (int i = 0; i < test_case.total_test_count(); ++i) {
5231     if (test_case.GetTestInfo(i)->is_reportable())
5232       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
5233   }
5234   *stream << "  </" << kTestsuite << ">\n";
5235 }
5236 
5237 // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)5238 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5239                                                 const UnitTest& unit_test) {
5240   const std::string kTestsuites = "testsuites";
5241 
5242   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5243   *stream << "<" << kTestsuites;
5244 
5245   OutputXmlAttribute(stream, kTestsuites, "tests",
5246                      StreamableToString(unit_test.reportable_test_count()));
5247   OutputXmlAttribute(stream, kTestsuites, "failures",
5248                      StreamableToString(unit_test.failed_test_count()));
5249   OutputXmlAttribute(
5250       stream, kTestsuites, "disabled",
5251       StreamableToString(unit_test.reportable_disabled_test_count()));
5252   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5253   OutputXmlAttribute(
5254       stream, kTestsuites, "timestamp",
5255       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5256   OutputXmlAttribute(stream, kTestsuites, "time",
5257                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5258 
5259   if (GTEST_FLAG(shuffle)) {
5260     OutputXmlAttribute(stream, kTestsuites, "random_seed",
5261                        StreamableToString(unit_test.random_seed()));
5262   }
5263   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5264 
5265   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5266   *stream << ">\n";
5267 
5268   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
5269     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
5270       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
5271   }
5272   *stream << "</" << kTestsuites << ">\n";
5273 }
5274 
PrintXmlTestsList(std::ostream * stream,const std::vector<TestCase * > & test_cases)5275 void XmlUnitTestResultPrinter::PrintXmlTestsList(
5276     std::ostream* stream, const std::vector<TestCase*>& test_cases) {
5277   const std::string kTestsuites = "testsuites";
5278 
5279   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5280   *stream << "<" << kTestsuites;
5281 
5282   int total_tests = 0;
5283   for (size_t i = 0; i < test_cases.size(); ++i) {
5284     total_tests += test_cases[i]->total_test_count();
5285   }
5286   OutputXmlAttribute(stream, kTestsuites, "tests",
5287                      StreamableToString(total_tests));
5288   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5289   *stream << ">\n";
5290 
5291   for (size_t i = 0; i < test_cases.size(); ++i) {
5292     PrintXmlTestCase(stream, *test_cases[i]);
5293   }
5294   *stream << "</" << kTestsuites << ">\n";
5295 }
5296 
5297 // Produces a string representing the test properties in a result as space
5298 // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)5299 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5300     const TestResult& result) {
5301   Message attributes;
5302   for (int i = 0; i < result.test_property_count(); ++i) {
5303     const TestProperty& property = result.GetTestProperty(i);
5304     attributes << " " << property.key() << "="
5305         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5306   }
5307   return attributes.GetString();
5308 }
5309 
OutputXmlTestProperties(std::ostream * stream,const TestResult & result)5310 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5311     std::ostream* stream, const TestResult& result) {
5312   const std::string kProperties = "properties";
5313   const std::string kProperty = "property";
5314 
5315   if (result.test_property_count() <= 0) {
5316     return;
5317   }
5318 
5319   *stream << "<" << kProperties << ">\n";
5320   for (int i = 0; i < result.test_property_count(); ++i) {
5321     const TestProperty& property = result.GetTestProperty(i);
5322     *stream << "<" << kProperty;
5323     *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
5324     *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
5325     *stream << "/>\n";
5326   }
5327   *stream << "</" << kProperties << ">\n";
5328 }
5329 
5330 // End XmlUnitTestResultPrinter
5331 
5332 // This class generates an JSON output file.
5333 class JsonUnitTestResultPrinter : public EmptyTestEventListener {
5334  public:
5335   explicit JsonUnitTestResultPrinter(const char* output_file);
5336 
5337   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
5338 
5339   // Prints an JSON summary of all unit tests.
5340   static void PrintJsonTestList(::std::ostream* stream,
5341                                 const std::vector<TestCase*>& test_cases);
5342 
5343  private:
5344   // Returns an JSON-escaped copy of the input string str.
5345   static std::string EscapeJson(const std::string& str);
5346 
5347   //// Verifies that the given attribute belongs to the given element and
5348   //// streams the attribute as JSON.
5349   static void OutputJsonKey(std::ostream* stream,
5350                             const std::string& element_name,
5351                             const std::string& name,
5352                             const std::string& value,
5353                             const std::string& indent,
5354                             bool comma = true);
5355   static void OutputJsonKey(std::ostream* stream,
5356                             const std::string& element_name,
5357                             const std::string& name,
5358                             int value,
5359                             const std::string& indent,
5360                             bool comma = true);
5361 
5362   // Streams a JSON representation of a TestInfo object.
5363   static void OutputJsonTestInfo(::std::ostream* stream,
5364                                  const char* test_case_name,
5365                                  const TestInfo& test_info);
5366 
5367   // Prints a JSON representation of a TestCase object
5368   static void PrintJsonTestCase(::std::ostream* stream,
5369                                 const TestCase& test_case);
5370 
5371   // Prints a JSON summary of unit_test to output stream out.
5372   static void PrintJsonUnitTest(::std::ostream* stream,
5373                                 const UnitTest& unit_test);
5374 
5375   // Produces a string representing the test properties in a result as
5376   // a JSON dictionary.
5377   static std::string TestPropertiesAsJson(const TestResult& result,
5378                                           const std::string& indent);
5379 
5380   // The output file.
5381   const std::string output_file_;
5382 
5383   GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
5384 };
5385 
5386 // Creates a new JsonUnitTestResultPrinter.
JsonUnitTestResultPrinter(const char * output_file)5387 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
5388     : output_file_(output_file) {
5389   if (output_file_.empty()) {
5390     GTEST_LOG_(FATAL) << "JSON output file may not be null";
5391   }
5392 }
5393 
OnTestIterationEnd(const UnitTest & unit_test,int)5394 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5395                                                   int /*iteration*/) {
5396   FILE* jsonout = OpenFileForWriting(output_file_);
5397   std::stringstream stream;
5398   PrintJsonUnitTest(&stream, unit_test);
5399   fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
5400   fclose(jsonout);
5401 }
5402 
5403 // Returns an JSON-escaped copy of the input string str.
EscapeJson(const std::string & str)5404 std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
5405   Message m;
5406 
5407   for (size_t i = 0; i < str.size(); ++i) {
5408     const char ch = str[i];
5409     switch (ch) {
5410       case '\\':
5411       case '"':
5412       case '/':
5413         m << '\\' << ch;
5414         break;
5415       case '\b':
5416         m << "\\b";
5417         break;
5418       case '\t':
5419         m << "\\t";
5420         break;
5421       case '\n':
5422         m << "\\n";
5423         break;
5424       case '\f':
5425         m << "\\f";
5426         break;
5427       case '\r':
5428         m << "\\r";
5429         break;
5430       default:
5431         if (ch < ' ') {
5432           m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
5433         } else {
5434           m << ch;
5435         }
5436         break;
5437     }
5438   }
5439 
5440   return m.GetString();
5441 }
5442 
5443 // The following routines generate an JSON representation of a UnitTest
5444 // object.
5445 
5446 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsDuration(TimeInMillis ms)5447 static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
5448   ::std::stringstream ss;
5449   ss << (static_cast<double>(ms) * 1e-3) << "s";
5450   return ss.str();
5451 }
5452 
5453 // Converts the given epoch time in milliseconds to a date string in the
5454 // RFC3339 format, without the timezone information.
FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms)5455 static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
5456   struct tm time_struct;
5457   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5458     return "";
5459   // YYYY-MM-DDThh:mm:ss
5460   return StreamableToString(time_struct.tm_year + 1900) + "-" +
5461       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5462       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5463       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5464       String::FormatIntWidth2(time_struct.tm_min) + ":" +
5465       String::FormatIntWidth2(time_struct.tm_sec) + "Z";
5466 }
5467 
Indent(int width)5468 static inline std::string Indent(int width) {
5469   return std::string(width, ' ');
5470 }
5471 
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value,const std::string & indent,bool comma)5472 void JsonUnitTestResultPrinter::OutputJsonKey(
5473     std::ostream* stream,
5474     const std::string& element_name,
5475     const std::string& name,
5476     const std::string& value,
5477     const std::string& indent,
5478     bool comma) {
5479   const std::vector<std::string>& allowed_names =
5480       GetReservedAttributesForElement(element_name);
5481 
5482   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5483                    allowed_names.end())
5484       << "Key \"" << name << "\" is not allowed for value \"" << element_name
5485       << "\".";
5486 
5487   *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
5488   if (comma)
5489     *stream << ",\n";
5490 }
5491 
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,int value,const std::string & indent,bool comma)5492 void JsonUnitTestResultPrinter::OutputJsonKey(
5493     std::ostream* stream,
5494     const std::string& element_name,
5495     const std::string& name,
5496     int value,
5497     const std::string& indent,
5498     bool comma) {
5499   const std::vector<std::string>& allowed_names =
5500       GetReservedAttributesForElement(element_name);
5501 
5502   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5503                    allowed_names.end())
5504       << "Key \"" << name << "\" is not allowed for value \"" << element_name
5505       << "\".";
5506 
5507   *stream << indent << "\"" << name << "\": " << StreamableToString(value);
5508   if (comma)
5509     *stream << ",\n";
5510 }
5511 
5512 // Prints a JSON representation of a TestInfo object.
OutputJsonTestInfo(::std::ostream * stream,const char * test_case_name,const TestInfo & test_info)5513 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
5514                                                    const char* test_case_name,
5515                                                    const TestInfo& test_info) {
5516   const TestResult& result = *test_info.result();
5517   const std::string kTestcase = "testcase";
5518   const std::string kIndent = Indent(10);
5519 
5520   *stream << Indent(8) << "{\n";
5521   OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent);
5522 
5523   if (test_info.value_param() != NULL) {
5524     OutputJsonKey(stream, kTestcase, "value_param",
5525                   test_info.value_param(), kIndent);
5526   }
5527   if (test_info.type_param() != NULL) {
5528     OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(),
5529                   kIndent);
5530   }
5531   if (GTEST_FLAG(list_tests)) {
5532     OutputJsonKey(stream, kTestcase, "file", test_info.file(), kIndent);
5533     OutputJsonKey(stream, kTestcase, "line", test_info.line(), kIndent, false);
5534     *stream << "\n" << Indent(8) << "}";
5535     return;
5536   }
5537 
5538   OutputJsonKey(stream, kTestcase, "status",
5539                 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
5540   OutputJsonKey(stream, kTestcase, "time",
5541                 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
5542   OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false);
5543   *stream << TestPropertiesAsJson(result, kIndent);
5544 
5545   int failures = 0;
5546   for (int i = 0; i < result.total_part_count(); ++i) {
5547     const TestPartResult& part = result.GetTestPartResult(i);
5548     if (part.failed()) {
5549       *stream << ",\n";
5550       if (++failures == 1) {
5551         *stream << kIndent << "\"" << "failures" << "\": [\n";
5552       }
5553       const std::string location =
5554           internal::FormatCompilerIndependentFileLocation(part.file_name(),
5555                                                           part.line_number());
5556       const std::string message = EscapeJson(location + "\n" + part.message());
5557       *stream << kIndent << "  {\n"
5558               << kIndent << "    \"failure\": \"" << message << "\",\n"
5559               << kIndent << "    \"type\": \"\"\n"
5560               << kIndent << "  }";
5561     }
5562   }
5563 
5564   if (failures > 0)
5565     *stream << "\n" << kIndent << "]";
5566   *stream << "\n" << Indent(8) << "}";
5567 }
5568 
5569 // Prints an JSON representation of a TestCase object
PrintJsonTestCase(std::ostream * stream,const TestCase & test_case)5570 void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream,
5571                                                   const TestCase& test_case) {
5572   const std::string kTestsuite = "testsuite";
5573   const std::string kIndent = Indent(6);
5574 
5575   *stream << Indent(4) << "{\n";
5576   OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent);
5577   OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(),
5578                 kIndent);
5579   if (!GTEST_FLAG(list_tests)) {
5580     OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(),
5581                   kIndent);
5582     OutputJsonKey(stream, kTestsuite, "disabled",
5583                   test_case.reportable_disabled_test_count(), kIndent);
5584     OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
5585     OutputJsonKey(stream, kTestsuite, "time",
5586                   FormatTimeInMillisAsDuration(test_case.elapsed_time()),
5587                   kIndent, false);
5588     *stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent)
5589             << ",\n";
5590   }
5591 
5592   *stream << kIndent << "\"" << kTestsuite << "\": [\n";
5593 
5594   bool comma = false;
5595   for (int i = 0; i < test_case.total_test_count(); ++i) {
5596     if (test_case.GetTestInfo(i)->is_reportable()) {
5597       if (comma) {
5598         *stream << ",\n";
5599       } else {
5600         comma = true;
5601       }
5602       OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
5603     }
5604   }
5605   *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
5606 }
5607 
5608 // Prints a JSON summary of unit_test to output stream out.
PrintJsonUnitTest(std::ostream * stream,const UnitTest & unit_test)5609 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
5610                                                   const UnitTest& unit_test) {
5611   const std::string kTestsuites = "testsuites";
5612   const std::string kIndent = Indent(2);
5613   *stream << "{\n";
5614 
5615   OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
5616                 kIndent);
5617   OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
5618                 kIndent);
5619   OutputJsonKey(stream, kTestsuites, "disabled",
5620                 unit_test.reportable_disabled_test_count(), kIndent);
5621   OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
5622   if (GTEST_FLAG(shuffle)) {
5623     OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
5624                   kIndent);
5625   }
5626   OutputJsonKey(stream, kTestsuites, "timestamp",
5627                 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
5628                 kIndent);
5629   OutputJsonKey(stream, kTestsuites, "time",
5630                 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
5631                 false);
5632 
5633   *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
5634           << ",\n";
5635 
5636   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5637   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5638 
5639   bool comma = false;
5640   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
5641     if (unit_test.GetTestCase(i)->reportable_test_count() > 0) {
5642       if (comma) {
5643         *stream << ",\n";
5644       } else {
5645         comma = true;
5646       }
5647       PrintJsonTestCase(stream, *unit_test.GetTestCase(i));
5648     }
5649   }
5650 
5651   *stream << "\n" << kIndent << "]\n" << "}\n";
5652 }
5653 
PrintJsonTestList(std::ostream * stream,const std::vector<TestCase * > & test_cases)5654 void JsonUnitTestResultPrinter::PrintJsonTestList(
5655     std::ostream* stream, const std::vector<TestCase*>& test_cases) {
5656   const std::string kTestsuites = "testsuites";
5657   const std::string kIndent = Indent(2);
5658   *stream << "{\n";
5659   int total_tests = 0;
5660   for (size_t i = 0; i < test_cases.size(); ++i) {
5661     total_tests += test_cases[i]->total_test_count();
5662   }
5663   OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
5664 
5665   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5666   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5667 
5668   for (size_t i = 0; i < test_cases.size(); ++i) {
5669     if (i != 0) {
5670       *stream << ",\n";
5671     }
5672     PrintJsonTestCase(stream, *test_cases[i]);
5673   }
5674 
5675   *stream << "\n"
5676           << kIndent << "]\n"
5677           << "}\n";
5678 }
5679 // Produces a string representing the test properties in a result as
5680 // a JSON dictionary.
TestPropertiesAsJson(const TestResult & result,const std::string & indent)5681 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
5682     const TestResult& result, const std::string& indent) {
5683   Message attributes;
5684   for (int i = 0; i < result.test_property_count(); ++i) {
5685     const TestProperty& property = result.GetTestProperty(i);
5686     attributes << ",\n" << indent << "\"" << property.key() << "\": "
5687                << "\"" << EscapeJson(property.value()) << "\"";
5688   }
5689   return attributes.GetString();
5690 }
5691 
5692 // End JsonUnitTestResultPrinter
5693 
5694 #if GTEST_CAN_STREAM_RESULTS_
5695 
5696 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5697 // replaces them by "%xx" where xx is their hexadecimal value. For
5698 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
5699 // in both time and space -- important as the input str may contain an
5700 // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)5701 std::string StreamingListener::UrlEncode(const char* str) {
5702   std::string result;
5703   result.reserve(strlen(str) + 1);
5704   for (char ch = *str; ch != '\0'; ch = *++str) {
5705     switch (ch) {
5706       case '%':
5707       case '=':
5708       case '&':
5709       case '\n':
5710         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5711         break;
5712       default:
5713         result.push_back(ch);
5714         break;
5715     }
5716   }
5717   return result;
5718 }
5719 
MakeConnection()5720 void StreamingListener::SocketWriter::MakeConnection() {
5721   GTEST_CHECK_(sockfd_ == -1)
5722       << "MakeConnection() can't be called when there is already a connection.";
5723 
5724   addrinfo hints;
5725   memset(&hints, 0, sizeof(hints));
5726   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
5727   hints.ai_socktype = SOCK_STREAM;
5728   addrinfo* servinfo = NULL;
5729 
5730   // Use the getaddrinfo() to get a linked list of IP addresses for
5731   // the given host name.
5732   const int error_num = getaddrinfo(
5733       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5734   if (error_num != 0) {
5735     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5736                         << gai_strerror(error_num);
5737   }
5738 
5739   // Loop through all the results and connect to the first we can.
5740   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
5741        cur_addr = cur_addr->ai_next) {
5742     sockfd_ = socket(
5743         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5744     if (sockfd_ != -1) {
5745       // Connect the client socket to the server socket.
5746       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5747         close(sockfd_);
5748         sockfd_ = -1;
5749       }
5750     }
5751   }
5752 
5753   freeaddrinfo(servinfo);  // all done with this structure
5754 
5755   if (sockfd_ == -1) {
5756     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5757                         << host_name_ << ":" << port_num_;
5758   }
5759 }
5760 
5761 // End of class Streaming Listener
5762 #endif  // GTEST_CAN_STREAM_RESULTS__
5763 
5764 // class OsStackTraceGetter
5765 
5766 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5767     "... " GTEST_NAME_ " internal frames ...";
5768 
CurrentStackTrace(int max_depth,int skip_count)5769 std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
5770     GTEST_LOCK_EXCLUDED_(mutex_) {
5771 #if GTEST_HAS_ABSL
5772   std::string result;
5773 
5774   if (max_depth <= 0) {
5775     return result;
5776   }
5777 
5778   max_depth = std::min(max_depth, kMaxStackTraceDepth);
5779 
5780   std::vector<void*> raw_stack(max_depth);
5781   // Skips the frames requested by the caller, plus this function.
5782   const int raw_stack_size =
5783       absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5784 
5785   void* caller_frame = nullptr;
5786   {
5787     MutexLock lock(&mutex_);
5788     caller_frame = caller_frame_;
5789   }
5790 
5791   for (int i = 0; i < raw_stack_size; ++i) {
5792     if (raw_stack[i] == caller_frame &&
5793         !GTEST_FLAG(show_internal_stack_frames)) {
5794       // Add a marker to the trace and stop adding frames.
5795       absl::StrAppend(&result, kElidedFramesMarker, "\n");
5796       break;
5797     }
5798 
5799     char tmp[1024];
5800     const char* symbol = "(unknown)";
5801     if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
5802       symbol = tmp;
5803     }
5804 
5805     char line[1024];
5806     snprintf(line, sizeof(line), "  %p: %s\n", raw_stack[i], symbol);
5807     result += line;
5808   }
5809 
5810   return result;
5811 
5812 #else  // !GTEST_HAS_ABSL
5813   static_cast<void>(max_depth);
5814   static_cast<void>(skip_count);
5815   return "";
5816 #endif  // GTEST_HAS_ABSL
5817 }
5818 
UponLeavingGTest()5819 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
5820 #if GTEST_HAS_ABSL
5821   void* caller_frame = nullptr;
5822   if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5823     caller_frame = nullptr;
5824   }
5825 
5826   MutexLock lock(&mutex_);
5827   caller_frame_ = caller_frame;
5828 #endif  // GTEST_HAS_ABSL
5829 }
5830 
5831 // A helper class that creates the premature-exit file in its
5832 // constructor and deletes the file in its destructor.
5833 class ScopedPrematureExitFile {
5834  public:
ScopedPrematureExitFile(const char * premature_exit_filepath)5835   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5836       : premature_exit_filepath_(premature_exit_filepath ?
5837                                  premature_exit_filepath : "") {
5838     // If a path to the premature-exit file is specified...
5839     if (!premature_exit_filepath_.empty()) {
5840       // create the file with a single "0" character in it.  I/O
5841       // errors are ignored as there's nothing better we can do and we
5842       // don't want to fail the test because of this.
5843       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5844       fwrite("0", 1, 1, pfile);
5845       fclose(pfile);
5846     }
5847   }
5848 
~ScopedPrematureExitFile()5849   ~ScopedPrematureExitFile() {
5850     if (!premature_exit_filepath_.empty()) {
5851       int retval = remove(premature_exit_filepath_.c_str());
5852       if (retval) {
5853         GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
5854                           << premature_exit_filepath_ << "\" with error "
5855                           << retval;
5856       }
5857     }
5858   }
5859 
5860  private:
5861   const std::string premature_exit_filepath_;
5862 
5863   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5864 };
5865 
5866 }  // namespace internal
5867 
5868 // class TestEventListeners
5869 
TestEventListeners()5870 TestEventListeners::TestEventListeners()
5871     : repeater_(new internal::TestEventRepeater()),
5872       default_result_printer_(NULL),
5873       default_xml_generator_(NULL) {
5874 }
5875 
~TestEventListeners()5876 TestEventListeners::~TestEventListeners() { delete repeater_; }
5877 
5878 // Returns the standard listener responsible for the default console
5879 // output.  Can be removed from the listeners list to shut down default
5880 // console output.  Note that removing this object from the listener list
5881 // with Release transfers its ownership to the user.
Append(TestEventListener * listener)5882 void TestEventListeners::Append(TestEventListener* listener) {
5883   repeater_->Append(listener);
5884 }
5885 
5886 // Removes the given event listener from the list and returns it.  It then
5887 // becomes the caller's responsibility to delete the listener. Returns
5888 // NULL if the listener is not found in the list.
Release(TestEventListener * listener)5889 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5890   if (listener == default_result_printer_)
5891     default_result_printer_ = NULL;
5892   else if (listener == default_xml_generator_)
5893     default_xml_generator_ = NULL;
5894   return repeater_->Release(listener);
5895 }
5896 
5897 // Returns repeater that broadcasts the TestEventListener events to all
5898 // subscribers.
repeater()5899 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5900 
5901 // Sets the default_result_printer attribute to the provided listener.
5902 // The listener is also added to the listener list and previous
5903 // default_result_printer is removed from it and deleted. The listener can
5904 // also be NULL in which case it will not be added to the list. Does
5905 // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)5906 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5907   if (default_result_printer_ != listener) {
5908     // It is an error to pass this method a listener that is already in the
5909     // list.
5910     delete Release(default_result_printer_);
5911     default_result_printer_ = listener;
5912     if (listener != NULL)
5913       Append(listener);
5914   }
5915 }
5916 
5917 // Sets the default_xml_generator attribute to the provided listener.  The
5918 // listener is also added to the listener list and previous
5919 // default_xml_generator is removed from it and deleted. The listener can
5920 // also be NULL in which case it will not be added to the list. Does
5921 // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)5922 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5923   if (default_xml_generator_ != listener) {
5924     // It is an error to pass this method a listener that is already in the
5925     // list.
5926     delete Release(default_xml_generator_);
5927     default_xml_generator_ = listener;
5928     if (listener != NULL)
5929       Append(listener);
5930   }
5931 }
5932 
5933 // Controls whether events will be forwarded by the repeater to the
5934 // listeners in the list.
EventForwardingEnabled() const5935 bool TestEventListeners::EventForwardingEnabled() const {
5936   return repeater_->forwarding_enabled();
5937 }
5938 
SuppressEventForwarding()5939 void TestEventListeners::SuppressEventForwarding() {
5940   repeater_->set_forwarding_enabled(false);
5941 }
5942 
5943 // class UnitTest
5944 
5945 // Gets the singleton UnitTest object.  The first time this method is
5946 // called, a UnitTest object is constructed and returned.  Consecutive
5947 // calls will return the same object.
5948 //
5949 // We don't protect this under mutex_ as a user is not supposed to
5950 // call this before main() starts, from which point on the return
5951 // value will never change.
GetInstance()5952 UnitTest* UnitTest::GetInstance() {
5953   // When compiled with MSVC 7.1 in optimized mode, destroying the
5954   // UnitTest object upon exiting the program messes up the exit code,
5955   // causing successful tests to appear failed.  We have to use a
5956   // different implementation in this case to bypass the compiler bug.
5957   // This implementation makes the compiler happy, at the cost of
5958   // leaking the UnitTest object.
5959 
5960   // CodeGear C++Builder insists on a public destructor for the
5961   // default implementation.  Use this implementation to keep good OO
5962   // design with private destructor.
5963 
5964 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5965   static UnitTest* const instance = new UnitTest;
5966   return instance;
5967 #else
5968   static UnitTest instance;
5969   return &instance;
5970 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5971 }
5972 
5973 // Gets the number of successful test cases.
successful_test_case_count() const5974 int UnitTest::successful_test_case_count() const {
5975   return impl()->successful_test_case_count();
5976 }
5977 
5978 // Gets the number of failed test cases.
failed_test_case_count() const5979 int UnitTest::failed_test_case_count() const {
5980   return impl()->failed_test_case_count();
5981 }
5982 
5983 // Gets the number of all test cases.
total_test_case_count() const5984 int UnitTest::total_test_case_count() const {
5985   return impl()->total_test_case_count();
5986 }
5987 
5988 // Gets the number of all test cases that contain at least one test
5989 // that should run.
test_case_to_run_count() const5990 int UnitTest::test_case_to_run_count() const {
5991   return impl()->test_case_to_run_count();
5992 }
5993 
5994 // Gets the number of successful tests.
successful_test_count() const5995 int UnitTest::successful_test_count() const {
5996   return impl()->successful_test_count();
5997 }
5998 
5999 // Gets the number of failed tests.
failed_test_count() const6000 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
6001 
6002 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const6003 int UnitTest::reportable_disabled_test_count() const {
6004   return impl()->reportable_disabled_test_count();
6005 }
6006 
6007 // Gets the number of disabled tests.
disabled_test_count() const6008 int UnitTest::disabled_test_count() const {
6009   return impl()->disabled_test_count();
6010 }
6011 
6012 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const6013 int UnitTest::reportable_test_count() const {
6014   return impl()->reportable_test_count();
6015 }
6016 
6017 // Gets the number of all tests.
total_test_count() const6018 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
6019 
6020 // Gets the number of tests that should run.
test_to_run_count() const6021 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
6022 
6023 // Gets the time of the test program start, in ms from the start of the
6024 // UNIX epoch.
start_timestamp() const6025 internal::TimeInMillis UnitTest::start_timestamp() const {
6026     return impl()->start_timestamp();
6027 }
6028 
6029 // Gets the elapsed time, in milliseconds.
elapsed_time() const6030 internal::TimeInMillis UnitTest::elapsed_time() const {
6031   return impl()->elapsed_time();
6032 }
6033 
6034 // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const6035 bool UnitTest::Passed() const { return impl()->Passed(); }
6036 
6037 // Returns true iff the unit test failed (i.e. some test case failed
6038 // or something outside of all tests failed).
Failed() const6039 bool UnitTest::Failed() const { return impl()->Failed(); }
6040 
6041 // Gets the i-th test case among all the test cases. i can range from 0 to
6042 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const6043 const TestCase* UnitTest::GetTestCase(int i) const {
6044   return impl()->GetTestCase(i);
6045 }
6046 
6047 // Returns the TestResult containing information on test failures and
6048 // properties logged outside of individual test cases.
ad_hoc_test_result() const6049 const TestResult& UnitTest::ad_hoc_test_result() const {
6050   return *impl()->ad_hoc_test_result();
6051 }
6052 
6053 // Gets the i-th test case among all the test cases. i can range from 0 to
6054 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)6055 TestCase* UnitTest::GetMutableTestCase(int i) {
6056   return impl()->GetMutableTestCase(i);
6057 }
6058 
6059 // Returns the list of event listeners that can be used to track events
6060 // inside Google Test.
listeners()6061 TestEventListeners& UnitTest::listeners() {
6062   return *impl()->listeners();
6063 }
6064 
6065 // Registers and returns a global test environment.  When a test
6066 // program is run, all global test environments will be set-up in the
6067 // order they were registered.  After all tests in the program have
6068 // finished, all global test environments will be torn-down in the
6069 // *reverse* order they were registered.
6070 //
6071 // The UnitTest object takes ownership of the given environment.
6072 //
6073 // We don't protect this under mutex_, as we only support calling it
6074 // from the main thread.
AddEnvironment(Environment * env)6075 Environment* UnitTest::AddEnvironment(Environment* env) {
6076   if (env == NULL) {
6077     return NULL;
6078   }
6079 
6080   impl_->environments().push_back(env);
6081   return env;
6082 }
6083 
6084 // Adds a TestPartResult to the current TestResult object.  All Google Test
6085 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
6086 // this to report their results.  The user code should use the
6087 // 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)6088 void UnitTest::AddTestPartResult(
6089     TestPartResult::Type result_type,
6090     const char* file_name,
6091     int line_number,
6092     const std::string& message,
6093     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
6094   Message msg;
6095   msg << message;
6096 
6097   internal::MutexLock lock(&mutex_);
6098   if (impl_->gtest_trace_stack().size() > 0) {
6099     msg << "\n" << GTEST_NAME_ << " trace:";
6100 
6101     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
6102          i > 0; --i) {
6103       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6104       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
6105           << " " << trace.message;
6106     }
6107   }
6108 
6109   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
6110     msg << internal::kStackTraceMarker << os_stack_trace;
6111   }
6112 
6113   const TestPartResult result =
6114     TestPartResult(result_type, file_name, line_number,
6115                    msg.GetString().c_str());
6116   impl_->GetTestPartResultReporterForCurrentThread()->
6117       ReportTestPartResult(result);
6118 
6119   if (result_type != TestPartResult::kSuccess) {
6120     // gtest_break_on_failure takes precedence over
6121     // gtest_throw_on_failure.  This allows a user to set the latter
6122     // in the code (perhaps in order to use Google Test assertions
6123     // with another testing framework) and specify the former on the
6124     // command line for debugging.
6125     if (GTEST_FLAG(break_on_failure)) {
6126 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6127       // Using DebugBreak on Windows allows gtest to still break into a debugger
6128       // when a failure happens and both the --gtest_break_on_failure and
6129       // the --gtest_catch_exceptions flags are specified.
6130       DebugBreak();
6131 #elif (!defined(__native_client__)) &&            \
6132     ((defined(__clang__) || defined(__GNUC__)) && \
6133      (defined(__x86_64__) || defined(__i386__)))
6134       // with clang/gcc we can achieve the same effect on x86 by invoking int3
6135       asm("int3");
6136 #else
6137       // Dereference NULL through a volatile pointer to prevent the compiler
6138       // from removing. We use this rather than abort() or __builtin_trap() for
6139       // portability: Symbian doesn't implement abort() well, and some debuggers
6140       // don't correctly trap abort().
6141       *static_cast<volatile int*>(NULL) = 1;
6142 #endif  // GTEST_OS_WINDOWS
6143     } else if (GTEST_FLAG(throw_on_failure)) {
6144 #if GTEST_HAS_EXCEPTIONS
6145       throw internal::GoogleTestFailureException(result);
6146 #else
6147       // We cannot call abort() as it generates a pop-up in debug mode
6148       // that cannot be suppressed in VC 7.1 or below.
6149       exit(1);
6150 #endif
6151     }
6152   }
6153 }
6154 
6155 // Adds a TestProperty to the current TestResult object when invoked from
6156 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
6157 // from SetUpTestCase or TearDownTestCase, or to the global property set
6158 // when invoked elsewhere.  If the result already contains a property with
6159 // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)6160 void UnitTest::RecordProperty(const std::string& key,
6161                               const std::string& value) {
6162   impl_->RecordProperty(TestProperty(key, value));
6163 }
6164 
6165 // Runs all tests in this UnitTest object and prints the result.
6166 // Returns 0 if successful, or 1 otherwise.
6167 //
6168 // We don't protect this under mutex_, as we only support calling it
6169 // from the main thread.
Run()6170 int UnitTest::Run() {
6171   const bool in_death_test_child_process =
6172       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
6173 
6174   // Google Test implements this protocol for catching that a test
6175   // program exits before returning control to Google Test:
6176   //
6177   //   1. Upon start, Google Test creates a file whose absolute path
6178   //      is specified by the environment variable
6179   //      TEST_PREMATURE_EXIT_FILE.
6180   //   2. When Google Test has finished its work, it deletes the file.
6181   //
6182   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
6183   // running a Google-Test-based test program and check the existence
6184   // of the file at the end of the test execution to see if it has
6185   // exited prematurely.
6186 
6187   // If we are in the child process of a death test, don't
6188   // create/delete the premature exit file, as doing so is unnecessary
6189   // and will confuse the parent process.  Otherwise, create/delete
6190   // the file upon entering/leaving this function.  If the program
6191   // somehow exits before this function has a chance to return, the
6192   // premature-exit file will be left undeleted, causing a test runner
6193   // that understands the premature-exit-file protocol to report the
6194   // test as having failed.
6195   const internal::ScopedPrematureExitFile premature_exit_file(
6196       in_death_test_child_process ?
6197       NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
6198 
6199   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
6200   // used for the duration of the program.
6201   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
6202 
6203 #if GTEST_OS_WINDOWS
6204   // Either the user wants Google Test to catch exceptions thrown by the
6205   // tests or this is executing in the context of death test child
6206   // process. In either case the user does not want to see pop-up dialogs
6207   // about crashes - they are expected.
6208   if (impl()->catch_exceptions() || in_death_test_child_process) {
6209 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6210     // SetErrorMode doesn't exist on CE.
6211     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6212                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6213 # endif  // !GTEST_OS_WINDOWS_MOBILE
6214 
6215 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
6216     // Death test children can be terminated with _abort().  On Windows,
6217     // _abort() can show a dialog with a warning message.  This forces the
6218     // abort message to go to stderr instead.
6219     _set_error_mode(_OUT_TO_STDERR);
6220 # endif
6221 
6222 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
6223     // In the debug version, Visual Studio pops up a separate dialog
6224     // offering a choice to debug the aborted program. We need to suppress
6225     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
6226     // executed. Google Test will notify the user of any unexpected
6227     // failure via stderr.
6228     //
6229     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
6230     // Users of prior VC versions shall suffer the agony and pain of
6231     // clicking through the countless debug dialogs.
6232     // FIXME: find a way to suppress the abort dialog() in the
6233     // debug mode when compiled with VC 7.1 or lower.
6234     if (!GTEST_FLAG(break_on_failure))
6235       _set_abort_behavior(
6236           0x0,                                    // Clear the following flags:
6237           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
6238 # endif
6239   }
6240 #endif  // GTEST_OS_WINDOWS
6241 
6242   return internal::HandleExceptionsInMethodIfSupported(
6243       impl(),
6244       &internal::UnitTestImpl::RunAllTests,
6245       "auxiliary test code (environments or event listeners)") ? 0 : 1;
6246 }
6247 
6248 // Returns the working directory when the first TEST() or TEST_F() was
6249 // executed.
original_working_dir() const6250 const char* UnitTest::original_working_dir() const {
6251   return impl_->original_working_dir_.c_str();
6252 }
6253 
6254 // Returns the TestCase object for the test that's currently running,
6255 // or NULL if no test is running.
current_test_case() const6256 const TestCase* UnitTest::current_test_case() const
6257     GTEST_LOCK_EXCLUDED_(mutex_) {
6258   internal::MutexLock lock(&mutex_);
6259   return impl_->current_test_case();
6260 }
6261 
6262 // Returns the TestInfo object for the test that's currently running,
6263 // or NULL if no test is running.
current_test_info() const6264 const TestInfo* UnitTest::current_test_info() const
6265     GTEST_LOCK_EXCLUDED_(mutex_) {
6266   internal::MutexLock lock(&mutex_);
6267   return impl_->current_test_info();
6268 }
6269 
6270 // Returns the random seed used at the start of the current test run.
random_seed() const6271 int UnitTest::random_seed() const { return impl_->random_seed(); }
6272 
6273 // Returns ParameterizedTestCaseRegistry object used to keep track of
6274 // value-parameterized tests and instantiate and register them.
6275 internal::ParameterizedTestCaseRegistry&
parameterized_test_registry()6276     UnitTest::parameterized_test_registry()
6277         GTEST_LOCK_EXCLUDED_(mutex_) {
6278   return impl_->parameterized_test_registry();
6279 }
6280 
6281 // Creates an empty UnitTest.
UnitTest()6282 UnitTest::UnitTest() {
6283   impl_ = new internal::UnitTestImpl(this);
6284 }
6285 
6286 // Destructor of UnitTest.
~UnitTest()6287 UnitTest::~UnitTest() {
6288   delete impl_;
6289 }
6290 
6291 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
6292 // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)6293 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
6294     GTEST_LOCK_EXCLUDED_(mutex_) {
6295   internal::MutexLock lock(&mutex_);
6296   impl_->gtest_trace_stack().push_back(trace);
6297 }
6298 
6299 // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()6300 void UnitTest::PopGTestTrace()
6301     GTEST_LOCK_EXCLUDED_(mutex_) {
6302   internal::MutexLock lock(&mutex_);
6303   impl_->gtest_trace_stack().pop_back();
6304 }
6305 
6306 namespace internal {
6307 
UnitTestImpl(UnitTest * parent)6308 UnitTestImpl::UnitTestImpl(UnitTest* parent)
6309     : parent_(parent),
6310       GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
6311       default_global_test_part_result_reporter_(this),
6312       default_per_thread_test_part_result_reporter_(this),
6313       GTEST_DISABLE_MSC_WARNINGS_POP_()
6314       global_test_part_result_repoter_(
6315           &default_global_test_part_result_reporter_),
6316       per_thread_test_part_result_reporter_(
6317           &default_per_thread_test_part_result_reporter_),
6318       parameterized_test_registry_(),
6319       parameterized_tests_registered_(false),
6320       last_death_test_case_(-1),
6321       current_test_case_(NULL),
6322       current_test_info_(NULL),
6323       ad_hoc_test_result_(),
6324       os_stack_trace_getter_(NULL),
6325       post_flag_parse_init_performed_(false),
6326       random_seed_(0),  // Will be overridden by the flag before first use.
6327       random_(0),  // Will be reseeded before first use.
6328       start_timestamp_(0),
6329       elapsed_time_(0),
6330 #if GTEST_HAS_DEATH_TEST
6331       death_test_factory_(new DefaultDeathTestFactory),
6332 #endif
6333       // Will be overridden by the flag before first use.
6334       catch_exceptions_(false) {
6335   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
6336 }
6337 
~UnitTestImpl()6338 UnitTestImpl::~UnitTestImpl() {
6339   // Deletes every TestCase.
6340   ForEach(test_cases_, internal::Delete<TestCase>);
6341 
6342   // Deletes every Environment.
6343   ForEach(environments_, internal::Delete<Environment>);
6344 
6345   delete os_stack_trace_getter_;
6346 }
6347 
6348 // Adds a TestProperty to the current TestResult object when invoked in a
6349 // context of a test, to current test case's ad_hoc_test_result when invoke
6350 // from SetUpTestCase/TearDownTestCase, or to the global property set
6351 // otherwise.  If the result already contains a property with the same key,
6352 // the value will be updated.
RecordProperty(const TestProperty & test_property)6353 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
6354   std::string xml_element;
6355   TestResult* test_result;  // TestResult appropriate for property recording.
6356 
6357   if (current_test_info_ != NULL) {
6358     xml_element = "testcase";
6359     test_result = &(current_test_info_->result_);
6360   } else if (current_test_case_ != NULL) {
6361     xml_element = "testsuite";
6362     test_result = &(current_test_case_->ad_hoc_test_result_);
6363   } else {
6364     xml_element = "testsuites";
6365     test_result = &ad_hoc_test_result_;
6366   }
6367   test_result->RecordProperty(xml_element, test_property);
6368 }
6369 
6370 #if GTEST_HAS_DEATH_TEST
6371 // Disables event forwarding if the control is currently in a death test
6372 // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()6373 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
6374   if (internal_run_death_test_flag_.get() != NULL)
6375     listeners()->SuppressEventForwarding();
6376 }
6377 #endif  // GTEST_HAS_DEATH_TEST
6378 
6379 // Initializes event listeners performing XML output as specified by
6380 // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()6381 void UnitTestImpl::ConfigureXmlOutput() {
6382   const std::string& output_format = UnitTestOptions::GetOutputFormat();
6383   if (output_format == "xml") {
6384     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
6385         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6386   } else if (output_format == "json") {
6387     listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
6388         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6389   } else if (output_format != "") {
6390     GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
6391                         << output_format << "\" ignored.";
6392   }
6393 }
6394 
6395 #if GTEST_CAN_STREAM_RESULTS_
6396 // Initializes event listeners for streaming test results in string form.
6397 // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()6398 void UnitTestImpl::ConfigureStreamingOutput() {
6399   const std::string& target = GTEST_FLAG(stream_result_to);
6400   if (!target.empty()) {
6401     const size_t pos = target.find(':');
6402     if (pos != std::string::npos) {
6403       listeners()->Append(new StreamingListener(target.substr(0, pos),
6404                                                 target.substr(pos+1)));
6405     } else {
6406       GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
6407                           << "\" ignored.";
6408     }
6409   }
6410 }
6411 #endif  // GTEST_CAN_STREAM_RESULTS_
6412 
6413 // Performs initialization dependent upon flag values obtained in
6414 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
6415 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
6416 // this function is also called from RunAllTests.  Since this function can be
6417 // called more than once, it has to be idempotent.
PostFlagParsingInit()6418 void UnitTestImpl::PostFlagParsingInit() {
6419   // Ensures that this function does not execute more than once.
6420   if (!post_flag_parse_init_performed_) {
6421     post_flag_parse_init_performed_ = true;
6422 
6423 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6424     // Register to send notifications about key process state changes.
6425     listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
6426 #endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6427 
6428 #if GTEST_HAS_DEATH_TEST
6429     InitDeathTestSubprocessControlInfo();
6430     SuppressTestEventsIfInSubprocess();
6431 #endif  // GTEST_HAS_DEATH_TEST
6432 
6433     // Registers parameterized tests. This makes parameterized tests
6434     // available to the UnitTest reflection API without running
6435     // RUN_ALL_TESTS.
6436     RegisterParameterizedTests();
6437 
6438     // Configures listeners for XML output. This makes it possible for users
6439     // to shut down the default XML output before invoking RUN_ALL_TESTS.
6440     ConfigureXmlOutput();
6441 
6442 #if GTEST_CAN_STREAM_RESULTS_
6443     // Configures listeners for streaming test results to the specified server.
6444     ConfigureStreamingOutput();
6445 #endif  // GTEST_CAN_STREAM_RESULTS_
6446 
6447 #if GTEST_HAS_ABSL
6448     if (GTEST_FLAG(install_failure_signal_handler)) {
6449       absl::FailureSignalHandlerOptions options;
6450       absl::InstallFailureSignalHandler(options);
6451     }
6452 #endif  // GTEST_HAS_ABSL
6453   }
6454 }
6455 
6456 // A predicate that checks the name of a TestCase against a known
6457 // value.
6458 //
6459 // This is used for implementation of the UnitTest class only.  We put
6460 // it in the anonymous namespace to prevent polluting the outer
6461 // namespace.
6462 //
6463 // TestCaseNameIs is copyable.
6464 class TestCaseNameIs {
6465  public:
6466   // Constructor.
TestCaseNameIs(const std::string & name)6467   explicit TestCaseNameIs(const std::string& name)
6468       : name_(name) {}
6469 
6470   // Returns true iff the name of test_case matches name_.
operator ()(const TestCase * test_case) const6471   bool operator()(const TestCase* test_case) const {
6472     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
6473   }
6474 
6475  private:
6476   std::string name_;
6477 };
6478 
6479 // Finds and returns a TestCase with the given name.  If one doesn't
6480 // exist, creates one and returns it.  It's the CALLER'S
6481 // RESPONSIBILITY to ensure that this function is only called WHEN THE
6482 // TESTS ARE NOT SHUFFLED.
6483 //
6484 // Arguments:
6485 //
6486 //   test_case_name: name of the test case
6487 //   type_param:     the name of the test case's type parameter, or NULL if
6488 //                   this is not a typed or a type-parameterized test case.
6489 //   set_up_tc:      pointer to the function that sets up the test case
6490 //   tear_down_tc:   pointer to the function that tears down the test case
GetTestCase(const char * test_case_name,const char * type_param,Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc)6491 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
6492                                     const char* type_param,
6493                                     Test::SetUpTestCaseFunc set_up_tc,
6494                                     Test::TearDownTestCaseFunc tear_down_tc) {
6495   // Can we find a TestCase with the given name?
6496   const std::vector<TestCase*>::const_reverse_iterator test_case =
6497       std::find_if(test_cases_.rbegin(), test_cases_.rend(),
6498                    TestCaseNameIs(test_case_name));
6499 
6500   if (test_case != test_cases_.rend())
6501     return *test_case;
6502 
6503   // No.  Let's create one.
6504   TestCase* const new_test_case =
6505       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
6506 
6507   // Is this a death test case?
6508   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
6509                                                kDeathTestCaseFilter)) {
6510     // Yes.  Inserts the test case after the last death test case
6511     // defined so far.  This only works when the test cases haven't
6512     // been shuffled.  Otherwise we may end up running a death test
6513     // after a non-death test.
6514     ++last_death_test_case_;
6515     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
6516                        new_test_case);
6517   } else {
6518     // No.  Appends to the end of the list.
6519     test_cases_.push_back(new_test_case);
6520   }
6521 
6522   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
6523   return new_test_case;
6524 }
6525 
6526 // Helpers for setting up / tearing down the given environment.  They
6527 // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)6528 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)6529 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
6530 
6531 // Runs all tests in this UnitTest object, prints the result, and
6532 // returns true if all tests are successful.  If any exception is
6533 // thrown during a test, the test is considered to be failed, but the
6534 // rest of the tests will still be run.
6535 //
6536 // When parameterized tests are enabled, it expands and registers
6537 // parameterized tests first in RegisterParameterizedTests().
6538 // All other functions called from RunAllTests() may safely assume that
6539 // parameterized tests are ready to be counted and run.
RunAllTests()6540 bool UnitTestImpl::RunAllTests() {
6541   // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
6542   const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
6543 
6544   // Do not run any test if the --help flag was specified.
6545   if (g_help_flag)
6546     return true;
6547 
6548   // Repeats the call to the post-flag parsing initialization in case the
6549   // user didn't call InitGoogleTest.
6550   PostFlagParsingInit();
6551 
6552   // Even if sharding is not on, test runners may want to use the
6553   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6554   // protocol.
6555   internal::WriteToShardStatusFileIfNeeded();
6556 
6557   // True iff we are in a subprocess for running a thread-safe-style
6558   // death test.
6559   bool in_subprocess_for_death_test = false;
6560 
6561 #if GTEST_HAS_DEATH_TEST
6562   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
6563 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6564   if (in_subprocess_for_death_test) {
6565     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6566   }
6567 # endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6568 #endif  // GTEST_HAS_DEATH_TEST
6569 
6570   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6571                                         in_subprocess_for_death_test);
6572 
6573   // Compares the full test names with the filter to decide which
6574   // tests to run.
6575   const bool has_tests_to_run = FilterTests(should_shard
6576                                               ? HONOR_SHARDING_PROTOCOL
6577                                               : IGNORE_SHARDING_PROTOCOL) > 0;
6578 
6579   // Lists the tests and exits if the --gtest_list_tests flag was specified.
6580   if (GTEST_FLAG(list_tests)) {
6581     // This must be called *after* FilterTests() has been called.
6582     ListTestsMatchingFilter();
6583     return true;
6584   }
6585 
6586   random_seed_ = GTEST_FLAG(shuffle) ?
6587       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6588 
6589   // True iff at least one test has failed.
6590   bool failed = false;
6591 
6592   TestEventListener* repeater = listeners()->repeater();
6593 
6594   start_timestamp_ = GetTimeInMillis();
6595   repeater->OnTestProgramStart(*parent_);
6596 
6597   // How many times to repeat the tests?  We don't want to repeat them
6598   // when we are inside the subprocess of a death test.
6599   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6600   // Repeats forever if the repeat count is negative.
6601   const bool forever = repeat < 0;
6602   for (int i = 0; forever || i != repeat; i++) {
6603     // We want to preserve failures generated by ad-hoc test
6604     // assertions executed before RUN_ALL_TESTS().
6605     ClearNonAdHocTestResult();
6606 
6607     const TimeInMillis start = GetTimeInMillis();
6608 
6609     // Shuffles test cases and tests if requested.
6610     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6611       random()->Reseed(random_seed_);
6612       // This should be done before calling OnTestIterationStart(),
6613       // such that a test event listener can see the actual test order
6614       // in the event.
6615       ShuffleTests();
6616     }
6617 
6618     // Tells the unit test event listeners that the tests are about to start.
6619     repeater->OnTestIterationStart(*parent_, i);
6620 
6621     // Runs each test case if there is at least one test to run.
6622     if (has_tests_to_run) {
6623       // Sets up all environments beforehand.
6624       repeater->OnEnvironmentsSetUpStart(*parent_);
6625       ForEach(environments_, SetUpEnvironment);
6626       repeater->OnEnvironmentsSetUpEnd(*parent_);
6627 
6628       // Runs the tests only if there was no fatal failure during global
6629       // set-up.
6630       if (!Test::HasFatalFailure()) {
6631         for (int test_index = 0; test_index < total_test_case_count();
6632              test_index++) {
6633           GetMutableTestCase(test_index)->Run();
6634         }
6635       }
6636 
6637       // Tears down all environments in reverse order afterwards.
6638       repeater->OnEnvironmentsTearDownStart(*parent_);
6639       std::for_each(environments_.rbegin(), environments_.rend(),
6640                     TearDownEnvironment);
6641       repeater->OnEnvironmentsTearDownEnd(*parent_);
6642     }
6643 
6644     elapsed_time_ = GetTimeInMillis() - start;
6645 
6646     // Tells the unit test event listener that the tests have just finished.
6647     repeater->OnTestIterationEnd(*parent_, i);
6648 
6649     // Gets the result and clears it.
6650     if (!Passed()) {
6651       failed = true;
6652     }
6653 
6654     // Restores the original test order after the iteration.  This
6655     // allows the user to quickly repro a failure that happens in the
6656     // N-th iteration without repeating the first (N - 1) iterations.
6657     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6658     // case the user somehow changes the value of the flag somewhere
6659     // (it's always safe to unshuffle the tests).
6660     UnshuffleTests();
6661 
6662     if (GTEST_FLAG(shuffle)) {
6663       // Picks a new random seed for each iteration.
6664       random_seed_ = GetNextRandomSeed(random_seed_);
6665     }
6666   }
6667 
6668   repeater->OnTestProgramEnd(*parent_);
6669 
6670   if (!gtest_is_initialized_before_run_all_tests) {
6671     ColoredPrintf(
6672         COLOR_RED,
6673         "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
6674         "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
6675         "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
6676         " will start to enforce the valid usage. "
6677         "Please fix it ASAP, or IT WILL START TO FAIL.\n");  // NOLINT
6678 #if GTEST_FOR_GOOGLE_
6679     ColoredPrintf(COLOR_RED,
6680                   "For more details, see http://wiki/Main/ValidGUnitMain.\n");
6681 #endif  // GTEST_FOR_GOOGLE_
6682   }
6683 
6684   return !failed;
6685 }
6686 
6687 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6688 // if the variable is present. If a file already exists at this location, this
6689 // function will write over it. If the variable is present, but the file cannot
6690 // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()6691 void WriteToShardStatusFileIfNeeded() {
6692   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6693   if (test_shard_file != NULL) {
6694     FILE* const file = posix::FOpen(test_shard_file, "w");
6695     if (file == NULL) {
6696       ColoredPrintf(COLOR_RED,
6697                     "Could not write to the test shard status file \"%s\" "
6698                     "specified by the %s environment variable.\n",
6699                     test_shard_file, kTestShardStatusFile);
6700       fflush(stdout);
6701       exit(EXIT_FAILURE);
6702     }
6703     fclose(file);
6704   }
6705 }
6706 
6707 // Checks whether sharding is enabled by examining the relevant
6708 // environment variable values. If the variables are present,
6709 // but inconsistent (i.e., shard_index >= total_shards), prints
6710 // an error and exits. If in_subprocess_for_death_test, sharding is
6711 // disabled because it must only be applied to the original test
6712 // 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)6713 bool ShouldShard(const char* total_shards_env,
6714                  const char* shard_index_env,
6715                  bool in_subprocess_for_death_test) {
6716   if (in_subprocess_for_death_test) {
6717     return false;
6718   }
6719 
6720   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6721   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6722 
6723   if (total_shards == -1 && shard_index == -1) {
6724     return false;
6725   } else if (total_shards == -1 && shard_index != -1) {
6726     const Message msg = Message()
6727       << "Invalid environment variables: you have "
6728       << kTestShardIndex << " = " << shard_index
6729       << ", but have left " << kTestTotalShards << " unset.\n";
6730     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6731     fflush(stdout);
6732     exit(EXIT_FAILURE);
6733   } else if (total_shards != -1 && shard_index == -1) {
6734     const Message msg = Message()
6735       << "Invalid environment variables: you have "
6736       << kTestTotalShards << " = " << total_shards
6737       << ", but have left " << kTestShardIndex << " unset.\n";
6738     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6739     fflush(stdout);
6740     exit(EXIT_FAILURE);
6741   } else if (shard_index < 0 || shard_index >= total_shards) {
6742     const Message msg = Message()
6743       << "Invalid environment variables: we require 0 <= "
6744       << kTestShardIndex << " < " << kTestTotalShards
6745       << ", but you have " << kTestShardIndex << "=" << shard_index
6746       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
6747     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6748     fflush(stdout);
6749     exit(EXIT_FAILURE);
6750   }
6751 
6752   return total_shards > 1;
6753 }
6754 
6755 // Parses the environment variable var as an Int32. If it is unset,
6756 // returns default_val. If it is not an Int32, prints an error
6757 // and aborts.
Int32FromEnvOrDie(const char * var,Int32 default_val)6758 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6759   const char* str_val = posix::GetEnv(var);
6760   if (str_val == NULL) {
6761     return default_val;
6762   }
6763 
6764   Int32 result;
6765   if (!ParseInt32(Message() << "The value of environment variable " << var,
6766                   str_val, &result)) {
6767     exit(EXIT_FAILURE);
6768   }
6769   return result;
6770 }
6771 
6772 // Given the total number of shards, the shard index, and the test id,
6773 // returns true iff the test should be run on this shard. The test id is
6774 // some arbitrary but unique non-negative integer assigned to each test
6775 // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)6776 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6777   return (test_id % total_shards) == shard_index;
6778 }
6779 
6780 // Compares the name of each test with the user-specified filter to
6781 // decide whether the test should be run, then records the result in
6782 // each TestCase and TestInfo object.
6783 // If shard_tests == true, further filters tests based on sharding
6784 // variables in the environment - see
6785 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
6786 // . Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)6787 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6788   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6789       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6790   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6791       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6792 
6793   // num_runnable_tests are the number of tests that will
6794   // run across all shards (i.e., match filter and are not disabled).
6795   // num_selected_tests are the number of tests to be run on
6796   // this shard.
6797   int num_runnable_tests = 0;
6798   int num_selected_tests = 0;
6799   for (size_t i = 0; i < test_cases_.size(); i++) {
6800     TestCase* const test_case = test_cases_[i];
6801     const std::string &test_case_name = test_case->name();
6802     test_case->set_should_run(false);
6803 
6804     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6805       TestInfo* const test_info = test_case->test_info_list()[j];
6806       const std::string test_name(test_info->name());
6807       // A test is disabled if test case name or test name matches
6808       // kDisableTestFilter.
6809       const bool is_disabled =
6810           internal::UnitTestOptions::MatchesFilter(test_case_name,
6811                                                    kDisableTestFilter) ||
6812           internal::UnitTestOptions::MatchesFilter(test_name,
6813                                                    kDisableTestFilter);
6814       test_info->is_disabled_ = is_disabled;
6815 
6816       const bool matches_filter =
6817           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
6818                                                        test_name);
6819       test_info->matches_filter_ = matches_filter;
6820 
6821       const bool is_runnable =
6822           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6823           matches_filter;
6824 
6825       const bool is_in_another_shard =
6826           shard_tests != IGNORE_SHARDING_PROTOCOL &&
6827           !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6828       test_info->is_in_another_shard_ = is_in_another_shard;
6829       const bool is_selected = is_runnable && !is_in_another_shard;
6830 
6831       num_runnable_tests += is_runnable;
6832       num_selected_tests += is_selected;
6833 
6834       test_info->should_run_ = is_selected;
6835       test_case->set_should_run(test_case->should_run() || is_selected);
6836     }
6837   }
6838   return num_selected_tests;
6839 }
6840 
6841 // Prints the given C-string on a single line by replacing all '\n'
6842 // characters with string "\\n".  If the output takes more than
6843 // max_length characters, only prints the first max_length characters
6844 // and "...".
PrintOnOneLine(const char * str,int max_length)6845 static void PrintOnOneLine(const char* str, int max_length) {
6846   if (str != NULL) {
6847     for (int i = 0; *str != '\0'; ++str) {
6848       if (i >= max_length) {
6849         printf("...");
6850         break;
6851       }
6852       if (*str == '\n') {
6853         printf("\\n");
6854         i += 2;
6855       } else {
6856         printf("%c", *str);
6857         ++i;
6858       }
6859     }
6860   }
6861 }
6862 
6863 // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()6864 void UnitTestImpl::ListTestsMatchingFilter() {
6865   // Print at most this many characters for each type/value parameter.
6866   const int kMaxParamLength = 250;
6867 
6868   for (size_t i = 0; i < test_cases_.size(); i++) {
6869     const TestCase* const test_case = test_cases_[i];
6870     bool printed_test_case_name = false;
6871 
6872     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6873       const TestInfo* const test_info =
6874           test_case->test_info_list()[j];
6875       if (test_info->matches_filter_) {
6876         if (!printed_test_case_name) {
6877           printed_test_case_name = true;
6878           printf("%s.", test_case->name());
6879           if (test_case->type_param() != NULL) {
6880             printf("  # %s = ", kTypeParamLabel);
6881             // We print the type parameter on a single line to make
6882             // the output easy to parse by a program.
6883             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6884           }
6885           printf("\n");
6886         }
6887         printf("  %s", test_info->name());
6888         if (test_info->value_param() != NULL) {
6889           printf("  # %s = ", kValueParamLabel);
6890           // We print the value parameter on a single line to make the
6891           // output easy to parse by a program.
6892           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6893         }
6894         printf("\n");
6895       }
6896     }
6897   }
6898   fflush(stdout);
6899   const std::string& output_format = UnitTestOptions::GetOutputFormat();
6900   if (output_format == "xml" || output_format == "json") {
6901     FILE* fileout = OpenFileForWriting(
6902         UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
6903     std::stringstream stream;
6904     if (output_format == "xml") {
6905       XmlUnitTestResultPrinter(
6906           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6907           .PrintXmlTestsList(&stream, test_cases_);
6908     } else if (output_format == "json") {
6909       JsonUnitTestResultPrinter(
6910           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6911           .PrintJsonTestList(&stream, test_cases_);
6912     }
6913     fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
6914     fclose(fileout);
6915   }
6916 }
6917 
6918 // Sets the OS stack trace getter.
6919 //
6920 // Does nothing if the input and the current OS stack trace getter are
6921 // the same; otherwise, deletes the old getter and makes the input the
6922 // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)6923 void UnitTestImpl::set_os_stack_trace_getter(
6924     OsStackTraceGetterInterface* getter) {
6925   if (os_stack_trace_getter_ != getter) {
6926     delete os_stack_trace_getter_;
6927     os_stack_trace_getter_ = getter;
6928   }
6929 }
6930 
6931 // Returns the current OS stack trace getter if it is not NULL;
6932 // otherwise, creates an OsStackTraceGetter, makes it the current
6933 // getter, and returns it.
os_stack_trace_getter()6934 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6935   if (os_stack_trace_getter_ == NULL) {
6936 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6937     os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
6938 #else
6939     os_stack_trace_getter_ = new OsStackTraceGetter;
6940 #endif  // GTEST_OS_STACK_TRACE_GETTER_
6941   }
6942 
6943   return os_stack_trace_getter_;
6944 }
6945 
6946 // Returns the most specific TestResult currently running.
current_test_result()6947 TestResult* UnitTestImpl::current_test_result() {
6948   if (current_test_info_ != NULL) {
6949     return &current_test_info_->result_;
6950   }
6951   if (current_test_case_ != NULL) {
6952     return &current_test_case_->ad_hoc_test_result_;
6953   }
6954   return &ad_hoc_test_result_;
6955 }
6956 
6957 // Shuffles all test cases, and the tests within each test case,
6958 // making sure that death tests are still run first.
ShuffleTests()6959 void UnitTestImpl::ShuffleTests() {
6960   // Shuffles the death test cases.
6961   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6962 
6963   // Shuffles the non-death test cases.
6964   ShuffleRange(random(), last_death_test_case_ + 1,
6965                static_cast<int>(test_cases_.size()), &test_case_indices_);
6966 
6967   // Shuffles the tests inside each test case.
6968   for (size_t i = 0; i < test_cases_.size(); i++) {
6969     test_cases_[i]->ShuffleTests(random());
6970   }
6971 }
6972 
6973 // Restores the test cases and tests to their order before the first shuffle.
UnshuffleTests()6974 void UnitTestImpl::UnshuffleTests() {
6975   for (size_t i = 0; i < test_cases_.size(); i++) {
6976     // Unshuffles the tests in each test case.
6977     test_cases_[i]->UnshuffleTests();
6978     // Resets the index of each test case.
6979     test_case_indices_[i] = static_cast<int>(i);
6980   }
6981 }
6982 
6983 // Returns the current OS stack trace as an std::string.
6984 //
6985 // The maximum number of stack frames to be included is specified by
6986 // the gtest_stack_trace_depth flag.  The skip_count parameter
6987 // specifies the number of top frames to be skipped, which doesn't
6988 // count against the number of frames to be included.
6989 //
6990 // For example, if Foo() calls Bar(), which in turn calls
6991 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6992 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)6993 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
6994                                             int skip_count) {
6995   // We pass skip_count + 1 to skip this wrapper function in addition
6996   // to what the user really wants to skip.
6997   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6998 }
6999 
7000 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
7001 // suppress unreachable code warnings.
7002 namespace {
7003 class ClassUniqueToAlwaysTrue {};
7004 }
7005 
IsTrue(bool condition)7006 bool IsTrue(bool condition) { return condition; }
7007 
AlwaysTrue()7008 bool AlwaysTrue() {
7009 #if GTEST_HAS_EXCEPTIONS
7010   // This condition is always false so AlwaysTrue() never actually throws,
7011   // but it makes the compiler think that it may throw.
7012   if (IsTrue(false))
7013     throw ClassUniqueToAlwaysTrue();
7014 #endif  // GTEST_HAS_EXCEPTIONS
7015   return true;
7016 }
7017 
7018 // If *pstr starts with the given prefix, modifies *pstr to be right
7019 // past the prefix and returns true; otherwise leaves *pstr unchanged
7020 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)7021 bool SkipPrefix(const char* prefix, const char** pstr) {
7022   const size_t prefix_len = strlen(prefix);
7023   if (strncmp(*pstr, prefix, prefix_len) == 0) {
7024     *pstr += prefix_len;
7025     return true;
7026   }
7027   return false;
7028 }
7029 
7030 // Parses a string as a command line flag.  The string should have
7031 // the format "--flag=value".  When def_optional is true, the "=value"
7032 // part can be omitted.
7033 //
7034 // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)7035 static const char* ParseFlagValue(const char* str, const char* flag,
7036                                   bool def_optional) {
7037   // str and flag must not be NULL.
7038   if (str == NULL || flag == NULL) return NULL;
7039 
7040   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
7041   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
7042   const size_t flag_len = flag_str.length();
7043   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
7044 
7045   // Skips the flag name.
7046   const char* flag_end = str + flag_len;
7047 
7048   // When def_optional is true, it's OK to not have a "=value" part.
7049   if (def_optional && (flag_end[0] == '\0')) {
7050     return flag_end;
7051   }
7052 
7053   // If def_optional is true and there are more characters after the
7054   // flag name, or if def_optional is false, there must be a '=' after
7055   // the flag name.
7056   if (flag_end[0] != '=') return NULL;
7057 
7058   // Returns the string after "=".
7059   return flag_end + 1;
7060 }
7061 
7062 // Parses a string for a bool flag, in the form of either
7063 // "--flag=value" or "--flag".
7064 //
7065 // In the former case, the value is taken as true as long as it does
7066 // not start with '0', 'f', or 'F'.
7067 //
7068 // In the latter case, the value is taken as true.
7069 //
7070 // On success, stores the value of the flag in *value, and returns
7071 // true.  On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)7072 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
7073   // Gets the value of the flag as a string.
7074   const char* const value_str = ParseFlagValue(str, flag, true);
7075 
7076   // Aborts if the parsing failed.
7077   if (value_str == NULL) return false;
7078 
7079   // Converts the string value to a bool.
7080   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
7081   return true;
7082 }
7083 
7084 // Parses a string for an Int32 flag, in the form of
7085 // "--flag=value".
7086 //
7087 // On success, stores the value of the flag in *value, and returns
7088 // true.  On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,Int32 * value)7089 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
7090   // Gets the value of the flag as a string.
7091   const char* const value_str = ParseFlagValue(str, flag, false);
7092 
7093   // Aborts if the parsing failed.
7094   if (value_str == NULL) return false;
7095 
7096   // Sets *value to the value of the flag.
7097   return ParseInt32(Message() << "The value of flag --" << flag,
7098                     value_str, value);
7099 }
7100 
7101 // Parses a string for a string flag, in the form of
7102 // "--flag=value".
7103 //
7104 // On success, stores the value of the flag in *value, and returns
7105 // true.  On failure, returns false without changing *value.
7106 template <typename String>
ParseStringFlag(const char * str,const char * flag,String * value)7107 static bool ParseStringFlag(const char* str, const char* flag, String* value) {
7108   // Gets the value of the flag as a string.
7109   const char* const value_str = ParseFlagValue(str, flag, false);
7110 
7111   // Aborts if the parsing failed.
7112   if (value_str == NULL) return false;
7113 
7114   // Sets *value to the value of the flag.
7115   *value = value_str;
7116   return true;
7117 }
7118 
7119 // Determines whether a string has a prefix that Google Test uses for its
7120 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
7121 // If Google Test detects that a command line flag has its prefix but is not
7122 // recognized, it will print its help message. Flags starting with
7123 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
7124 // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)7125 static bool HasGoogleTestFlagPrefix(const char* str) {
7126   return (SkipPrefix("--", &str) ||
7127           SkipPrefix("-", &str) ||
7128           SkipPrefix("/", &str)) &&
7129          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
7130          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
7131           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
7132 }
7133 
7134 // Prints a string containing code-encoded text.  The following escape
7135 // sequences can be used in the string to control the text color:
7136 //
7137 //   @@    prints a single '@' character.
7138 //   @R    changes the color to red.
7139 //   @G    changes the color to green.
7140 //   @Y    changes the color to yellow.
7141 //   @D    changes to the default terminal text color.
7142 //
7143 // FIXME: Write tests for this once we add stdout
7144 // capturing to Google Test.
PrintColorEncoded(const char * str)7145 static void PrintColorEncoded(const char* str) {
7146   GTestColor color = COLOR_DEFAULT;  // The current color.
7147 
7148   // Conceptually, we split the string into segments divided by escape
7149   // sequences.  Then we print one segment at a time.  At the end of
7150   // each iteration, the str pointer advances to the beginning of the
7151   // next segment.
7152   for (;;) {
7153     const char* p = strchr(str, '@');
7154     if (p == NULL) {
7155       ColoredPrintf(color, "%s", str);
7156       return;
7157     }
7158 
7159     ColoredPrintf(color, "%s", std::string(str, p).c_str());
7160 
7161     const char ch = p[1];
7162     str = p + 2;
7163     if (ch == '@') {
7164       ColoredPrintf(color, "@");
7165     } else if (ch == 'D') {
7166       color = COLOR_DEFAULT;
7167     } else if (ch == 'R') {
7168       color = COLOR_RED;
7169     } else if (ch == 'G') {
7170       color = COLOR_GREEN;
7171     } else if (ch == 'Y') {
7172       color = COLOR_YELLOW;
7173     } else {
7174       --str;
7175     }
7176   }
7177 }
7178 
7179 static const char kColorEncodedHelpMessage[] =
7180 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
7181 "following command line flags to control its behavior:\n"
7182 "\n"
7183 "Test Selection:\n"
7184 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
7185 "      List the names of all tests instead of running them. The name of\n"
7186 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
7187 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
7188     "[@G-@YNEGATIVE_PATTERNS]@D\n"
7189 "      Run only the tests whose name matches one of the positive patterns but\n"
7190 "      none of the negative patterns. '?' matches any single character; '*'\n"
7191 "      matches any substring; ':' separates two patterns.\n"
7192 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
7193 "      Run all disabled tests too.\n"
7194 "\n"
7195 "Test Execution:\n"
7196 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
7197 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
7198 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
7199 "      Randomize tests' orders on every iteration.\n"
7200 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
7201 "      Random number seed to use for shuffling test orders (between 1 and\n"
7202 "      99999, or 0 to use a seed based on the current time).\n"
7203 "\n"
7204 "Test Output:\n"
7205 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
7206 "      Enable/disable colored output. The default is @Gauto@D.\n"
7207 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
7208 "      Don't print the elapsed time of each test.\n"
7209 "  @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
7210     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
7211 "      Generate a JSON or XML report in the given directory or with the given\n"
7212 "      file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
7213 # if GTEST_CAN_STREAM_RESULTS_
7214 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
7215 "      Stream test results to the given server.\n"
7216 # endif  // GTEST_CAN_STREAM_RESULTS_
7217 "\n"
7218 "Assertion Behavior:\n"
7219 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7220 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
7221 "      Set the default death test style.\n"
7222 # endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7223 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
7224 "      Turn assertion failures into debugger break-points.\n"
7225 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
7226 "      Turn assertion failures into C++ exceptions for use by an external\n"
7227 "      test framework.\n"
7228 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
7229 "      Do not report exceptions as test failures. Instead, allow them\n"
7230 "      to crash the program or throw a pop-up (on Windows).\n"
7231 "\n"
7232 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
7233     "the corresponding\n"
7234 "environment variable of a flag (all letters in upper-case). For example, to\n"
7235 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
7236     "color=no@D or set\n"
7237 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
7238 "\n"
7239 "For more information, please read the " GTEST_NAME_ " documentation at\n"
7240 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
7241 "(not one in your own code or tests), please report it to\n"
7242 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
7243 
ParseGoogleTestFlag(const char * const arg)7244 static bool ParseGoogleTestFlag(const char* const arg) {
7245   return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7246                        &GTEST_FLAG(also_run_disabled_tests)) ||
7247       ParseBoolFlag(arg, kBreakOnFailureFlag,
7248                     &GTEST_FLAG(break_on_failure)) ||
7249       ParseBoolFlag(arg, kCatchExceptionsFlag,
7250                     &GTEST_FLAG(catch_exceptions)) ||
7251       ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
7252       ParseStringFlag(arg, kDeathTestStyleFlag,
7253                       &GTEST_FLAG(death_test_style)) ||
7254       ParseBoolFlag(arg, kDeathTestUseFork,
7255                     &GTEST_FLAG(death_test_use_fork)) ||
7256       ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
7257       ParseStringFlag(arg, kInternalRunDeathTestFlag,
7258                       &GTEST_FLAG(internal_run_death_test)) ||
7259       ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
7260       ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
7261       ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
7262       ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
7263       ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
7264       ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
7265       ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
7266       ParseInt32Flag(arg, kStackTraceDepthFlag,
7267                      &GTEST_FLAG(stack_trace_depth)) ||
7268       ParseStringFlag(arg, kStreamResultToFlag,
7269                       &GTEST_FLAG(stream_result_to)) ||
7270       ParseBoolFlag(arg, kThrowOnFailureFlag,
7271                     &GTEST_FLAG(throw_on_failure));
7272 }
7273 
7274 #if GTEST_USE_OWN_FLAGFILE_FLAG_
LoadFlagsFromFile(const std::string & path)7275 static void LoadFlagsFromFile(const std::string& path) {
7276   FILE* flagfile = posix::FOpen(path.c_str(), "r");
7277   if (!flagfile) {
7278     GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
7279                       << "\"";
7280   }
7281   std::string contents(ReadEntireFile(flagfile));
7282   posix::FClose(flagfile);
7283   std::vector<std::string> lines;
7284   SplitString(contents, '\n', &lines);
7285   for (size_t i = 0; i < lines.size(); ++i) {
7286     if (lines[i].empty())
7287       continue;
7288     if (!ParseGoogleTestFlag(lines[i].c_str()))
7289       g_help_flag = true;
7290   }
7291 }
7292 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
7293 
7294 // Parses the command line for Google Test flags, without initializing
7295 // other parts of Google Test.  The type parameter CharType can be
7296 // instantiated to either char or wchar_t.
7297 template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)7298 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
7299   for (int i = 1; i < *argc; i++) {
7300     const std::string arg_string = StreamableToString(argv[i]);
7301     const char* const arg = arg_string.c_str();
7302 
7303     using internal::ParseBoolFlag;
7304     using internal::ParseInt32Flag;
7305     using internal::ParseStringFlag;
7306 
7307     bool remove_flag = false;
7308     if (ParseGoogleTestFlag(arg)) {
7309       remove_flag = true;
7310 #if GTEST_USE_OWN_FLAGFILE_FLAG_
7311     } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
7312       LoadFlagsFromFile(GTEST_FLAG(flagfile));
7313       remove_flag = true;
7314 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
7315     } else if (arg_string == "--help" || arg_string == "-h" ||
7316                arg_string == "-?" || arg_string == "/?" ||
7317                HasGoogleTestFlagPrefix(arg)) {
7318       // Both help flag and unrecognized Google Test flags (excluding
7319       // internal ones) trigger help display.
7320       g_help_flag = true;
7321     }
7322 
7323     if (remove_flag) {
7324       // Shift the remainder of the argv list left by one.  Note
7325       // that argv has (*argc + 1) elements, the last one always being
7326       // NULL.  The following loop moves the trailing NULL element as
7327       // well.
7328       for (int j = i; j != *argc; j++) {
7329         argv[j] = argv[j + 1];
7330       }
7331 
7332       // Decrements the argument count.
7333       (*argc)--;
7334 
7335       // We also need to decrement the iterator as we just removed
7336       // an element.
7337       i--;
7338     }
7339   }
7340 
7341   if (g_help_flag) {
7342     // We print the help here instead of in RUN_ALL_TESTS(), as the
7343     // latter may not be called at all if the user is using Google
7344     // Test with another testing framework.
7345     PrintColorEncoded(kColorEncodedHelpMessage);
7346   }
7347 }
7348 
7349 // Parses the command line for Google Test flags, without initializing
7350 // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)7351 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
7352   ParseGoogleTestFlagsOnlyImpl(argc, argv);
7353 
7354   // Fix the value of *_NSGetArgc() on macOS, but iff
7355   // *_NSGetArgv() == argv
7356   // Only applicable to char** version of argv
7357 #if GTEST_OS_MAC
7358 #ifndef GTEST_OS_IOS
7359   if (*_NSGetArgv() == argv) {
7360     *_NSGetArgc() = *argc;
7361   }
7362 #endif
7363 #endif
7364 }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)7365 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
7366   ParseGoogleTestFlagsOnlyImpl(argc, argv);
7367 }
7368 
7369 // The internal implementation of InitGoogleTest().
7370 //
7371 // The type parameter CharType can be instantiated to either char or
7372 // wchar_t.
7373 template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)7374 void InitGoogleTestImpl(int* argc, CharType** argv) {
7375   // We don't want to run the initialization code twice.
7376   if (GTestIsInitialized()) return;
7377 
7378   if (*argc <= 0) return;
7379 
7380   g_argvs.clear();
7381   for (int i = 0; i != *argc; i++) {
7382     g_argvs.push_back(StreamableToString(argv[i]));
7383   }
7384 
7385 #if GTEST_HAS_ABSL
7386   absl::InitializeSymbolizer(g_argvs[0].c_str());
7387 #endif  // GTEST_HAS_ABSL
7388 
7389   ParseGoogleTestFlagsOnly(argc, argv);
7390   GetUnitTestImpl()->PostFlagParsingInit();
7391 }
7392 
7393 }  // namespace internal
7394 
7395 // Initializes Google Test.  This must be called before calling
7396 // RUN_ALL_TESTS().  In particular, it parses a command line for the
7397 // flags that Google Test recognizes.  Whenever a Google Test flag is
7398 // seen, it is removed from argv, and *argc is decremented.
7399 //
7400 // No value is returned.  Instead, the Google Test flag variables are
7401 // updated.
7402 //
7403 // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)7404 void InitGoogleTest(int* argc, char** argv) {
7405 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7406   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7407 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7408   internal::InitGoogleTestImpl(argc, argv);
7409 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7410 }
7411 
7412 // This overloaded version can be used in Windows programs compiled in
7413 // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)7414 void InitGoogleTest(int* argc, wchar_t** argv) {
7415 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7416   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7417 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7418   internal::InitGoogleTestImpl(argc, argv);
7419 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7420 }
7421 
TempDir()7422 std::string TempDir() {
7423 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
7424   return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
7425 #endif
7426 
7427 #if GTEST_OS_WINDOWS_MOBILE
7428   return "\\temp\\";
7429 #elif GTEST_OS_WINDOWS
7430   const char* temp_dir = internal::posix::GetEnv("TEMP");
7431   if (temp_dir == NULL || temp_dir[0] == '\0')
7432     return "\\temp\\";
7433   else if (temp_dir[strlen(temp_dir) - 1] == '\\')
7434     return temp_dir;
7435   else
7436     return std::string(temp_dir) + "\\";
7437 #elif GTEST_OS_LINUX_ANDROID
7438   return "/sdcard/";
7439 #else
7440   return "/tmp/";
7441 #endif  // GTEST_OS_WINDOWS_MOBILE
7442 }
7443 
7444 // Class ScopedTrace
7445 
7446 // Pushes the given source file location and message onto a per-thread
7447 // trace stack maintained by Google Test.
PushTrace(const char * file,int line,std::string message)7448 void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
7449   internal::TraceInfo trace;
7450   trace.file = file;
7451   trace.line = line;
7452   trace.message.swap(message);
7453 
7454   UnitTest::GetInstance()->PushGTestTrace(trace);
7455 }
7456 
7457 // Pops the info pushed by the c'tor.
~ScopedTrace()7458 ScopedTrace::~ScopedTrace()
7459     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
7460   UnitTest::GetInstance()->PopGTestTrace();
7461 }
7462 
7463 }  // namespace testing
7464 // Copyright 2005, Google Inc.
7465 // All rights reserved.
7466 //
7467 // Redistribution and use in source and binary forms, with or without
7468 // modification, are permitted provided that the following conditions are
7469 // met:
7470 //
7471 //     * Redistributions of source code must retain the above copyright
7472 // notice, this list of conditions and the following disclaimer.
7473 //     * Redistributions in binary form must reproduce the above
7474 // copyright notice, this list of conditions and the following disclaimer
7475 // in the documentation and/or other materials provided with the
7476 // distribution.
7477 //     * Neither the name of Google Inc. nor the names of its
7478 // contributors may be used to endorse or promote products derived from
7479 // this software without specific prior written permission.
7480 //
7481 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7482 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7483 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7484 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7485 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7486 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7487 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7488 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7489 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7490 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7491 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7492 
7493 //
7494 // This file implements death tests.
7495 
7496 
7497 #if GTEST_HAS_DEATH_TEST
7498 
7499 # if GTEST_OS_MAC
7500 #  include <crt_externs.h>
7501 # endif  // GTEST_OS_MAC
7502 
7503 # include <errno.h>
7504 # include <fcntl.h>
7505 # include <limits.h>
7506 
7507 # if GTEST_OS_LINUX
7508 #  include <signal.h>
7509 # endif  // GTEST_OS_LINUX
7510 
7511 # include <stdarg.h>
7512 
7513 # if GTEST_OS_WINDOWS
7514 #  include <windows.h>
7515 # else
7516 #  include <sys/mman.h>
7517 #  include <sys/wait.h>
7518 # endif  // GTEST_OS_WINDOWS
7519 
7520 # if GTEST_OS_QNX
7521 #  include <spawn.h>
7522 # endif  // GTEST_OS_QNX
7523 
7524 # if GTEST_OS_FUCHSIA
7525 #  include <lib/fdio/io.h>
7526 #  include <lib/fdio/spawn.h>
7527 #  include <zircon/processargs.h>
7528 #  include <zircon/syscalls.h>
7529 #  include <zircon/syscalls/port.h>
7530 # endif  // GTEST_OS_FUCHSIA
7531 
7532 #endif  // GTEST_HAS_DEATH_TEST
7533 
7534 
7535 namespace testing {
7536 
7537 // Constants.
7538 
7539 // The default death test style.
7540 //
7541 // This is defined in internal/gtest-port.h as "fast", but can be overridden by
7542 // a definition in internal/custom/gtest-port.h. The recommended value, which is
7543 // used internally at Google, is "threadsafe".
7544 static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
7545 
7546 GTEST_DEFINE_string_(
7547     death_test_style,
7548     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
7549     "Indicates how to run a death test in a forked child process: "
7550     "\"threadsafe\" (child process re-executes the test binary "
7551     "from the beginning, running only the specific death test) or "
7552     "\"fast\" (child process runs the death test immediately "
7553     "after forking).");
7554 
7555 GTEST_DEFINE_bool_(
7556     death_test_use_fork,
7557     internal::BoolFromGTestEnv("death_test_use_fork", false),
7558     "Instructs to use fork()/_exit() instead of clone() in death tests. "
7559     "Ignored and always uses fork() on POSIX systems where clone() is not "
7560     "implemented. Useful when running under valgrind or similar tools if "
7561     "those do not support clone(). Valgrind 3.3.1 will just fail if "
7562     "it sees an unsupported combination of clone() flags. "
7563     "It is not recommended to use this flag w/o valgrind though it will "
7564     "work in 99% of the cases. Once valgrind is fixed, this flag will "
7565     "most likely be removed.");
7566 
7567 namespace internal {
7568 GTEST_DEFINE_string_(
7569     internal_run_death_test, "",
7570     "Indicates the file, line number, temporal index of "
7571     "the single death test to run, and a file descriptor to "
7572     "which a success code may be sent, all separated by "
7573     "the '|' characters.  This flag is specified if and only if the current "
7574     "process is a sub-process launched for running a thread-safe "
7575     "death test.  FOR INTERNAL USE ONLY.");
7576 }  // namespace internal
7577 
7578 #if GTEST_HAS_DEATH_TEST
7579 
7580 namespace internal {
7581 
7582 // Valid only for fast death tests. Indicates the code is running in the
7583 // child process of a fast style death test.
7584 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7585 static bool g_in_fast_death_test_child = false;
7586 # endif
7587 
7588 // Returns a Boolean value indicating whether the caller is currently
7589 // executing in the context of the death test child process.  Tools such as
7590 // Valgrind heap checkers may need this to modify their behavior in death
7591 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
7592 // implementation of death tests.  User code MUST NOT use it.
InDeathTestChild()7593 bool InDeathTestChild() {
7594 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7595 
7596   // On Windows and Fuchsia, death tests are thread-safe regardless of the value
7597   // of the death_test_style flag.
7598   return !GTEST_FLAG(internal_run_death_test).empty();
7599 
7600 # else
7601 
7602   if (GTEST_FLAG(death_test_style) == "threadsafe")
7603     return !GTEST_FLAG(internal_run_death_test).empty();
7604   else
7605     return g_in_fast_death_test_child;
7606 #endif
7607 }
7608 
7609 }  // namespace internal
7610 
7611 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)7612 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
7613 }
7614 
7615 // ExitedWithCode function-call operator.
operator ()(int exit_status) const7616 bool ExitedWithCode::operator()(int exit_status) const {
7617 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7618 
7619   return exit_status == exit_code_;
7620 
7621 # else
7622 
7623   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
7624 
7625 # endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7626 }
7627 
7628 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7629 // KilledBySignal constructor.
KilledBySignal(int signum)7630 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
7631 }
7632 
7633 // KilledBySignal function-call operator.
operator ()(int exit_status) const7634 bool KilledBySignal::operator()(int exit_status) const {
7635 #  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7636   {
7637     bool result;
7638     if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7639       return result;
7640     }
7641   }
7642 #  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7643   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7644 }
7645 # endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7646 
7647 namespace internal {
7648 
7649 // Utilities needed for death tests.
7650 
7651 // Generates a textual description of a given exit code, in the format
7652 // specified by wait(2).
ExitSummary(int exit_code)7653 static std::string ExitSummary(int exit_code) {
7654   Message m;
7655 
7656 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7657 
7658   m << "Exited with exit status " << exit_code;
7659 
7660 # else
7661 
7662   if (WIFEXITED(exit_code)) {
7663     m << "Exited with exit status " << WEXITSTATUS(exit_code);
7664   } else if (WIFSIGNALED(exit_code)) {
7665     m << "Terminated by signal " << WTERMSIG(exit_code);
7666   }
7667 #  ifdef WCOREDUMP
7668   if (WCOREDUMP(exit_code)) {
7669     m << " (core dumped)";
7670   }
7671 #  endif
7672 # endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7673 
7674   return m.GetString();
7675 }
7676 
7677 // Returns true if exit_status describes a process that was terminated
7678 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)7679 bool ExitedUnsuccessfully(int exit_status) {
7680   return !ExitedWithCode(0)(exit_status);
7681 }
7682 
7683 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7684 // Generates a textual failure message when a death test finds more than
7685 // one thread running, or cannot determine the number of threads, prior
7686 // to executing the given statement.  It is the responsibility of the
7687 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)7688 static std::string DeathTestThreadWarning(size_t thread_count) {
7689   Message msg;
7690   msg << "Death tests use fork(), which is unsafe particularly"
7691       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
7692   if (thread_count == 0) {
7693     msg << "couldn't detect the number of threads.";
7694   } else {
7695     msg << "detected " << thread_count << " threads.";
7696   }
7697   msg << " See "
7698          "https://github.com/google/googletest/blob/master/googletest/docs/"
7699          "advanced.md#death-tests-and-threads"
7700       << " for more explanation and suggested solutions, especially if"
7701       << " this is the last message you see before your test times out.";
7702   return msg.GetString();
7703 }
7704 # endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7705 
7706 // Flag characters for reporting a death test that did not die.
7707 static const char kDeathTestLived = 'L';
7708 static const char kDeathTestReturned = 'R';
7709 static const char kDeathTestThrew = 'T';
7710 static const char kDeathTestInternalError = 'I';
7711 
7712 #if GTEST_OS_FUCHSIA
7713 
7714 // File descriptor used for the pipe in the child process.
7715 static const int kFuchsiaReadPipeFd = 3;
7716 
7717 #endif
7718 
7719 // An enumeration describing all of the possible ways that a death test can
7720 // conclude.  DIED means that the process died while executing the test
7721 // code; LIVED means that process lived beyond the end of the test code;
7722 // RETURNED means that the test statement attempted to execute a return
7723 // statement, which is not allowed; THREW means that the test statement
7724 // returned control by throwing an exception.  IN_PROGRESS means the test
7725 // has not yet concluded.
7726 // FIXME: Unify names and possibly values for
7727 // AbortReason, DeathTestOutcome, and flag characters above.
7728 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7729 
7730 // Routine for aborting the program which is safe to call from an
7731 // exec-style death test child process, in which case the error
7732 // message is propagated back to the parent process.  Otherwise, the
7733 // message is simply printed to stderr.  In either case, the program
7734 // then exits with status 1.
DeathTestAbort(const std::string & message)7735 static void DeathTestAbort(const std::string& message) {
7736   // On a POSIX system, this function may be called from a threadsafe-style
7737   // death test child process, which operates on a very small stack.  Use
7738   // the heap for any additional non-minuscule memory requirements.
7739   const InternalRunDeathTestFlag* const flag =
7740       GetUnitTestImpl()->internal_run_death_test_flag();
7741   if (flag != NULL) {
7742     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7743     fputc(kDeathTestInternalError, parent);
7744     fprintf(parent, "%s", message.c_str());
7745     fflush(parent);
7746     _exit(1);
7747   } else {
7748     fprintf(stderr, "%s", message.c_str());
7749     fflush(stderr);
7750     posix::Abort();
7751   }
7752 }
7753 
7754 // A replacement for CHECK that calls DeathTestAbort if the assertion
7755 // fails.
7756 # define GTEST_DEATH_TEST_CHECK_(expression) \
7757   do { \
7758     if (!::testing::internal::IsTrue(expression)) { \
7759       DeathTestAbort( \
7760           ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
7761           + ::testing::internal::StreamableToString(__LINE__) + ": " \
7762           + #expression); \
7763     } \
7764   } while (::testing::internal::AlwaysFalse())
7765 
7766 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7767 // evaluating any system call that fulfills two conditions: it must return
7768 // -1 on failure, and set errno to EINTR when it is interrupted and
7769 // should be tried again.  The macro expands to a loop that repeatedly
7770 // evaluates the expression as long as it evaluates to -1 and sets
7771 // errno to EINTR.  If the expression evaluates to -1 but errno is
7772 // something other than EINTR, DeathTestAbort is called.
7773 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7774   do { \
7775     int gtest_retval; \
7776     do { \
7777       gtest_retval = (expression); \
7778     } while (gtest_retval == -1 && errno == EINTR); \
7779     if (gtest_retval == -1) { \
7780       DeathTestAbort( \
7781           ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7782           + ::testing::internal::StreamableToString(__LINE__) + ": " \
7783           + #expression + " != -1"); \
7784     } \
7785   } while (::testing::internal::AlwaysFalse())
7786 
7787 // Returns the message describing the last system error in errno.
GetLastErrnoDescription()7788 std::string GetLastErrnoDescription() {
7789     return errno == 0 ? "" : posix::StrError(errno);
7790 }
7791 
7792 // This is called from a death test parent process to read a failure
7793 // message from the death test child process and log it with the FATAL
7794 // severity. On Windows, the message is read from a pipe handle. On other
7795 // platforms, it is read from a file descriptor.
FailFromInternalError(int fd)7796 static void FailFromInternalError(int fd) {
7797   Message error;
7798   char buffer[256];
7799   int num_read;
7800 
7801   do {
7802     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7803       buffer[num_read] = '\0';
7804       error << buffer;
7805     }
7806   } while (num_read == -1 && errno == EINTR);
7807 
7808   if (num_read == 0) {
7809     GTEST_LOG_(FATAL) << error.GetString();
7810   } else {
7811     const int last_error = errno;
7812     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7813                       << GetLastErrnoDescription() << " [" << last_error << "]";
7814   }
7815 }
7816 
7817 // Death test constructor.  Increments the running death test count
7818 // for the current test.
DeathTest()7819 DeathTest::DeathTest() {
7820   TestInfo* const info = GetUnitTestImpl()->current_test_info();
7821   if (info == NULL) {
7822     DeathTestAbort("Cannot run a death test outside of a TEST or "
7823                    "TEST_F construct");
7824   }
7825 }
7826 
7827 // Creates and returns a death test by dispatching to the current
7828 // death test factory.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)7829 bool DeathTest::Create(const char* statement, const RE* regex,
7830                        const char* file, int line, DeathTest** test) {
7831   return GetUnitTestImpl()->death_test_factory()->Create(
7832       statement, regex, file, line, test);
7833 }
7834 
LastMessage()7835 const char* DeathTest::LastMessage() {
7836   return last_death_test_message_.c_str();
7837 }
7838 
set_last_death_test_message(const std::string & message)7839 void DeathTest::set_last_death_test_message(const std::string& message) {
7840   last_death_test_message_ = message;
7841 }
7842 
7843 std::string DeathTest::last_death_test_message_;
7844 
7845 // Provides cross platform implementation for some death functionality.
7846 class DeathTestImpl : public DeathTest {
7847  protected:
DeathTestImpl(const char * a_statement,const RE * a_regex)7848   DeathTestImpl(const char* a_statement, const RE* a_regex)
7849       : statement_(a_statement),
7850         regex_(a_regex),
7851         spawned_(false),
7852         status_(-1),
7853         outcome_(IN_PROGRESS),
7854         read_fd_(-1),
7855         write_fd_(-1) {}
7856 
7857   // read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl()7858   ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7859 
7860   void Abort(AbortReason reason);
7861   virtual bool Passed(bool status_ok);
7862 
statement() const7863   const char* statement() const { return statement_; }
regex() const7864   const RE* regex() const { return regex_; }
spawned() const7865   bool spawned() const { return spawned_; }
set_spawned(bool is_spawned)7866   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
status() const7867   int status() const { return status_; }
set_status(int a_status)7868   void set_status(int a_status) { status_ = a_status; }
outcome() const7869   DeathTestOutcome outcome() const { return outcome_; }
set_outcome(DeathTestOutcome an_outcome)7870   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
read_fd() const7871   int read_fd() const { return read_fd_; }
set_read_fd(int fd)7872   void set_read_fd(int fd) { read_fd_ = fd; }
write_fd() const7873   int write_fd() const { return write_fd_; }
set_write_fd(int fd)7874   void set_write_fd(int fd) { write_fd_ = fd; }
7875 
7876   // Called in the parent process only. Reads the result code of the death
7877   // test child process via a pipe, interprets it to set the outcome_
7878   // member, and closes read_fd_.  Outputs diagnostics and terminates in
7879   // case of unexpected codes.
7880   void ReadAndInterpretStatusByte();
7881 
7882  private:
7883   // The textual content of the code this object is testing.  This class
7884   // doesn't own this string and should not attempt to delete it.
7885   const char* const statement_;
7886   // The regular expression which test output must match.  DeathTestImpl
7887   // doesn't own this object and should not attempt to delete it.
7888   const RE* const regex_;
7889   // True if the death test child process has been successfully spawned.
7890   bool spawned_;
7891   // The exit status of the child process.
7892   int status_;
7893   // How the death test concluded.
7894   DeathTestOutcome outcome_;
7895   // Descriptor to the read end of the pipe to the child process.  It is
7896   // always -1 in the child process.  The child keeps its write end of the
7897   // pipe in write_fd_.
7898   int read_fd_;
7899   // Descriptor to the child's write end of the pipe to the parent process.
7900   // It is always -1 in the parent process.  The parent keeps its end of the
7901   // pipe in read_fd_.
7902   int write_fd_;
7903 };
7904 
7905 // Called in the parent process only. Reads the result code of the death
7906 // test child process via a pipe, interprets it to set the outcome_
7907 // member, and closes read_fd_.  Outputs diagnostics and terminates in
7908 // case of unexpected codes.
ReadAndInterpretStatusByte()7909 void DeathTestImpl::ReadAndInterpretStatusByte() {
7910   char flag;
7911   int bytes_read;
7912 
7913   // The read() here blocks until data is available (signifying the
7914   // failure of the death test) or until the pipe is closed (signifying
7915   // its success), so it's okay to call this in the parent before
7916   // the child process has exited.
7917   do {
7918     bytes_read = posix::Read(read_fd(), &flag, 1);
7919   } while (bytes_read == -1 && errno == EINTR);
7920 
7921   if (bytes_read == 0) {
7922     set_outcome(DIED);
7923   } else if (bytes_read == 1) {
7924     switch (flag) {
7925       case kDeathTestReturned:
7926         set_outcome(RETURNED);
7927         break;
7928       case kDeathTestThrew:
7929         set_outcome(THREW);
7930         break;
7931       case kDeathTestLived:
7932         set_outcome(LIVED);
7933         break;
7934       case kDeathTestInternalError:
7935         FailFromInternalError(read_fd());  // Does not return.
7936         break;
7937       default:
7938         GTEST_LOG_(FATAL) << "Death test child process reported "
7939                           << "unexpected status byte ("
7940                           << static_cast<unsigned int>(flag) << ")";
7941     }
7942   } else {
7943     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
7944                       << GetLastErrnoDescription();
7945   }
7946   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
7947   set_read_fd(-1);
7948 }
7949 
7950 // Signals that the death test code which should have exited, didn't.
7951 // Should be called only in a death test child process.
7952 // Writes a status byte to the child's status file descriptor, then
7953 // calls _exit(1).
Abort(AbortReason reason)7954 void DeathTestImpl::Abort(AbortReason reason) {
7955   // The parent process considers the death test to be a failure if
7956   // it finds any data in our pipe.  So, here we write a single flag byte
7957   // to the pipe, then exit.
7958   const char status_ch =
7959       reason == TEST_DID_NOT_DIE ? kDeathTestLived :
7960       reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
7961 
7962   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
7963   // We are leaking the descriptor here because on some platforms (i.e.,
7964   // when built as Windows DLL), destructors of global objects will still
7965   // run after calling _exit(). On such systems, write_fd_ will be
7966   // indirectly closed from the destructor of UnitTestImpl, causing double
7967   // close if it is also closed here. On debug configurations, double close
7968   // may assert. As there are no in-process buffers to flush here, we are
7969   // relying on the OS to close the descriptor after the process terminates
7970   // when the destructors are not run.
7971   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
7972 }
7973 
7974 // Returns an indented copy of stderr output for a death test.
7975 // This makes distinguishing death test output lines from regular log lines
7976 // much easier.
FormatDeathTestOutput(const::std::string & output)7977 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
7978   ::std::string ret;
7979   for (size_t at = 0; ; ) {
7980     const size_t line_end = output.find('\n', at);
7981     ret += "[  DEATH   ] ";
7982     if (line_end == ::std::string::npos) {
7983       ret += output.substr(at);
7984       break;
7985     }
7986     ret += output.substr(at, line_end + 1 - at);
7987     at = line_end + 1;
7988   }
7989   return ret;
7990 }
7991 
7992 // Assesses the success or failure of a death test, using both private
7993 // members which have previously been set, and one argument:
7994 //
7995 // Private data members:
7996 //   outcome:  An enumeration describing how the death test
7997 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
7998 //             fails in the latter three cases.
7999 //   status:   The exit status of the child process. On *nix, it is in the
8000 //             in the format specified by wait(2). On Windows, this is the
8001 //             value supplied to the ExitProcess() API or a numeric code
8002 //             of the exception that terminated the program.
8003 //   regex:    A regular expression object to be applied to
8004 //             the test's captured standard error output; the death test
8005 //             fails if it does not match.
8006 //
8007 // Argument:
8008 //   status_ok: true if exit_status is acceptable in the context of
8009 //              this particular death test, which fails if it is false
8010 //
8011 // Returns true iff all of the above conditions are met.  Otherwise, the
8012 // first failing condition, in the order given above, is the one that is
8013 // reported. Also sets the last death test message string.
Passed(bool status_ok)8014 bool DeathTestImpl::Passed(bool status_ok) {
8015   if (!spawned())
8016     return false;
8017 
8018   const std::string error_message = GetCapturedStderr();
8019 
8020   bool success = false;
8021   Message buffer;
8022 
8023   buffer << "Death test: " << statement() << "\n";
8024   switch (outcome()) {
8025     case LIVED:
8026       buffer << "    Result: failed to die.\n"
8027              << " Error msg:\n" << FormatDeathTestOutput(error_message);
8028       break;
8029     case THREW:
8030       buffer << "    Result: threw an exception.\n"
8031              << " Error msg:\n" << FormatDeathTestOutput(error_message);
8032       break;
8033     case RETURNED:
8034       buffer << "    Result: illegal return in test statement.\n"
8035              << " Error msg:\n" << FormatDeathTestOutput(error_message);
8036       break;
8037     case DIED:
8038       if (status_ok) {
8039 # if GTEST_USES_PCRE
8040         // PCRE regexes support embedded NULs.
8041         const bool matched = RE::PartialMatch(error_message, *regex());
8042 # else
8043         const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
8044 # endif  // GTEST_USES_PCRE
8045         if (matched) {
8046           success = true;
8047         } else {
8048           buffer << "    Result: died but not with expected error.\n"
8049                  << "  Expected: " << regex()->pattern() << "\n"
8050                  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
8051         }
8052       } else {
8053         buffer << "    Result: died but not with expected exit code:\n"
8054                << "            " << ExitSummary(status()) << "\n"
8055                << "Actual msg:\n" << FormatDeathTestOutput(error_message);
8056       }
8057       break;
8058     case IN_PROGRESS:
8059     default:
8060       GTEST_LOG_(FATAL)
8061           << "DeathTest::Passed somehow called before conclusion of test";
8062   }
8063 
8064   DeathTest::set_last_death_test_message(buffer.GetString());
8065   return success;
8066 }
8067 
8068 # if GTEST_OS_WINDOWS
8069 // WindowsDeathTest implements death tests on Windows. Due to the
8070 // specifics of starting new processes on Windows, death tests there are
8071 // always threadsafe, and Google Test considers the
8072 // --gtest_death_test_style=fast setting to be equivalent to
8073 // --gtest_death_test_style=threadsafe there.
8074 //
8075 // A few implementation notes:  Like the Linux version, the Windows
8076 // implementation uses pipes for child-to-parent communication. But due to
8077 // the specifics of pipes on Windows, some extra steps are required:
8078 //
8079 // 1. The parent creates a communication pipe and stores handles to both
8080 //    ends of it.
8081 // 2. The parent starts the child and provides it with the information
8082 //    necessary to acquire the handle to the write end of the pipe.
8083 // 3. The child acquires the write end of the pipe and signals the parent
8084 //    using a Windows event.
8085 // 4. Now the parent can release the write end of the pipe on its side. If
8086 //    this is done before step 3, the object's reference count goes down to
8087 //    0 and it is destroyed, preventing the child from acquiring it. The
8088 //    parent now has to release it, or read operations on the read end of
8089 //    the pipe will not return when the child terminates.
8090 // 5. The parent reads child's output through the pipe (outcome code and
8091 //    any possible error messages) from the pipe, and its stderr and then
8092 //    determines whether to fail the test.
8093 //
8094 // Note: to distinguish Win32 API calls from the local method and function
8095 // calls, the former are explicitly resolved in the global namespace.
8096 //
8097 class WindowsDeathTest : public DeathTestImpl {
8098  public:
WindowsDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)8099   WindowsDeathTest(const char* a_statement,
8100                    const RE* a_regex,
8101                    const char* file,
8102                    int line)
8103       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
8104 
8105   // All of these virtual functions are inherited from DeathTest.
8106   virtual int Wait();
8107   virtual TestRole AssumeRole();
8108 
8109  private:
8110   // The name of the file in which the death test is located.
8111   const char* const file_;
8112   // The line number on which the death test is located.
8113   const int line_;
8114   // Handle to the write end of the pipe to the child process.
8115   AutoHandle write_handle_;
8116   // Child process handle.
8117   AutoHandle child_handle_;
8118   // Event the child process uses to signal the parent that it has
8119   // acquired the handle to the write end of the pipe. After seeing this
8120   // event the parent can release its own handles to make sure its
8121   // ReadFile() calls return when the child terminates.
8122   AutoHandle event_handle_;
8123 };
8124 
8125 // Waits for the child in a death test to exit, returning its exit
8126 // status, or 0 if no child process exists.  As a side effect, sets the
8127 // outcome data member.
Wait()8128 int WindowsDeathTest::Wait() {
8129   if (!spawned())
8130     return 0;
8131 
8132   // Wait until the child either signals that it has acquired the write end
8133   // of the pipe or it dies.
8134   const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8135   switch (::WaitForMultipleObjects(2,
8136                                    wait_handles,
8137                                    FALSE,  // Waits for any of the handles.
8138                                    INFINITE)) {
8139     case WAIT_OBJECT_0:
8140     case WAIT_OBJECT_0 + 1:
8141       break;
8142     default:
8143       GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
8144   }
8145 
8146   // The child has acquired the write end of the pipe or exited.
8147   // We release the handle on our side and continue.
8148   write_handle_.Reset();
8149   event_handle_.Reset();
8150 
8151   ReadAndInterpretStatusByte();
8152 
8153   // Waits for the child process to exit if it haven't already. This
8154   // returns immediately if the child has already exited, regardless of
8155   // whether previous calls to WaitForMultipleObjects synchronized on this
8156   // handle or not.
8157   GTEST_DEATH_TEST_CHECK_(
8158       WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8159                                              INFINITE));
8160   DWORD status_code;
8161   GTEST_DEATH_TEST_CHECK_(
8162       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8163   child_handle_.Reset();
8164   set_status(static_cast<int>(status_code));
8165   return status();
8166 }
8167 
8168 // The AssumeRole process for a Windows death test.  It creates a child
8169 // process with the same executable as the current process to run the
8170 // death test.  The child process is given the --gtest_filter and
8171 // --gtest_internal_run_death_test flags such that it knows to run the
8172 // current death test only.
AssumeRole()8173 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8174   const UnitTestImpl* const impl = GetUnitTestImpl();
8175   const InternalRunDeathTestFlag* const flag =
8176       impl->internal_run_death_test_flag();
8177   const TestInfo* const info = impl->current_test_info();
8178   const int death_test_index = info->result()->death_test_count();
8179 
8180   if (flag != NULL) {
8181     // ParseInternalRunDeathTestFlag() has performed all the necessary
8182     // processing.
8183     set_write_fd(flag->write_fd());
8184     return EXECUTE_TEST;
8185   }
8186 
8187   // WindowsDeathTest uses an anonymous pipe to communicate results of
8188   // a death test.
8189   SECURITY_ATTRIBUTES handles_are_inheritable = {
8190     sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
8191   HANDLE read_handle, write_handle;
8192   GTEST_DEATH_TEST_CHECK_(
8193       ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8194                    0)  // Default buffer size.
8195       != FALSE);
8196   set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8197                                 O_RDONLY));
8198   write_handle_.Reset(write_handle);
8199   event_handle_.Reset(::CreateEvent(
8200       &handles_are_inheritable,
8201       TRUE,    // The event will automatically reset to non-signaled state.
8202       FALSE,   // The initial state is non-signalled.
8203       NULL));  // The even is unnamed.
8204   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
8205   const std::string filter_flag =
8206       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
8207       info->test_case_name() + "." + info->name();
8208   const std::string internal_flag =
8209       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
8210       "=" + file_ + "|" + StreamableToString(line_) + "|" +
8211       StreamableToString(death_test_index) + "|" +
8212       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
8213       // size_t has the same width as pointers on both 32-bit and 64-bit
8214       // Windows platforms.
8215       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
8216       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
8217       "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
8218 
8219   char executable_path[_MAX_PATH + 1];  // NOLINT
8220   GTEST_DEATH_TEST_CHECK_(
8221       _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
8222                                             executable_path,
8223                                             _MAX_PATH));
8224 
8225   std::string command_line =
8226       std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
8227       internal_flag + "\"";
8228 
8229   DeathTest::set_last_death_test_message("");
8230 
8231   CaptureStderr();
8232   // Flush the log buffers since the log streams are shared with the child.
8233   FlushInfoLog();
8234 
8235   // The child process will share the standard handles with the parent.
8236   STARTUPINFOA startup_info;
8237   memset(&startup_info, 0, sizeof(STARTUPINFO));
8238   startup_info.dwFlags = STARTF_USESTDHANDLES;
8239   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
8240   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
8241   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
8242 
8243   PROCESS_INFORMATION process_info;
8244   GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
8245       executable_path,
8246       const_cast<char*>(command_line.c_str()),
8247       NULL,   // Retuned process handle is not inheritable.
8248       NULL,   // Retuned thread handle is not inheritable.
8249       TRUE,   // Child inherits all inheritable handles (for write_handle_).
8250       0x0,    // Default creation flags.
8251       NULL,   // Inherit the parent's environment.
8252       UnitTest::GetInstance()->original_working_dir(),
8253       &startup_info,
8254       &process_info) != FALSE);
8255   child_handle_.Reset(process_info.hProcess);
8256   ::CloseHandle(process_info.hThread);
8257   set_spawned(true);
8258   return OVERSEE_TEST;
8259 }
8260 
8261 # elif GTEST_OS_FUCHSIA
8262 
8263 class FuchsiaDeathTest : public DeathTestImpl {
8264  public:
FuchsiaDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)8265   FuchsiaDeathTest(const char* a_statement,
8266                    const RE* a_regex,
8267                    const char* file,
8268                    int line)
8269       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
~FuchsiaDeathTest()8270   virtual ~FuchsiaDeathTest() {
8271     zx_status_t status = zx_handle_close(child_process_);
8272     GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8273     status = zx_handle_close(port_);
8274     GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8275   }
8276 
8277   // All of these virtual functions are inherited from DeathTest.
8278   virtual int Wait();
8279   virtual TestRole AssumeRole();
8280 
8281  private:
8282   // The name of the file in which the death test is located.
8283   const char* const file_;
8284   // The line number on which the death test is located.
8285   const int line_;
8286 
8287   zx_handle_t child_process_ = ZX_HANDLE_INVALID;
8288   zx_handle_t port_ = ZX_HANDLE_INVALID;
8289 };
8290 
8291 // Utility class for accumulating command-line arguments.
8292 class Arguments {
8293  public:
Arguments()8294   Arguments() {
8295     args_.push_back(NULL);
8296   }
8297 
~Arguments()8298   ~Arguments() {
8299     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8300          ++i) {
8301       free(*i);
8302     }
8303   }
AddArgument(const char * argument)8304   void AddArgument(const char* argument) {
8305     args_.insert(args_.end() - 1, posix::StrDup(argument));
8306   }
8307 
8308   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)8309   void AddArguments(const ::std::vector<Str>& arguments) {
8310     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8311          i != arguments.end();
8312          ++i) {
8313       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8314     }
8315   }
Argv()8316   char* const* Argv() {
8317     return &args_[0];
8318   }
8319 
size()8320   int size() {
8321     return args_.size() - 1;
8322   }
8323 
8324  private:
8325   std::vector<char*> args_;
8326 };
8327 
8328 // Waits for the child in a death test to exit, returning its exit
8329 // status, or 0 if no child process exists.  As a side effect, sets the
8330 // outcome data member.
Wait()8331 int FuchsiaDeathTest::Wait() {
8332   if (!spawned())
8333     return 0;
8334 
8335   // Register to wait for the child process to terminate.
8336   zx_status_t status_zx;
8337   status_zx = zx_object_wait_async(child_process_,
8338                                    port_,
8339                                    0 /* key */,
8340                                    ZX_PROCESS_TERMINATED,
8341                                    ZX_WAIT_ASYNC_ONCE);
8342   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8343 
8344   // Wait for it to terminate, or an exception to be received.
8345   zx_port_packet_t packet;
8346   status_zx = zx_port_wait(port_, ZX_TIME_INFINITE, &packet);
8347   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8348 
8349   if (ZX_PKT_IS_EXCEPTION(packet.type)) {
8350     // Process encountered an exception. Kill it directly rather than letting
8351     // other handlers process the event.
8352     status_zx = zx_task_kill(child_process_);
8353     GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8354 
8355     // Now wait for |child_process_| to terminate.
8356     zx_signals_t signals = 0;
8357     status_zx = zx_object_wait_one(
8358         child_process_, ZX_PROCESS_TERMINATED, ZX_TIME_INFINITE, &signals);
8359     GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8360     GTEST_DEATH_TEST_CHECK_(signals & ZX_PROCESS_TERMINATED);
8361   } else {
8362     // Process terminated.
8363     GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
8364     GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
8365   }
8366 
8367   ReadAndInterpretStatusByte();
8368 
8369   zx_info_process_t buffer;
8370   status_zx = zx_object_get_info(
8371       child_process_,
8372       ZX_INFO_PROCESS,
8373       &buffer,
8374       sizeof(buffer),
8375       nullptr,
8376       nullptr);
8377   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8378 
8379   GTEST_DEATH_TEST_CHECK_(buffer.exited);
8380   set_status(buffer.return_code);
8381   return status();
8382 }
8383 
8384 // The AssumeRole process for a Fuchsia death test.  It creates a child
8385 // process with the same executable as the current process to run the
8386 // death test.  The child process is given the --gtest_filter and
8387 // --gtest_internal_run_death_test flags such that it knows to run the
8388 // current death test only.
AssumeRole()8389 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
8390   const UnitTestImpl* const impl = GetUnitTestImpl();
8391   const InternalRunDeathTestFlag* const flag =
8392       impl->internal_run_death_test_flag();
8393   const TestInfo* const info = impl->current_test_info();
8394   const int death_test_index = info->result()->death_test_count();
8395 
8396   if (flag != NULL) {
8397     // ParseInternalRunDeathTestFlag() has performed all the necessary
8398     // processing.
8399     set_write_fd(kFuchsiaReadPipeFd);
8400     return EXECUTE_TEST;
8401   }
8402 
8403   CaptureStderr();
8404   // Flush the log buffers since the log streams are shared with the child.
8405   FlushInfoLog();
8406 
8407   // Build the child process command line.
8408   const std::string filter_flag =
8409       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
8410       + info->test_case_name() + "." + info->name();
8411   const std::string internal_flag =
8412       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8413       + file_ + "|"
8414       + StreamableToString(line_) + "|"
8415       + StreamableToString(death_test_index);
8416   Arguments args;
8417   args.AddArguments(GetInjectableArgvs());
8418   args.AddArgument(filter_flag.c_str());
8419   args.AddArgument(internal_flag.c_str());
8420 
8421   // Build the pipe for communication with the child.
8422   zx_status_t status;
8423   zx_handle_t child_pipe_handle;
8424   uint32_t type;
8425   status = fdio_pipe_half(&child_pipe_handle, &type);
8426   GTEST_DEATH_TEST_CHECK_(status >= 0);
8427   set_read_fd(status);
8428 
8429   // Set the pipe handle for the child.
8430   fdio_spawn_action_t add_handle_action = {};
8431   add_handle_action.action = FDIO_SPAWN_ACTION_ADD_HANDLE;
8432   add_handle_action.h.id = PA_HND(type, kFuchsiaReadPipeFd);
8433   add_handle_action.h.handle = child_pipe_handle;
8434 
8435   // Spawn the child process.
8436   status = fdio_spawn_etc(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL,
8437                           args.Argv()[0], args.Argv(), nullptr, 1,
8438                           &add_handle_action, &child_process_, nullptr);
8439   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8440 
8441   // Create an exception port and attach it to the |child_process_|, to allow
8442   // us to suppress the system default exception handler from firing.
8443   status = zx_port_create(0, &port_);
8444   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8445   status = zx_task_bind_exception_port(
8446       child_process_, port_, 0 /* key */, 0 /*options */);
8447   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8448 
8449   set_spawned(true);
8450   return OVERSEE_TEST;
8451 }
8452 
8453 #else  // We are neither on Windows, nor on Fuchsia.
8454 
8455 // ForkingDeathTest provides implementations for most of the abstract
8456 // methods of the DeathTest interface.  Only the AssumeRole method is
8457 // left undefined.
8458 class ForkingDeathTest : public DeathTestImpl {
8459  public:
8460   ForkingDeathTest(const char* statement, const RE* regex);
8461 
8462   // All of these virtual functions are inherited from DeathTest.
8463   virtual int Wait();
8464 
8465  protected:
set_child_pid(pid_t child_pid)8466   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
8467 
8468  private:
8469   // PID of child process during death test; 0 in the child process itself.
8470   pid_t child_pid_;
8471 };
8472 
8473 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * a_statement,const RE * a_regex)8474 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
8475     : DeathTestImpl(a_statement, a_regex),
8476       child_pid_(-1) {}
8477 
8478 // Waits for the child in a death test to exit, returning its exit
8479 // status, or 0 if no child process exists.  As a side effect, sets the
8480 // outcome data member.
Wait()8481 int ForkingDeathTest::Wait() {
8482   if (!spawned())
8483     return 0;
8484 
8485   ReadAndInterpretStatusByte();
8486 
8487   int status_value;
8488   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
8489   set_status(status_value);
8490   return status_value;
8491 }
8492 
8493 // A concrete death test class that forks, then immediately runs the test
8494 // in the child process.
8495 class NoExecDeathTest : public ForkingDeathTest {
8496  public:
NoExecDeathTest(const char * a_statement,const RE * a_regex)8497   NoExecDeathTest(const char* a_statement, const RE* a_regex) :
8498       ForkingDeathTest(a_statement, a_regex) { }
8499   virtual TestRole AssumeRole();
8500 };
8501 
8502 // The AssumeRole process for a fork-and-run death test.  It implements a
8503 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()8504 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
8505   const size_t thread_count = GetThreadCount();
8506   if (thread_count != 1) {
8507     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
8508   }
8509 
8510   int pipe_fd[2];
8511   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8512 
8513   DeathTest::set_last_death_test_message("");
8514   CaptureStderr();
8515   // When we fork the process below, the log file buffers are copied, but the
8516   // file descriptors are shared.  We flush all log files here so that closing
8517   // the file descriptors in the child process doesn't throw off the
8518   // synchronization between descriptors and buffers in the parent process.
8519   // This is as close to the fork as possible to avoid a race condition in case
8520   // there are multiple threads running before the death test, and another
8521   // thread writes to the log file.
8522   FlushInfoLog();
8523 
8524   const pid_t child_pid = fork();
8525   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8526   set_child_pid(child_pid);
8527   if (child_pid == 0) {
8528     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
8529     set_write_fd(pipe_fd[1]);
8530     // Redirects all logging to stderr in the child process to prevent
8531     // concurrent writes to the log files.  We capture stderr in the parent
8532     // process and append the child process' output to a log.
8533     LogToStderr();
8534     // Event forwarding to the listeners of event listener API mush be shut
8535     // down in death test subprocesses.
8536     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
8537     g_in_fast_death_test_child = true;
8538     return EXECUTE_TEST;
8539   } else {
8540     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8541     set_read_fd(pipe_fd[0]);
8542     set_spawned(true);
8543     return OVERSEE_TEST;
8544   }
8545 }
8546 
8547 // A concrete death test class that forks and re-executes the main
8548 // program from the beginning, with command-line flags set that cause
8549 // only this specific death test to be run.
8550 class ExecDeathTest : public ForkingDeathTest {
8551  public:
ExecDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)8552   ExecDeathTest(const char* a_statement, const RE* a_regex,
8553                 const char* file, int line) :
8554       ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
8555   virtual TestRole AssumeRole();
8556  private:
GetArgvsForDeathTestChildProcess()8557   static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
8558     ::std::vector<std::string> args = GetInjectableArgvs();
8559 #  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8560     ::std::vector<std::string> extra_args =
8561         GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
8562     args.insert(args.end(), extra_args.begin(), extra_args.end());
8563 #  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8564     return args;
8565   }
8566   // The name of the file in which the death test is located.
8567   const char* const file_;
8568   // The line number on which the death test is located.
8569   const int line_;
8570 };
8571 
8572 // Utility class for accumulating command-line arguments.
8573 class Arguments {
8574  public:
Arguments()8575   Arguments() {
8576     args_.push_back(NULL);
8577   }
8578 
~Arguments()8579   ~Arguments() {
8580     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8581          ++i) {
8582       free(*i);
8583     }
8584   }
AddArgument(const char * argument)8585   void AddArgument(const char* argument) {
8586     args_.insert(args_.end() - 1, posix::StrDup(argument));
8587   }
8588 
8589   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)8590   void AddArguments(const ::std::vector<Str>& arguments) {
8591     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8592          i != arguments.end();
8593          ++i) {
8594       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8595     }
8596   }
Argv()8597   char* const* Argv() {
8598     return &args_[0];
8599   }
8600 
8601  private:
8602   std::vector<char*> args_;
8603 };
8604 
8605 // A struct that encompasses the arguments to the child process of a
8606 // threadsafe-style death test process.
8607 struct ExecDeathTestArgs {
8608   char* const* argv;  // Command-line arguments for the child's call to exec
8609   int close_fd;       // File descriptor to close; the read end of a pipe
8610 };
8611 
8612 #  if GTEST_OS_MAC
GetEnviron()8613 inline char** GetEnviron() {
8614   // When Google Test is built as a framework on MacOS X, the environ variable
8615   // is unavailable. Apple's documentation (man environ) recommends using
8616   // _NSGetEnviron() instead.
8617   return *_NSGetEnviron();
8618 }
8619 #  else
8620 // Some POSIX platforms expect you to declare environ. extern "C" makes
8621 // it reside in the global namespace.
8622 extern "C" char** environ;
GetEnviron()8623 inline char** GetEnviron() { return environ; }
8624 #  endif  // GTEST_OS_MAC
8625 
8626 #  if !GTEST_OS_QNX
8627 // The main function for a threadsafe-style death test child process.
8628 // This function is called in a clone()-ed process and thus must avoid
8629 // any potentially unsafe operations like malloc or libc functions.
ExecDeathTestChildMain(void * child_arg)8630 static int ExecDeathTestChildMain(void* child_arg) {
8631   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
8632   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
8633 
8634   // We need to execute the test program in the same environment where
8635   // it was originally invoked.  Therefore we change to the original
8636   // working directory first.
8637   const char* const original_dir =
8638       UnitTest::GetInstance()->original_working_dir();
8639   // We can safely call chdir() as it's a direct system call.
8640   if (chdir(original_dir) != 0) {
8641     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8642                    GetLastErrnoDescription());
8643     return EXIT_FAILURE;
8644   }
8645 
8646   // We can safely call execve() as it's a direct system call.  We
8647   // cannot use execvp() as it's a libc function and thus potentially
8648   // unsafe.  Since execve() doesn't search the PATH, the user must
8649   // invoke the test program via a valid path that contains at least
8650   // one path separator.
8651   execve(args->argv[0], args->argv, GetEnviron());
8652   DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
8653                  original_dir + " failed: " +
8654                  GetLastErrnoDescription());
8655   return EXIT_FAILURE;
8656 }
8657 #  endif  // !GTEST_OS_QNX
8658 
8659 #  if GTEST_HAS_CLONE
8660 // Two utility routines that together determine the direction the stack
8661 // grows.
8662 // This could be accomplished more elegantly by a single recursive
8663 // function, but we want to guard against the unlikely possibility of
8664 // a smart compiler optimizing the recursion away.
8665 //
8666 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
8667 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
8668 // correct answer.
8669 static void StackLowerThanAddress(const void* ptr,
8670                                   bool* result) GTEST_NO_INLINE_;
StackLowerThanAddress(const void * ptr,bool * result)8671 static void StackLowerThanAddress(const void* ptr, bool* result) {
8672   int dummy;
8673   *result = (&dummy < ptr);
8674 }
8675 
8676 // Make sure AddressSanitizer does not tamper with the stack here.
8677 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
StackGrowsDown()8678 static bool StackGrowsDown() {
8679   int dummy;
8680   bool result;
8681   StackLowerThanAddress(&dummy, &result);
8682   return result;
8683 }
8684 #  endif  // GTEST_HAS_CLONE
8685 
8686 // Spawns a child process with the same executable as the current process in
8687 // a thread-safe manner and instructs it to run the death test.  The
8688 // implementation uses fork(2) + exec.  On systems where clone(2) is
8689 // available, it is used instead, being slightly more thread-safe.  On QNX,
8690 // fork supports only single-threaded environments, so this function uses
8691 // spawn(2) there instead.  The function dies with an error message if
8692 // anything goes wrong.
ExecDeathTestSpawnChild(char * const * argv,int close_fd)8693 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
8694   ExecDeathTestArgs args = { argv, close_fd };
8695   pid_t child_pid = -1;
8696 
8697 #  if GTEST_OS_QNX
8698   // Obtains the current directory and sets it to be closed in the child
8699   // process.
8700   const int cwd_fd = open(".", O_RDONLY);
8701   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
8702   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
8703   // We need to execute the test program in the same environment where
8704   // it was originally invoked.  Therefore we change to the original
8705   // working directory first.
8706   const char* const original_dir =
8707       UnitTest::GetInstance()->original_working_dir();
8708   // We can safely call chdir() as it's a direct system call.
8709   if (chdir(original_dir) != 0) {
8710     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8711                    GetLastErrnoDescription());
8712     return EXIT_FAILURE;
8713   }
8714 
8715   int fd_flags;
8716   // Set close_fd to be closed after spawn.
8717   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
8718   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
8719                                         fd_flags | FD_CLOEXEC));
8720   struct inheritance inherit = {0};
8721   // spawn is a system call.
8722   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
8723   // Restores the current working directory.
8724   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
8725   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
8726 
8727 #  else   // GTEST_OS_QNX
8728 #   if GTEST_OS_LINUX
8729   // When a SIGPROF signal is received while fork() or clone() are executing,
8730   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
8731   // it after the call to fork()/clone() is complete.
8732   struct sigaction saved_sigprof_action;
8733   struct sigaction ignore_sigprof_action;
8734   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
8735   sigemptyset(&ignore_sigprof_action.sa_mask);
8736   ignore_sigprof_action.sa_handler = SIG_IGN;
8737   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
8738       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
8739 #   endif  // GTEST_OS_LINUX
8740 
8741 #   if GTEST_HAS_CLONE
8742   const bool use_fork = GTEST_FLAG(death_test_use_fork);
8743 
8744   if (!use_fork) {
8745     static const bool stack_grows_down = StackGrowsDown();
8746     const size_t stack_size = getpagesize();
8747     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
8748     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
8749                              MAP_ANON | MAP_PRIVATE, -1, 0);
8750     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
8751 
8752     // Maximum stack alignment in bytes:  For a downward-growing stack, this
8753     // amount is subtracted from size of the stack space to get an address
8754     // that is within the stack space and is aligned on all systems we care
8755     // about.  As far as I know there is no ABI with stack alignment greater
8756     // than 64.  We assume stack and stack_size already have alignment of
8757     // kMaxStackAlignment.
8758     const size_t kMaxStackAlignment = 64;
8759     void* const stack_top =
8760         static_cast<char*>(stack) +
8761             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
8762     GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
8763         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
8764 
8765     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
8766 
8767     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
8768   }
8769 #   else
8770   const bool use_fork = true;
8771 #   endif  // GTEST_HAS_CLONE
8772 
8773   if (use_fork && (child_pid = fork()) == 0) {
8774       ExecDeathTestChildMain(&args);
8775       _exit(0);
8776   }
8777 #  endif  // GTEST_OS_QNX
8778 #  if GTEST_OS_LINUX
8779   GTEST_DEATH_TEST_CHECK_SYSCALL_(
8780       sigaction(SIGPROF, &saved_sigprof_action, NULL));
8781 #  endif  // GTEST_OS_LINUX
8782 
8783   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8784   return child_pid;
8785 }
8786 
8787 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
8788 // main program from the beginning, setting the --gtest_filter
8789 // and --gtest_internal_run_death_test flags to cause only the current
8790 // death test to be re-run.
AssumeRole()8791 DeathTest::TestRole ExecDeathTest::AssumeRole() {
8792   const UnitTestImpl* const impl = GetUnitTestImpl();
8793   const InternalRunDeathTestFlag* const flag =
8794       impl->internal_run_death_test_flag();
8795   const TestInfo* const info = impl->current_test_info();
8796   const int death_test_index = info->result()->death_test_count();
8797 
8798   if (flag != NULL) {
8799     set_write_fd(flag->write_fd());
8800     return EXECUTE_TEST;
8801   }
8802 
8803   int pipe_fd[2];
8804   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8805   // Clear the close-on-exec flag on the write end of the pipe, lest
8806   // it be closed when the child process does an exec:
8807   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
8808 
8809   const std::string filter_flag =
8810       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
8811       + info->test_case_name() + "." + info->name();
8812   const std::string internal_flag =
8813       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8814       + file_ + "|" + StreamableToString(line_) + "|"
8815       + StreamableToString(death_test_index) + "|"
8816       + StreamableToString(pipe_fd[1]);
8817   Arguments args;
8818   args.AddArguments(GetArgvsForDeathTestChildProcess());
8819   args.AddArgument(filter_flag.c_str());
8820   args.AddArgument(internal_flag.c_str());
8821 
8822   DeathTest::set_last_death_test_message("");
8823 
8824   CaptureStderr();
8825   // See the comment in NoExecDeathTest::AssumeRole for why the next line
8826   // is necessary.
8827   FlushInfoLog();
8828 
8829   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
8830   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8831   set_child_pid(child_pid);
8832   set_read_fd(pipe_fd[0]);
8833   set_spawned(true);
8834   return OVERSEE_TEST;
8835 }
8836 
8837 # endif  // !GTEST_OS_WINDOWS
8838 
8839 // Creates a concrete DeathTest-derived class that depends on the
8840 // --gtest_death_test_style flag, and sets the pointer pointed to
8841 // by the "test" argument to its address.  If the test should be
8842 // skipped, sets that pointer to NULL.  Returns true, unless the
8843 // flag is set to an invalid value.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)8844 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
8845                                      const char* file, int line,
8846                                      DeathTest** test) {
8847   UnitTestImpl* const impl = GetUnitTestImpl();
8848   const InternalRunDeathTestFlag* const flag =
8849       impl->internal_run_death_test_flag();
8850   const int death_test_index = impl->current_test_info()
8851       ->increment_death_test_count();
8852 
8853   if (flag != NULL) {
8854     if (death_test_index > flag->index()) {
8855       DeathTest::set_last_death_test_message(
8856           "Death test count (" + StreamableToString(death_test_index)
8857           + ") somehow exceeded expected maximum ("
8858           + StreamableToString(flag->index()) + ")");
8859       return false;
8860     }
8861 
8862     if (!(flag->file() == file && flag->line() == line &&
8863           flag->index() == death_test_index)) {
8864       *test = NULL;
8865       return true;
8866     }
8867   }
8868 
8869 # if GTEST_OS_WINDOWS
8870 
8871   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
8872       GTEST_FLAG(death_test_style) == "fast") {
8873     *test = new WindowsDeathTest(statement, regex, file, line);
8874   }
8875 
8876 # elif GTEST_OS_FUCHSIA
8877 
8878   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
8879       GTEST_FLAG(death_test_style) == "fast") {
8880     *test = new FuchsiaDeathTest(statement, regex, file, line);
8881   }
8882 
8883 # else
8884 
8885   if (GTEST_FLAG(death_test_style) == "threadsafe") {
8886     *test = new ExecDeathTest(statement, regex, file, line);
8887   } else if (GTEST_FLAG(death_test_style) == "fast") {
8888     *test = new NoExecDeathTest(statement, regex);
8889   }
8890 
8891 # endif  // GTEST_OS_WINDOWS
8892 
8893   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
8894     DeathTest::set_last_death_test_message(
8895         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
8896         + "\" encountered");
8897     return false;
8898   }
8899 
8900   return true;
8901 }
8902 
8903 # if GTEST_OS_WINDOWS
8904 // Recreates the pipe and event handles from the provided parameters,
8905 // signals the event, and returns a file descriptor wrapped around the pipe
8906 // 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)8907 static int GetStatusFileDescriptor(unsigned int parent_process_id,
8908                             size_t write_handle_as_size_t,
8909                             size_t event_handle_as_size_t) {
8910   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
8911                                                    FALSE,  // Non-inheritable.
8912                                                    parent_process_id));
8913   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
8914     DeathTestAbort("Unable to open parent process " +
8915                    StreamableToString(parent_process_id));
8916   }
8917 
8918   // FIXME: Replace the following check with a
8919   // compile-time assertion when available.
8920   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
8921 
8922   const HANDLE write_handle =
8923       reinterpret_cast<HANDLE>(write_handle_as_size_t);
8924   HANDLE dup_write_handle;
8925 
8926   // The newly initialized handle is accessible only in the parent
8927   // process. To obtain one accessible within the child, we need to use
8928   // DuplicateHandle.
8929   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
8930                          ::GetCurrentProcess(), &dup_write_handle,
8931                          0x0,    // Requested privileges ignored since
8932                                  // DUPLICATE_SAME_ACCESS is used.
8933                          FALSE,  // Request non-inheritable handler.
8934                          DUPLICATE_SAME_ACCESS)) {
8935     DeathTestAbort("Unable to duplicate the pipe handle " +
8936                    StreamableToString(write_handle_as_size_t) +
8937                    " from the parent process " +
8938                    StreamableToString(parent_process_id));
8939   }
8940 
8941   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
8942   HANDLE dup_event_handle;
8943 
8944   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
8945                          ::GetCurrentProcess(), &dup_event_handle,
8946                          0x0,
8947                          FALSE,
8948                          DUPLICATE_SAME_ACCESS)) {
8949     DeathTestAbort("Unable to duplicate the event handle " +
8950                    StreamableToString(event_handle_as_size_t) +
8951                    " from the parent process " +
8952                    StreamableToString(parent_process_id));
8953   }
8954 
8955   const int write_fd =
8956       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
8957   if (write_fd == -1) {
8958     DeathTestAbort("Unable to convert pipe handle " +
8959                    StreamableToString(write_handle_as_size_t) +
8960                    " to a file descriptor");
8961   }
8962 
8963   // Signals the parent that the write end of the pipe has been acquired
8964   // so the parent can release its own write end.
8965   ::SetEvent(dup_event_handle);
8966 
8967   return write_fd;
8968 }
8969 # endif  // GTEST_OS_WINDOWS
8970 
8971 // Returns a newly created InternalRunDeathTestFlag object with fields
8972 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
8973 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()8974 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
8975   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
8976 
8977   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
8978   // can use it here.
8979   int line = -1;
8980   int index = -1;
8981   ::std::vector< ::std::string> fields;
8982   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
8983   int write_fd = -1;
8984 
8985 # if GTEST_OS_WINDOWS
8986 
8987   unsigned int parent_process_id = 0;
8988   size_t write_handle_as_size_t = 0;
8989   size_t event_handle_as_size_t = 0;
8990 
8991   if (fields.size() != 6
8992       || !ParseNaturalNumber(fields[1], &line)
8993       || !ParseNaturalNumber(fields[2], &index)
8994       || !ParseNaturalNumber(fields[3], &parent_process_id)
8995       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
8996       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
8997     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
8998                    GTEST_FLAG(internal_run_death_test));
8999   }
9000   write_fd = GetStatusFileDescriptor(parent_process_id,
9001                                      write_handle_as_size_t,
9002                                      event_handle_as_size_t);
9003 
9004 # elif GTEST_OS_FUCHSIA
9005 
9006   if (fields.size() != 3
9007       || !ParseNaturalNumber(fields[1], &line)
9008       || !ParseNaturalNumber(fields[2], &index)) {
9009     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9010         + GTEST_FLAG(internal_run_death_test));
9011   }
9012 
9013 # else
9014 
9015   if (fields.size() != 4
9016       || !ParseNaturalNumber(fields[1], &line)
9017       || !ParseNaturalNumber(fields[2], &index)
9018       || !ParseNaturalNumber(fields[3], &write_fd)) {
9019     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9020         + GTEST_FLAG(internal_run_death_test));
9021   }
9022 
9023 # endif  // GTEST_OS_WINDOWS
9024 
9025   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9026 }
9027 
9028 }  // namespace internal
9029 
9030 #endif  // GTEST_HAS_DEATH_TEST
9031 
9032 }  // namespace testing
9033 // Copyright 2008, Google Inc.
9034 // All rights reserved.
9035 //
9036 // Redistribution and use in source and binary forms, with or without
9037 // modification, are permitted provided that the following conditions are
9038 // met:
9039 //
9040 //     * Redistributions of source code must retain the above copyright
9041 // notice, this list of conditions and the following disclaimer.
9042 //     * Redistributions in binary form must reproduce the above
9043 // copyright notice, this list of conditions and the following disclaimer
9044 // in the documentation and/or other materials provided with the
9045 // distribution.
9046 //     * Neither the name of Google Inc. nor the names of its
9047 // contributors may be used to endorse or promote products derived from
9048 // this software without specific prior written permission.
9049 //
9050 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9051 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9052 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9053 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9054 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9055 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9056 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9057 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9058 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9059 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9060 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9061 
9062 
9063 #include <stdlib.h>
9064 
9065 #if GTEST_OS_WINDOWS_MOBILE
9066 # include <windows.h>
9067 #elif GTEST_OS_WINDOWS
9068 # include <direct.h>
9069 # include <io.h>
9070 #elif GTEST_OS_SYMBIAN
9071 // Symbian OpenC has PATH_MAX in sys/syslimits.h
9072 # include <sys/syslimits.h>
9073 #else
9074 # include <limits.h>
9075 # include <climits>  // Some Linux distributions define PATH_MAX here.
9076 #endif  // GTEST_OS_WINDOWS_MOBILE
9077 
9078 
9079 #if GTEST_OS_WINDOWS
9080 # define GTEST_PATH_MAX_ _MAX_PATH
9081 #elif defined(PATH_MAX)
9082 # define GTEST_PATH_MAX_ PATH_MAX
9083 #elif defined(_XOPEN_PATH_MAX)
9084 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
9085 #else
9086 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
9087 #endif  // GTEST_OS_WINDOWS
9088 
9089 namespace testing {
9090 namespace internal {
9091 
9092 #if GTEST_OS_WINDOWS
9093 // On Windows, '\\' is the standard path separator, but many tools and the
9094 // Windows API also accept '/' as an alternate path separator. Unless otherwise
9095 // noted, a file path can contain either kind of path separators, or a mixture
9096 // of them.
9097 const char kPathSeparator = '\\';
9098 const char kAlternatePathSeparator = '/';
9099 const char kAlternatePathSeparatorString[] = "/";
9100 # if GTEST_OS_WINDOWS_MOBILE
9101 // Windows CE doesn't have a current directory. You should not use
9102 // the current directory in tests on Windows CE, but this at least
9103 // provides a reasonable fallback.
9104 const char kCurrentDirectoryString[] = "\\";
9105 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
9106 const DWORD kInvalidFileAttributes = 0xffffffff;
9107 # else
9108 const char kCurrentDirectoryString[] = ".\\";
9109 # endif  // GTEST_OS_WINDOWS_MOBILE
9110 #else
9111 const char kPathSeparator = '/';
9112 const char kCurrentDirectoryString[] = "./";
9113 #endif  // GTEST_OS_WINDOWS
9114 
9115 // Returns whether the given character is a valid path separator.
IsPathSeparator(char c)9116 static bool IsPathSeparator(char c) {
9117 #if GTEST_HAS_ALT_PATH_SEP_
9118   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
9119 #else
9120   return c == kPathSeparator;
9121 #endif
9122 }
9123 
9124 // Returns the current working directory, or "" if unsuccessful.
GetCurrentDir()9125 FilePath FilePath::GetCurrentDir() {
9126 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
9127   // Windows CE doesn't have a current directory, so we just return
9128   // something reasonable.
9129   return FilePath(kCurrentDirectoryString);
9130 #elif GTEST_OS_WINDOWS
9131   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9132   return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
9133 #else
9134   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9135   char* result = getcwd(cwd, sizeof(cwd));
9136 # if GTEST_OS_NACL
9137   // getcwd will likely fail in NaCl due to the sandbox, so return something
9138   // reasonable. The user may have provided a shim implementation for getcwd,
9139   // however, so fallback only when failure is detected.
9140   return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
9141 # endif  // GTEST_OS_NACL
9142   return FilePath(result == NULL ? "" : cwd);
9143 #endif  // GTEST_OS_WINDOWS_MOBILE
9144 }
9145 
9146 // Returns a copy of the FilePath with the case-insensitive extension removed.
9147 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
9148 // FilePath("dir/file"). If a case-insensitive extension is not
9149 // found, returns a copy of the original FilePath.
RemoveExtension(const char * extension) const9150 FilePath FilePath::RemoveExtension(const char* extension) const {
9151   const std::string dot_extension = std::string(".") + extension;
9152   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9153     return FilePath(pathname_.substr(
9154         0, pathname_.length() - dot_extension.length()));
9155   }
9156   return *this;
9157 }
9158 
9159 // Returns a pointer to the last occurrence of a valid path separator in
9160 // the FilePath. On Windows, for example, both '/' and '\' are valid path
9161 // separators. Returns NULL if no path separator was found.
FindLastPathSeparator() const9162 const char* FilePath::FindLastPathSeparator() const {
9163   const char* const last_sep = strrchr(c_str(), kPathSeparator);
9164 #if GTEST_HAS_ALT_PATH_SEP_
9165   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
9166   // Comparing two pointers of which only one is NULL is undefined.
9167   if (last_alt_sep != NULL &&
9168       (last_sep == NULL || last_alt_sep > last_sep)) {
9169     return last_alt_sep;
9170   }
9171 #endif
9172   return last_sep;
9173 }
9174 
9175 // Returns a copy of the FilePath with the directory part removed.
9176 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
9177 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
9178 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
9179 // returns an empty FilePath ("").
9180 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveDirectoryName() const9181 FilePath FilePath::RemoveDirectoryName() const {
9182   const char* const last_sep = FindLastPathSeparator();
9183   return last_sep ? FilePath(last_sep + 1) : *this;
9184 }
9185 
9186 // RemoveFileName returns the directory path with the filename removed.
9187 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
9188 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
9189 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
9190 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
9191 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveFileName() const9192 FilePath FilePath::RemoveFileName() const {
9193   const char* const last_sep = FindLastPathSeparator();
9194   std::string dir;
9195   if (last_sep) {
9196     dir = std::string(c_str(), last_sep + 1 - c_str());
9197   } else {
9198     dir = kCurrentDirectoryString;
9199   }
9200   return FilePath(dir);
9201 }
9202 
9203 // Helper functions for naming files in a directory for xml output.
9204 
9205 // Given directory = "dir", base_name = "test", number = 0,
9206 // extension = "xml", returns "dir/test.xml". If number is greater
9207 // than zero (e.g., 12), returns "dir/test_12.xml".
9208 // On Windows platform, uses \ as the separator rather than /.
MakeFileName(const FilePath & directory,const FilePath & base_name,int number,const char * extension)9209 FilePath FilePath::MakeFileName(const FilePath& directory,
9210                                 const FilePath& base_name,
9211                                 int number,
9212                                 const char* extension) {
9213   std::string file;
9214   if (number == 0) {
9215     file = base_name.string() + "." + extension;
9216   } else {
9217     file = base_name.string() + "_" + StreamableToString(number)
9218         + "." + extension;
9219   }
9220   return ConcatPaths(directory, FilePath(file));
9221 }
9222 
9223 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
9224 // On Windows, uses \ as the separator rather than /.
ConcatPaths(const FilePath & directory,const FilePath & relative_path)9225 FilePath FilePath::ConcatPaths(const FilePath& directory,
9226                                const FilePath& relative_path) {
9227   if (directory.IsEmpty())
9228     return relative_path;
9229   const FilePath dir(directory.RemoveTrailingPathSeparator());
9230   return FilePath(dir.string() + kPathSeparator + relative_path.string());
9231 }
9232 
9233 // Returns true if pathname describes something findable in the file-system,
9234 // either a file, directory, or whatever.
FileOrDirectoryExists() const9235 bool FilePath::FileOrDirectoryExists() const {
9236 #if GTEST_OS_WINDOWS_MOBILE
9237   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
9238   const DWORD attributes = GetFileAttributes(unicode);
9239   delete [] unicode;
9240   return attributes != kInvalidFileAttributes;
9241 #else
9242   posix::StatStruct file_stat;
9243   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
9244 #endif  // GTEST_OS_WINDOWS_MOBILE
9245 }
9246 
9247 // Returns true if pathname describes a directory in the file-system
9248 // that exists.
DirectoryExists() const9249 bool FilePath::DirectoryExists() const {
9250   bool result = false;
9251 #if GTEST_OS_WINDOWS
9252   // Don't strip off trailing separator if path is a root directory on
9253   // Windows (like "C:\\").
9254   const FilePath& path(IsRootDirectory() ? *this :
9255                                            RemoveTrailingPathSeparator());
9256 #else
9257   const FilePath& path(*this);
9258 #endif
9259 
9260 #if GTEST_OS_WINDOWS_MOBILE
9261   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
9262   const DWORD attributes = GetFileAttributes(unicode);
9263   delete [] unicode;
9264   if ((attributes != kInvalidFileAttributes) &&
9265       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
9266     result = true;
9267   }
9268 #else
9269   posix::StatStruct file_stat;
9270   result = posix::Stat(path.c_str(), &file_stat) == 0 &&
9271       posix::IsDir(file_stat);
9272 #endif  // GTEST_OS_WINDOWS_MOBILE
9273 
9274   return result;
9275 }
9276 
9277 // Returns true if pathname describes a root directory. (Windows has one
9278 // root directory per disk drive.)
IsRootDirectory() const9279 bool FilePath::IsRootDirectory() const {
9280 #if GTEST_OS_WINDOWS
9281   // FIXME: on Windows a network share like
9282   // \\server\share can be a root directory, although it cannot be the
9283   // current directory.  Handle this properly.
9284   return pathname_.length() == 3 && IsAbsolutePath();
9285 #else
9286   return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
9287 #endif
9288 }
9289 
9290 // Returns true if pathname describes an absolute path.
IsAbsolutePath() const9291 bool FilePath::IsAbsolutePath() const {
9292   const char* const name = pathname_.c_str();
9293 #if GTEST_OS_WINDOWS
9294   return pathname_.length() >= 3 &&
9295      ((name[0] >= 'a' && name[0] <= 'z') ||
9296       (name[0] >= 'A' && name[0] <= 'Z')) &&
9297      name[1] == ':' &&
9298      IsPathSeparator(name[2]);
9299 #else
9300   return IsPathSeparator(name[0]);
9301 #endif
9302 }
9303 
9304 // Returns a pathname for a file that does not currently exist. The pathname
9305 // will be directory/base_name.extension or
9306 // directory/base_name_<number>.extension if directory/base_name.extension
9307 // already exists. The number will be incremented until a pathname is found
9308 // that does not already exist.
9309 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
9310 // There could be a race condition if two or more processes are calling this
9311 // function at the same time -- they could both pick the same filename.
GenerateUniqueFileName(const FilePath & directory,const FilePath & base_name,const char * extension)9312 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
9313                                           const FilePath& base_name,
9314                                           const char* extension) {
9315   FilePath full_pathname;
9316   int number = 0;
9317   do {
9318     full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
9319   } while (full_pathname.FileOrDirectoryExists());
9320   return full_pathname;
9321 }
9322 
9323 // Returns true if FilePath ends with a path separator, which indicates that
9324 // it is intended to represent a directory. Returns false otherwise.
9325 // This does NOT check that a directory (or file) actually exists.
IsDirectory() const9326 bool FilePath::IsDirectory() const {
9327   return !pathname_.empty() &&
9328          IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
9329 }
9330 
9331 // Create directories so that path exists. Returns true if successful or if
9332 // the directories already exist; returns false if unable to create directories
9333 // for any reason.
CreateDirectoriesRecursively() const9334 bool FilePath::CreateDirectoriesRecursively() const {
9335   if (!this->IsDirectory()) {
9336     return false;
9337   }
9338 
9339   if (pathname_.length() == 0 || this->DirectoryExists()) {
9340     return true;
9341   }
9342 
9343   const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
9344   return parent.CreateDirectoriesRecursively() && this->CreateFolder();
9345 }
9346 
9347 // Create the directory so that path exists. Returns true if successful or
9348 // if the directory already exists; returns false if unable to create the
9349 // directory for any reason, including if the parent directory does not
9350 // exist. Not named "CreateDirectory" because that's a macro on Windows.
CreateFolder() const9351 bool FilePath::CreateFolder() const {
9352 #if GTEST_OS_WINDOWS_MOBILE
9353   FilePath removed_sep(this->RemoveTrailingPathSeparator());
9354   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
9355   int result = CreateDirectory(unicode, NULL) ? 0 : -1;
9356   delete [] unicode;
9357 #elif GTEST_OS_WINDOWS
9358   int result = _mkdir(pathname_.c_str());
9359 #else
9360   int result = mkdir(pathname_.c_str(), 0777);
9361 #endif  // GTEST_OS_WINDOWS_MOBILE
9362 
9363   if (result == -1) {
9364     return this->DirectoryExists();  // An error is OK if the directory exists.
9365   }
9366   return true;  // No error.
9367 }
9368 
9369 // If input name has a trailing separator character, remove it and return the
9370 // name, otherwise return the name string unmodified.
9371 // On Windows platform, uses \ as the separator, other platforms use /.
RemoveTrailingPathSeparator() const9372 FilePath FilePath::RemoveTrailingPathSeparator() const {
9373   return IsDirectory()
9374       ? FilePath(pathname_.substr(0, pathname_.length() - 1))
9375       : *this;
9376 }
9377 
9378 // Removes any redundant separators that might be in the pathname.
9379 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
9380 // redundancies that might be in a pathname involving "." or "..".
9381 // FIXME: handle Windows network shares (e.g. \\server\share).
Normalize()9382 void FilePath::Normalize() {
9383   if (pathname_.c_str() == NULL) {
9384     pathname_ = "";
9385     return;
9386   }
9387   const char* src = pathname_.c_str();
9388   char* const dest = new char[pathname_.length() + 1];
9389   char* dest_ptr = dest;
9390   memset(dest_ptr, 0, pathname_.length() + 1);
9391 
9392   while (*src != '\0') {
9393     *dest_ptr = *src;
9394     if (!IsPathSeparator(*src)) {
9395       src++;
9396     } else {
9397 #if GTEST_HAS_ALT_PATH_SEP_
9398       if (*dest_ptr == kAlternatePathSeparator) {
9399         *dest_ptr = kPathSeparator;
9400       }
9401 #endif
9402       while (IsPathSeparator(*src))
9403         src++;
9404     }
9405     dest_ptr++;
9406   }
9407   *dest_ptr = '\0';
9408   pathname_ = dest;
9409   delete[] dest;
9410 }
9411 
9412 }  // namespace internal
9413 }  // namespace testing
9414 // Copyright 2008, Google Inc.
9415 // All rights reserved.
9416 //
9417 // Redistribution and use in source and binary forms, with or without
9418 // modification, are permitted provided that the following conditions are
9419 // met:
9420 //
9421 //     * Redistributions of source code must retain the above copyright
9422 // notice, this list of conditions and the following disclaimer.
9423 //     * Redistributions in binary form must reproduce the above
9424 // copyright notice, this list of conditions and the following disclaimer
9425 // in the documentation and/or other materials provided with the
9426 // distribution.
9427 //     * Neither the name of Google Inc. nor the names of its
9428 // contributors may be used to endorse or promote products derived from
9429 // this software without specific prior written permission.
9430 //
9431 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9432 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9433 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9434 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9435 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9436 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9437 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9438 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9439 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9440 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9441 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9442 
9443 
9444 
9445 #include <limits.h>
9446 #include <stdlib.h>
9447 #include <stdio.h>
9448 #include <string.h>
9449 #include <fstream>
9450 
9451 #if GTEST_OS_WINDOWS
9452 # include <windows.h>
9453 # include <io.h>
9454 # include <sys/stat.h>
9455 # include <map>  // Used in ThreadLocal.
9456 #else
9457 # include <unistd.h>
9458 #endif  // GTEST_OS_WINDOWS
9459 
9460 #if GTEST_OS_MAC
9461 # include <mach/mach_init.h>
9462 # include <mach/task.h>
9463 # include <mach/vm_map.h>
9464 #endif  // GTEST_OS_MAC
9465 
9466 #if GTEST_OS_QNX
9467 # include <devctl.h>
9468 # include <fcntl.h>
9469 # include <sys/procfs.h>
9470 #endif  // GTEST_OS_QNX
9471 
9472 #if GTEST_OS_AIX
9473 # include <procinfo.h>
9474 # include <sys/types.h>
9475 #endif  // GTEST_OS_AIX
9476 
9477 #if GTEST_OS_FUCHSIA
9478 # include <zircon/process.h>
9479 # include <zircon/syscalls.h>
9480 #endif  // GTEST_OS_FUCHSIA
9481 
9482 
9483 namespace testing {
9484 namespace internal {
9485 
9486 #if defined(_MSC_VER) || defined(__BORLANDC__)
9487 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
9488 const int kStdOutFileno = 1;
9489 const int kStdErrFileno = 2;
9490 #else
9491 const int kStdOutFileno = STDOUT_FILENO;
9492 const int kStdErrFileno = STDERR_FILENO;
9493 #endif  // _MSC_VER
9494 
9495 #if GTEST_OS_LINUX
9496 
9497 namespace {
9498 template <typename T>
ReadProcFileField(const std::string & filename,int field)9499 T ReadProcFileField(const std::string& filename, int field) {
9500   std::string dummy;
9501   std::ifstream file(filename.c_str());
9502   while (field-- > 0) {
9503     file >> dummy;
9504   }
9505   T output = 0;
9506   file >> output;
9507   return output;
9508 }
9509 }  // namespace
9510 
9511 // Returns the number of active threads, or 0 when there is an error.
GetThreadCount()9512 size_t GetThreadCount() {
9513   const std::string filename =
9514       (Message() << "/proc/" << getpid() << "/stat").GetString();
9515   return ReadProcFileField<int>(filename, 19);
9516 }
9517 
9518 #elif GTEST_OS_MAC
9519 
GetThreadCount()9520 size_t GetThreadCount() {
9521   const task_t task = mach_task_self();
9522   mach_msg_type_number_t thread_count;
9523   thread_act_array_t thread_list;
9524   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
9525   if (status == KERN_SUCCESS) {
9526     // task_threads allocates resources in thread_list and we need to free them
9527     // to avoid leaks.
9528     vm_deallocate(task,
9529                   reinterpret_cast<vm_address_t>(thread_list),
9530                   sizeof(thread_t) * thread_count);
9531     return static_cast<size_t>(thread_count);
9532   } else {
9533     return 0;
9534   }
9535 }
9536 
9537 #elif GTEST_OS_QNX
9538 
9539 // Returns the number of threads running in the process, or 0 to indicate that
9540 // we cannot detect it.
GetThreadCount()9541 size_t GetThreadCount() {
9542   const int fd = open("/proc/self/as", O_RDONLY);
9543   if (fd < 0) {
9544     return 0;
9545   }
9546   procfs_info process_info;
9547   const int status =
9548       devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
9549   close(fd);
9550   if (status == EOK) {
9551     return static_cast<size_t>(process_info.num_threads);
9552   } else {
9553     return 0;
9554   }
9555 }
9556 
9557 #elif GTEST_OS_AIX
9558 
GetThreadCount()9559 size_t GetThreadCount() {
9560   struct procentry64 entry;
9561   pid_t pid = getpid();
9562   int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
9563   if (status == 1) {
9564     return entry.pi_thcount;
9565   } else {
9566     return 0;
9567   }
9568 }
9569 
9570 #elif GTEST_OS_FUCHSIA
9571 
GetThreadCount()9572 size_t GetThreadCount() {
9573   int dummy_buffer;
9574   size_t avail;
9575   zx_status_t status = zx_object_get_info(
9576       zx_process_self(),
9577       ZX_INFO_PROCESS_THREADS,
9578       &dummy_buffer,
9579       0,
9580       nullptr,
9581       &avail);
9582   if (status == ZX_OK) {
9583     return avail;
9584   } else {
9585     return 0;
9586   }
9587 }
9588 
9589 #else
9590 
GetThreadCount()9591 size_t GetThreadCount() {
9592   // There's no portable way to detect the number of threads, so we just
9593   // return 0 to indicate that we cannot detect it.
9594   return 0;
9595 }
9596 
9597 #endif  // GTEST_OS_LINUX
9598 
9599 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9600 
SleepMilliseconds(int n)9601 void SleepMilliseconds(int n) {
9602   ::Sleep(n);
9603 }
9604 
AutoHandle()9605 AutoHandle::AutoHandle()
9606     : handle_(INVALID_HANDLE_VALUE) {}
9607 
AutoHandle(Handle handle)9608 AutoHandle::AutoHandle(Handle handle)
9609     : handle_(handle) {}
9610 
~AutoHandle()9611 AutoHandle::~AutoHandle() {
9612   Reset();
9613 }
9614 
Get() const9615 AutoHandle::Handle AutoHandle::Get() const {
9616   return handle_;
9617 }
9618 
Reset()9619 void AutoHandle::Reset() {
9620   Reset(INVALID_HANDLE_VALUE);
9621 }
9622 
Reset(HANDLE handle)9623 void AutoHandle::Reset(HANDLE handle) {
9624   // Resetting with the same handle we already own is invalid.
9625   if (handle_ != handle) {
9626     if (IsCloseable()) {
9627       ::CloseHandle(handle_);
9628     }
9629     handle_ = handle;
9630   } else {
9631     GTEST_CHECK_(!IsCloseable())
9632         << "Resetting a valid handle to itself is likely a programmer error "
9633             "and thus not allowed.";
9634   }
9635 }
9636 
IsCloseable() const9637 bool AutoHandle::IsCloseable() const {
9638   // Different Windows APIs may use either of these values to represent an
9639   // invalid handle.
9640   return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
9641 }
9642 
Notification()9643 Notification::Notification()
9644     : event_(::CreateEvent(NULL,   // Default security attributes.
9645                            TRUE,   // Do not reset automatically.
9646                            FALSE,  // Initially unset.
9647                            NULL)) {  // Anonymous event.
9648   GTEST_CHECK_(event_.Get() != NULL);
9649 }
9650 
Notify()9651 void Notification::Notify() {
9652   GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
9653 }
9654 
WaitForNotification()9655 void Notification::WaitForNotification() {
9656   GTEST_CHECK_(
9657       ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
9658 }
9659 
Mutex()9660 Mutex::Mutex()
9661     : owner_thread_id_(0),
9662       type_(kDynamic),
9663       critical_section_init_phase_(0),
9664       critical_section_(new CRITICAL_SECTION) {
9665   ::InitializeCriticalSection(critical_section_);
9666 }
9667 
~Mutex()9668 Mutex::~Mutex() {
9669   // Static mutexes are leaked intentionally. It is not thread-safe to try
9670   // to clean them up.
9671   // FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires
9672   // nothing to clean it up but is available only on Vista and later.
9673   // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks
9674   if (type_ == kDynamic) {
9675     ::DeleteCriticalSection(critical_section_);
9676     delete critical_section_;
9677     critical_section_ = NULL;
9678   }
9679 }
9680 
Lock()9681 void Mutex::Lock() {
9682   ThreadSafeLazyInit();
9683   ::EnterCriticalSection(critical_section_);
9684   owner_thread_id_ = ::GetCurrentThreadId();
9685 }
9686 
Unlock()9687 void Mutex::Unlock() {
9688   ThreadSafeLazyInit();
9689   // We don't protect writing to owner_thread_id_ here, as it's the
9690   // caller's responsibility to ensure that the current thread holds the
9691   // mutex when this is called.
9692   owner_thread_id_ = 0;
9693   ::LeaveCriticalSection(critical_section_);
9694 }
9695 
9696 // Does nothing if the current thread holds the mutex. Otherwise, crashes
9697 // with high probability.
AssertHeld()9698 void Mutex::AssertHeld() {
9699   ThreadSafeLazyInit();
9700   GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
9701       << "The current thread is not holding the mutex @" << this;
9702 }
9703 
9704 namespace {
9705 
9706 // Use the RAII idiom to flag mem allocs that are intentionally never
9707 // deallocated. The motivation is to silence the false positive mem leaks
9708 // that are reported by the debug version of MS's CRT which can only detect
9709 // if an alloc is missing a matching deallocation.
9710 // Example:
9711 //    MemoryIsNotDeallocated memory_is_not_deallocated;
9712 //    critical_section_ = new CRITICAL_SECTION;
9713 //
9714 class MemoryIsNotDeallocated
9715 {
9716  public:
MemoryIsNotDeallocated()9717   MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
9718 #ifdef _MSC_VER
9719     old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
9720     // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
9721     // doesn't report mem leak if there's no matching deallocation.
9722     _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
9723 #endif  //  _MSC_VER
9724   }
9725 
~MemoryIsNotDeallocated()9726   ~MemoryIsNotDeallocated() {
9727 #ifdef _MSC_VER
9728     // Restore the original _CRTDBG_ALLOC_MEM_DF flag
9729     _CrtSetDbgFlag(old_crtdbg_flag_);
9730 #endif  //  _MSC_VER
9731   }
9732 
9733  private:
9734   int old_crtdbg_flag_;
9735 
9736   GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
9737 };
9738 
9739 }  // namespace
9740 
9741 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
ThreadSafeLazyInit()9742 void Mutex::ThreadSafeLazyInit() {
9743   // Dynamic mutexes are initialized in the constructor.
9744   if (type_ == kStatic) {
9745     switch (
9746         ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
9747       case 0:
9748         // If critical_section_init_phase_ was 0 before the exchange, we
9749         // are the first to test it and need to perform the initialization.
9750         owner_thread_id_ = 0;
9751         {
9752           // Use RAII to flag that following mem alloc is never deallocated.
9753           MemoryIsNotDeallocated memory_is_not_deallocated;
9754           critical_section_ = new CRITICAL_SECTION;
9755         }
9756         ::InitializeCriticalSection(critical_section_);
9757         // Updates the critical_section_init_phase_ to 2 to signal
9758         // initialization complete.
9759         GTEST_CHECK_(::InterlockedCompareExchange(
9760                           &critical_section_init_phase_, 2L, 1L) ==
9761                       1L);
9762         break;
9763       case 1:
9764         // Somebody else is already initializing the mutex; spin until they
9765         // are done.
9766         while (::InterlockedCompareExchange(&critical_section_init_phase_,
9767                                             2L,
9768                                             2L) != 2L) {
9769           // Possibly yields the rest of the thread's time slice to other
9770           // threads.
9771           ::Sleep(0);
9772         }
9773         break;
9774 
9775       case 2:
9776         break;  // The mutex is already initialized and ready for use.
9777 
9778       default:
9779         GTEST_CHECK_(false)
9780             << "Unexpected value of critical_section_init_phase_ "
9781             << "while initializing a static mutex.";
9782     }
9783   }
9784 }
9785 
9786 namespace {
9787 
9788 class ThreadWithParamSupport : public ThreadWithParamBase {
9789  public:
CreateThread(Runnable * runnable,Notification * thread_can_start)9790   static HANDLE CreateThread(Runnable* runnable,
9791                              Notification* thread_can_start) {
9792     ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
9793     DWORD thread_id;
9794     // FIXME: Consider to use _beginthreadex instead.
9795     HANDLE thread_handle = ::CreateThread(
9796         NULL,    // Default security.
9797         0,       // Default stack size.
9798         &ThreadWithParamSupport::ThreadMain,
9799         param,   // Parameter to ThreadMainStatic
9800         0x0,     // Default creation flags.
9801         &thread_id);  // Need a valid pointer for the call to work under Win98.
9802     GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
9803                                         << ::GetLastError() << ".";
9804     if (thread_handle == NULL) {
9805       delete param;
9806     }
9807     return thread_handle;
9808   }
9809 
9810  private:
9811   struct ThreadMainParam {
ThreadMainParamtesting::internal::__anon1006c1ff0a11::ThreadWithParamSupport::ThreadMainParam9812     ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
9813         : runnable_(runnable),
9814           thread_can_start_(thread_can_start) {
9815     }
9816     scoped_ptr<Runnable> runnable_;
9817     // Does not own.
9818     Notification* thread_can_start_;
9819   };
9820 
ThreadMain(void * ptr)9821   static DWORD WINAPI ThreadMain(void* ptr) {
9822     // Transfers ownership.
9823     scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
9824     if (param->thread_can_start_ != NULL)
9825       param->thread_can_start_->WaitForNotification();
9826     param->runnable_->Run();
9827     return 0;
9828   }
9829 
9830   // Prohibit instantiation.
9831   ThreadWithParamSupport();
9832 
9833   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
9834 };
9835 
9836 }  // namespace
9837 
ThreadWithParamBase(Runnable * runnable,Notification * thread_can_start)9838 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
9839                                          Notification* thread_can_start)
9840       : thread_(ThreadWithParamSupport::CreateThread(runnable,
9841                                                      thread_can_start)) {
9842 }
9843 
~ThreadWithParamBase()9844 ThreadWithParamBase::~ThreadWithParamBase() {
9845   Join();
9846 }
9847 
Join()9848 void ThreadWithParamBase::Join() {
9849   GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
9850       << "Failed to join the thread with error " << ::GetLastError() << ".";
9851 }
9852 
9853 // Maps a thread to a set of ThreadIdToThreadLocals that have values
9854 // instantiated on that thread and notifies them when the thread exits.  A
9855 // ThreadLocal instance is expected to persist until all threads it has
9856 // values on have terminated.
9857 class ThreadLocalRegistryImpl {
9858  public:
9859   // Registers thread_local_instance as having value on the current thread.
9860   // Returns a value that can be used to identify the thread from other threads.
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)9861   static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
9862       const ThreadLocalBase* thread_local_instance) {
9863     DWORD current_thread = ::GetCurrentThreadId();
9864     MutexLock lock(&mutex_);
9865     ThreadIdToThreadLocals* const thread_to_thread_locals =
9866         GetThreadLocalsMapLocked();
9867     ThreadIdToThreadLocals::iterator thread_local_pos =
9868         thread_to_thread_locals->find(current_thread);
9869     if (thread_local_pos == thread_to_thread_locals->end()) {
9870       thread_local_pos = thread_to_thread_locals->insert(
9871           std::make_pair(current_thread, ThreadLocalValues())).first;
9872       StartWatcherThreadFor(current_thread);
9873     }
9874     ThreadLocalValues& thread_local_values = thread_local_pos->second;
9875     ThreadLocalValues::iterator value_pos =
9876         thread_local_values.find(thread_local_instance);
9877     if (value_pos == thread_local_values.end()) {
9878       value_pos =
9879           thread_local_values
9880               .insert(std::make_pair(
9881                   thread_local_instance,
9882                   linked_ptr<ThreadLocalValueHolderBase>(
9883                       thread_local_instance->NewValueForCurrentThread())))
9884               .first;
9885     }
9886     return value_pos->second.get();
9887   }
9888 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)9889   static void OnThreadLocalDestroyed(
9890       const ThreadLocalBase* thread_local_instance) {
9891     std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
9892     // Clean up the ThreadLocalValues data structure while holding the lock, but
9893     // defer the destruction of the ThreadLocalValueHolderBases.
9894     {
9895       MutexLock lock(&mutex_);
9896       ThreadIdToThreadLocals* const thread_to_thread_locals =
9897           GetThreadLocalsMapLocked();
9898       for (ThreadIdToThreadLocals::iterator it =
9899           thread_to_thread_locals->begin();
9900           it != thread_to_thread_locals->end();
9901           ++it) {
9902         ThreadLocalValues& thread_local_values = it->second;
9903         ThreadLocalValues::iterator value_pos =
9904             thread_local_values.find(thread_local_instance);
9905         if (value_pos != thread_local_values.end()) {
9906           value_holders.push_back(value_pos->second);
9907           thread_local_values.erase(value_pos);
9908           // This 'if' can only be successful at most once, so theoretically we
9909           // could break out of the loop here, but we don't bother doing so.
9910         }
9911       }
9912     }
9913     // Outside the lock, let the destructor for 'value_holders' deallocate the
9914     // ThreadLocalValueHolderBases.
9915   }
9916 
OnThreadExit(DWORD thread_id)9917   static void OnThreadExit(DWORD thread_id) {
9918     GTEST_CHECK_(thread_id != 0) << ::GetLastError();
9919     std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
9920     // Clean up the ThreadIdToThreadLocals data structure while holding the
9921     // lock, but defer the destruction of the ThreadLocalValueHolderBases.
9922     {
9923       MutexLock lock(&mutex_);
9924       ThreadIdToThreadLocals* const thread_to_thread_locals =
9925           GetThreadLocalsMapLocked();
9926       ThreadIdToThreadLocals::iterator thread_local_pos =
9927           thread_to_thread_locals->find(thread_id);
9928       if (thread_local_pos != thread_to_thread_locals->end()) {
9929         ThreadLocalValues& thread_local_values = thread_local_pos->second;
9930         for (ThreadLocalValues::iterator value_pos =
9931             thread_local_values.begin();
9932             value_pos != thread_local_values.end();
9933             ++value_pos) {
9934           value_holders.push_back(value_pos->second);
9935         }
9936         thread_to_thread_locals->erase(thread_local_pos);
9937       }
9938     }
9939     // Outside the lock, let the destructor for 'value_holders' deallocate the
9940     // ThreadLocalValueHolderBases.
9941   }
9942 
9943  private:
9944   // In a particular thread, maps a ThreadLocal object to its value.
9945   typedef std::map<const ThreadLocalBase*,
9946                    linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
9947   // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
9948   // thread's ID.
9949   typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
9950 
9951   // Holds the thread id and thread handle that we pass from
9952   // StartWatcherThreadFor to WatcherThreadFunc.
9953   typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
9954 
StartWatcherThreadFor(DWORD thread_id)9955   static void StartWatcherThreadFor(DWORD thread_id) {
9956     // The returned handle will be kept in thread_map and closed by
9957     // watcher_thread in WatcherThreadFunc.
9958     HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
9959                                  FALSE,
9960                                  thread_id);
9961     GTEST_CHECK_(thread != NULL);
9962     // We need to pass a valid thread ID pointer into CreateThread for it
9963     // to work correctly under Win98.
9964     DWORD watcher_thread_id;
9965     HANDLE watcher_thread = ::CreateThread(
9966         NULL,   // Default security.
9967         0,      // Default stack size
9968         &ThreadLocalRegistryImpl::WatcherThreadFunc,
9969         reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
9970         CREATE_SUSPENDED,
9971         &watcher_thread_id);
9972     GTEST_CHECK_(watcher_thread != NULL);
9973     // Give the watcher thread the same priority as ours to avoid being
9974     // blocked by it.
9975     ::SetThreadPriority(watcher_thread,
9976                         ::GetThreadPriority(::GetCurrentThread()));
9977     ::ResumeThread(watcher_thread);
9978     ::CloseHandle(watcher_thread);
9979   }
9980 
9981   // Monitors exit from a given thread and notifies those
9982   // ThreadIdToThreadLocals about thread termination.
WatcherThreadFunc(LPVOID param)9983   static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
9984     const ThreadIdAndHandle* tah =
9985         reinterpret_cast<const ThreadIdAndHandle*>(param);
9986     GTEST_CHECK_(
9987         ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
9988     OnThreadExit(tah->first);
9989     ::CloseHandle(tah->second);
9990     delete tah;
9991     return 0;
9992   }
9993 
9994   // Returns map of thread local instances.
GetThreadLocalsMapLocked()9995   static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
9996     mutex_.AssertHeld();
9997     MemoryIsNotDeallocated memory_is_not_deallocated;
9998     static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
9999     return map;
10000   }
10001 
10002   // Protects access to GetThreadLocalsMapLocked() and its return value.
10003   static Mutex mutex_;
10004   // Protects access to GetThreadMapLocked() and its return value.
10005   static Mutex thread_map_mutex_;
10006 };
10007 
10008 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
10009 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
10010 
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)10011 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
10012       const ThreadLocalBase* thread_local_instance) {
10013   return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
10014       thread_local_instance);
10015 }
10016 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)10017 void ThreadLocalRegistry::OnThreadLocalDestroyed(
10018       const ThreadLocalBase* thread_local_instance) {
10019   ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
10020 }
10021 
10022 #endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
10023 
10024 #if GTEST_USES_POSIX_RE
10025 
10026 // Implements RE.  Currently only needed for death tests.
10027 
~RE()10028 RE::~RE() {
10029   if (is_valid_) {
10030     // regfree'ing an invalid regex might crash because the content
10031     // of the regex is undefined. Since the regex's are essentially
10032     // the same, one cannot be valid (or invalid) without the other
10033     // being so too.
10034     regfree(&partial_regex_);
10035     regfree(&full_regex_);
10036   }
10037   free(const_cast<char*>(pattern_));
10038 }
10039 
10040 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)10041 bool RE::FullMatch(const char* str, const RE& re) {
10042   if (!re.is_valid_) return false;
10043 
10044   regmatch_t match;
10045   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
10046 }
10047 
10048 // Returns true iff regular expression re matches a substring of str
10049 // (including str itself).
PartialMatch(const char * str,const RE & re)10050 bool RE::PartialMatch(const char* str, const RE& re) {
10051   if (!re.is_valid_) return false;
10052 
10053   regmatch_t match;
10054   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
10055 }
10056 
10057 // Initializes an RE from its string representation.
Init(const char * regex)10058 void RE::Init(const char* regex) {
10059   pattern_ = posix::StrDup(regex);
10060 
10061   // Reserves enough bytes to hold the regular expression used for a
10062   // full match.
10063   const size_t full_regex_len = strlen(regex) + 10;
10064   char* const full_pattern = new char[full_regex_len];
10065 
10066   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
10067   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
10068   // We want to call regcomp(&partial_regex_, ...) even if the
10069   // previous expression returns false.  Otherwise partial_regex_ may
10070   // not be properly initialized can may cause trouble when it's
10071   // freed.
10072   //
10073   // Some implementation of POSIX regex (e.g. on at least some
10074   // versions of Cygwin) doesn't accept the empty string as a valid
10075   // regex.  We change it to an equivalent form "()" to be safe.
10076   if (is_valid_) {
10077     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
10078     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
10079   }
10080   EXPECT_TRUE(is_valid_)
10081       << "Regular expression \"" << regex
10082       << "\" is not a valid POSIX Extended regular expression.";
10083 
10084   delete[] full_pattern;
10085 }
10086 
10087 #elif GTEST_USES_SIMPLE_RE
10088 
10089 // Returns true iff ch appears anywhere in str (excluding the
10090 // terminating '\0' character).
IsInSet(char ch,const char * str)10091 bool IsInSet(char ch, const char* str) {
10092   return ch != '\0' && strchr(str, ch) != NULL;
10093 }
10094 
10095 // Returns true iff ch belongs to the given classification.  Unlike
10096 // similar functions in <ctype.h>, these aren't affected by the
10097 // current locale.
IsAsciiDigit(char ch)10098 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)10099 bool IsAsciiPunct(char ch) {
10100   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
10101 }
IsRepeat(char ch)10102 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)10103 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)10104 bool IsAsciiWordChar(char ch) {
10105   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
10106       ('0' <= ch && ch <= '9') || ch == '_';
10107 }
10108 
10109 // Returns true iff "\\c" is a supported escape sequence.
IsValidEscape(char c)10110 bool IsValidEscape(char c) {
10111   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
10112 }
10113 
10114 // Returns true iff the given atom (specified by escaped and pattern)
10115 // matches ch.  The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)10116 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
10117   if (escaped) {  // "\\p" where p is pattern_char.
10118     switch (pattern_char) {
10119       case 'd': return IsAsciiDigit(ch);
10120       case 'D': return !IsAsciiDigit(ch);
10121       case 'f': return ch == '\f';
10122       case 'n': return ch == '\n';
10123       case 'r': return ch == '\r';
10124       case 's': return IsAsciiWhiteSpace(ch);
10125       case 'S': return !IsAsciiWhiteSpace(ch);
10126       case 't': return ch == '\t';
10127       case 'v': return ch == '\v';
10128       case 'w': return IsAsciiWordChar(ch);
10129       case 'W': return !IsAsciiWordChar(ch);
10130     }
10131     return IsAsciiPunct(pattern_char) && pattern_char == ch;
10132   }
10133 
10134   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
10135 }
10136 
10137 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)10138 static std::string FormatRegexSyntaxError(const char* regex, int index) {
10139   return (Message() << "Syntax error at index " << index
10140           << " in simple regular expression \"" << regex << "\": ").GetString();
10141 }
10142 
10143 // Generates non-fatal failures and returns false if regex is invalid;
10144 // otherwise returns true.
ValidateRegex(const char * regex)10145 bool ValidateRegex(const char* regex) {
10146   if (regex == NULL) {
10147     // FIXME: fix the source file location in the
10148     // assertion failures to match where the regex is used in user
10149     // code.
10150     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
10151     return false;
10152   }
10153 
10154   bool is_valid = true;
10155 
10156   // True iff ?, *, or + can follow the previous atom.
10157   bool prev_repeatable = false;
10158   for (int i = 0; regex[i]; i++) {
10159     if (regex[i] == '\\') {  // An escape sequence
10160       i++;
10161       if (regex[i] == '\0') {
10162         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10163                       << "'\\' cannot appear at the end.";
10164         return false;
10165       }
10166 
10167       if (!IsValidEscape(regex[i])) {
10168         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10169                       << "invalid escape sequence \"\\" << regex[i] << "\".";
10170         is_valid = false;
10171       }
10172       prev_repeatable = true;
10173     } else {  // Not an escape sequence.
10174       const char ch = regex[i];
10175 
10176       if (ch == '^' && i > 0) {
10177         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10178                       << "'^' can only appear at the beginning.";
10179         is_valid = false;
10180       } else if (ch == '$' && regex[i + 1] != '\0') {
10181         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10182                       << "'$' can only appear at the end.";
10183         is_valid = false;
10184       } else if (IsInSet(ch, "()[]{}|")) {
10185         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10186                       << "'" << ch << "' is unsupported.";
10187         is_valid = false;
10188       } else if (IsRepeat(ch) && !prev_repeatable) {
10189         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10190                       << "'" << ch << "' can only follow a repeatable token.";
10191         is_valid = false;
10192       }
10193 
10194       prev_repeatable = !IsInSet(ch, "^$?*+");
10195     }
10196   }
10197 
10198   return is_valid;
10199 }
10200 
10201 // Matches a repeated regex atom followed by a valid simple regular
10202 // expression.  The regex atom is defined as c if escaped is false,
10203 // or \c otherwise.  repeat is the repetition meta character (?, *,
10204 // or +).  The behavior is undefined if str contains too many
10205 // characters to be indexable by size_t, in which case the test will
10206 // probably time out anyway.  We are fine with this limitation as
10207 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)10208 bool MatchRepetitionAndRegexAtHead(
10209     bool escaped, char c, char repeat, const char* regex,
10210     const char* str) {
10211   const size_t min_count = (repeat == '+') ? 1 : 0;
10212   const size_t max_count = (repeat == '?') ? 1 :
10213       static_cast<size_t>(-1) - 1;
10214   // We cannot call numeric_limits::max() as it conflicts with the
10215   // max() macro on Windows.
10216 
10217   for (size_t i = 0; i <= max_count; ++i) {
10218     // We know that the atom matches each of the first i characters in str.
10219     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
10220       // We have enough matches at the head, and the tail matches too.
10221       // Since we only care about *whether* the pattern matches str
10222       // (as opposed to *how* it matches), there is no need to find a
10223       // greedy match.
10224       return true;
10225     }
10226     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
10227       return false;
10228   }
10229   return false;
10230 }
10231 
10232 // Returns true iff regex matches a prefix of str.  regex must be a
10233 // valid simple regular expression and not start with "^", or the
10234 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)10235 bool MatchRegexAtHead(const char* regex, const char* str) {
10236   if (*regex == '\0')  // An empty regex matches a prefix of anything.
10237     return true;
10238 
10239   // "$" only matches the end of a string.  Note that regex being
10240   // valid guarantees that there's nothing after "$" in it.
10241   if (*regex == '$')
10242     return *str == '\0';
10243 
10244   // Is the first thing in regex an escape sequence?
10245   const bool escaped = *regex == '\\';
10246   if (escaped)
10247     ++regex;
10248   if (IsRepeat(regex[1])) {
10249     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
10250     // here's an indirect recursion.  It terminates as the regex gets
10251     // shorter in each recursion.
10252     return MatchRepetitionAndRegexAtHead(
10253         escaped, regex[0], regex[1], regex + 2, str);
10254   } else {
10255     // regex isn't empty, isn't "$", and doesn't start with a
10256     // repetition.  We match the first atom of regex with the first
10257     // character of str and recurse.
10258     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
10259         MatchRegexAtHead(regex + 1, str + 1);
10260   }
10261 }
10262 
10263 // Returns true iff regex matches any substring of str.  regex must be
10264 // a valid simple regular expression, or the result is undefined.
10265 //
10266 // The algorithm is recursive, but the recursion depth doesn't exceed
10267 // the regex length, so we won't need to worry about running out of
10268 // stack space normally.  In rare cases the time complexity can be
10269 // exponential with respect to the regex length + the string length,
10270 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)10271 bool MatchRegexAnywhere(const char* regex, const char* str) {
10272   if (regex == NULL || str == NULL)
10273     return false;
10274 
10275   if (*regex == '^')
10276     return MatchRegexAtHead(regex + 1, str);
10277 
10278   // A successful match can be anywhere in str.
10279   do {
10280     if (MatchRegexAtHead(regex, str))
10281       return true;
10282   } while (*str++ != '\0');
10283   return false;
10284 }
10285 
10286 // Implements the RE class.
10287 
~RE()10288 RE::~RE() {
10289   free(const_cast<char*>(pattern_));
10290   free(const_cast<char*>(full_pattern_));
10291 }
10292 
10293 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)10294 bool RE::FullMatch(const char* str, const RE& re) {
10295   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
10296 }
10297 
10298 // Returns true iff regular expression re matches a substring of str
10299 // (including str itself).
PartialMatch(const char * str,const RE & re)10300 bool RE::PartialMatch(const char* str, const RE& re) {
10301   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
10302 }
10303 
10304 // Initializes an RE from its string representation.
Init(const char * regex)10305 void RE::Init(const char* regex) {
10306   pattern_ = full_pattern_ = NULL;
10307   if (regex != NULL) {
10308     pattern_ = posix::StrDup(regex);
10309   }
10310 
10311   is_valid_ = ValidateRegex(regex);
10312   if (!is_valid_) {
10313     // No need to calculate the full pattern when the regex is invalid.
10314     return;
10315   }
10316 
10317   const size_t len = strlen(regex);
10318   // Reserves enough bytes to hold the regular expression used for a
10319   // full match: we need space to prepend a '^', append a '$', and
10320   // terminate the string with '\0'.
10321   char* buffer = static_cast<char*>(malloc(len + 3));
10322   full_pattern_ = buffer;
10323 
10324   if (*regex != '^')
10325     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
10326 
10327   // We don't use snprintf or strncpy, as they trigger a warning when
10328   // compiled with VC++ 8.0.
10329   memcpy(buffer, regex, len);
10330   buffer += len;
10331 
10332   if (len == 0 || regex[len - 1] != '$')
10333     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
10334 
10335   *buffer = '\0';
10336 }
10337 
10338 #endif  // GTEST_USES_POSIX_RE
10339 
10340 const char kUnknownFile[] = "unknown file";
10341 
10342 // Formats a source file path and a line number as they would appear
10343 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)10344 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
10345   const std::string file_name(file == NULL ? kUnknownFile : file);
10346 
10347   if (line < 0) {
10348     return file_name + ":";
10349   }
10350 #ifdef _MSC_VER
10351   return file_name + "(" + StreamableToString(line) + "):";
10352 #else
10353   return file_name + ":" + StreamableToString(line) + ":";
10354 #endif  // _MSC_VER
10355 }
10356 
10357 // Formats a file location for compiler-independent XML output.
10358 // Although this function is not platform dependent, we put it next to
10359 // FormatFileLocation in order to contrast the two functions.
10360 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
10361 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)10362 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
10363     const char* file, int line) {
10364   const std::string file_name(file == NULL ? kUnknownFile : file);
10365 
10366   if (line < 0)
10367     return file_name;
10368   else
10369     return file_name + ":" + StreamableToString(line);
10370 }
10371 
GTestLog(GTestLogSeverity severity,const char * file,int line)10372 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
10373     : severity_(severity) {
10374   const char* const marker =
10375       severity == GTEST_INFO ?    "[  INFO ]" :
10376       severity == GTEST_WARNING ? "[WARNING]" :
10377       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
10378   GetStream() << ::std::endl << marker << " "
10379               << FormatFileLocation(file, line).c_str() << ": ";
10380 }
10381 
10382 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()10383 GTestLog::~GTestLog() {
10384   GetStream() << ::std::endl;
10385   if (severity_ == GTEST_FATAL) {
10386     fflush(stderr);
10387     posix::Abort();
10388   }
10389 }
10390 
10391 // Disable Microsoft deprecation warnings for POSIX functions called from
10392 // this class (creat, dup, dup2, and close)
10393 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
10394 
10395 #if GTEST_HAS_STREAM_REDIRECTION
10396 
10397 // Object that captures an output stream (stdout/stderr).
10398 class CapturedStream {
10399  public:
10400   // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)10401   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
10402 # if GTEST_OS_WINDOWS
10403     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
10404     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
10405 
10406     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
10407     const UINT success = ::GetTempFileNameA(temp_dir_path,
10408                                             "gtest_redir",
10409                                             0,  // Generate unique file name.
10410                                             temp_file_path);
10411     GTEST_CHECK_(success != 0)
10412         << "Unable to create a temporary file in " << temp_dir_path;
10413     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
10414     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
10415                                     << temp_file_path;
10416     filename_ = temp_file_path;
10417 # else
10418     // There's no guarantee that a test has write access to the current
10419     // directory, so we create the temporary file in the /tmp directory
10420     // instead. We use /tmp on most systems, and /sdcard on Android.
10421     // That's because Android doesn't have /tmp.
10422 #  if GTEST_OS_LINUX_ANDROID
10423     // Note: Android applications are expected to call the framework's
10424     // Context.getExternalStorageDirectory() method through JNI to get
10425     // the location of the world-writable SD Card directory. However,
10426     // this requires a Context handle, which cannot be retrieved
10427     // globally from native code. Doing so also precludes running the
10428     // code as part of a regular standalone executable, which doesn't
10429     // run in a Dalvik process (e.g. when running it through 'adb shell').
10430     //
10431     // The location /sdcard is directly accessible from native code
10432     // and is the only location (unofficially) supported by the Android
10433     // team. It's generally a symlink to the real SD Card mount point
10434     // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
10435     // other OEM-customized locations. Never rely on these, and always
10436     // use /sdcard.
10437     char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
10438 #  else
10439     char name_template[] = "/tmp/captured_stream.XXXXXX";
10440 #  endif  // GTEST_OS_LINUX_ANDROID
10441     const int captured_fd = mkstemp(name_template);
10442     filename_ = name_template;
10443 # endif  // GTEST_OS_WINDOWS
10444     fflush(NULL);
10445     dup2(captured_fd, fd_);
10446     close(captured_fd);
10447   }
10448 
~CapturedStream()10449   ~CapturedStream() {
10450     remove(filename_.c_str());
10451   }
10452 
GetCapturedString()10453   std::string GetCapturedString() {
10454     if (uncaptured_fd_ != -1) {
10455       // Restores the original stream.
10456       fflush(NULL);
10457       dup2(uncaptured_fd_, fd_);
10458       close(uncaptured_fd_);
10459       uncaptured_fd_ = -1;
10460     }
10461 
10462     FILE* const file = posix::FOpen(filename_.c_str(), "r");
10463     const std::string content = ReadEntireFile(file);
10464     posix::FClose(file);
10465     return content;
10466   }
10467 
10468  private:
10469   const int fd_;  // A stream to capture.
10470   int uncaptured_fd_;
10471   // Name of the temporary file holding the stderr output.
10472   ::std::string filename_;
10473 
10474   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
10475 };
10476 
10477 GTEST_DISABLE_MSC_DEPRECATED_POP_()
10478 
10479 static CapturedStream* g_captured_stderr = NULL;
10480 static CapturedStream* g_captured_stdout = NULL;
10481 
10482 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)10483 static void CaptureStream(int fd, const char* stream_name,
10484                           CapturedStream** stream) {
10485   if (*stream != NULL) {
10486     GTEST_LOG_(FATAL) << "Only one " << stream_name
10487                       << " capturer can exist at a time.";
10488   }
10489   *stream = new CapturedStream(fd);
10490 }
10491 
10492 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)10493 static std::string GetCapturedStream(CapturedStream** captured_stream) {
10494   const std::string content = (*captured_stream)->GetCapturedString();
10495 
10496   delete *captured_stream;
10497   *captured_stream = NULL;
10498 
10499   return content;
10500 }
10501 
10502 // Starts capturing stdout.
CaptureStdout()10503 void CaptureStdout() {
10504   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
10505 }
10506 
10507 // Starts capturing stderr.
CaptureStderr()10508 void CaptureStderr() {
10509   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
10510 }
10511 
10512 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()10513 std::string GetCapturedStdout() {
10514   return GetCapturedStream(&g_captured_stdout);
10515 }
10516 
10517 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()10518 std::string GetCapturedStderr() {
10519   return GetCapturedStream(&g_captured_stderr);
10520 }
10521 
10522 #endif  // GTEST_HAS_STREAM_REDIRECTION
10523 
10524 
10525 
10526 
10527 
GetFileSize(FILE * file)10528 size_t GetFileSize(FILE* file) {
10529   fseek(file, 0, SEEK_END);
10530   return static_cast<size_t>(ftell(file));
10531 }
10532 
ReadEntireFile(FILE * file)10533 std::string ReadEntireFile(FILE* file) {
10534   const size_t file_size = GetFileSize(file);
10535   char* const buffer = new char[file_size];
10536 
10537   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
10538   size_t bytes_read = 0;       // # of bytes read so far
10539 
10540   fseek(file, 0, SEEK_SET);
10541 
10542   // Keeps reading the file until we cannot read further or the
10543   // pre-determined file size is reached.
10544   do {
10545     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
10546     bytes_read += bytes_last_read;
10547   } while (bytes_last_read > 0 && bytes_read < file_size);
10548 
10549   const std::string content(buffer, bytes_read);
10550   delete[] buffer;
10551 
10552   return content;
10553 }
10554 
10555 #if GTEST_HAS_DEATH_TEST
10556 static const std::vector<std::string>* g_injected_test_argvs = NULL;  // Owned.
10557 
GetInjectableArgvs()10558 std::vector<std::string> GetInjectableArgvs() {
10559   if (g_injected_test_argvs != NULL) {
10560     return *g_injected_test_argvs;
10561   }
10562   return GetArgvs();
10563 }
10564 
SetInjectableArgvs(const std::vector<std::string> * new_argvs)10565 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
10566   if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
10567   g_injected_test_argvs = new_argvs;
10568 }
10569 
SetInjectableArgvs(const std::vector<std::string> & new_argvs)10570 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
10571   SetInjectableArgvs(
10572       new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10573 }
10574 
10575 #if GTEST_HAS_GLOBAL_STRING
SetInjectableArgvs(const std::vector<::string> & new_argvs)10576 void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
10577   SetInjectableArgvs(
10578       new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10579 }
10580 #endif  // GTEST_HAS_GLOBAL_STRING
10581 
ClearInjectableArgvs()10582 void ClearInjectableArgvs() {
10583   delete g_injected_test_argvs;
10584   g_injected_test_argvs = NULL;
10585 }
10586 #endif  // GTEST_HAS_DEATH_TEST
10587 
10588 #if GTEST_OS_WINDOWS_MOBILE
10589 namespace posix {
Abort()10590 void Abort() {
10591   DebugBreak();
10592   TerminateProcess(GetCurrentProcess(), 1);
10593 }
10594 }  // namespace posix
10595 #endif  // GTEST_OS_WINDOWS_MOBILE
10596 
10597 // Returns the name of the environment variable corresponding to the
10598 // given flag.  For example, FlagToEnvVar("foo") will return
10599 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)10600 static std::string FlagToEnvVar(const char* flag) {
10601   const std::string full_flag =
10602       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
10603 
10604   Message env_var;
10605   for (size_t i = 0; i != full_flag.length(); i++) {
10606     env_var << ToUpper(full_flag.c_str()[i]);
10607   }
10608 
10609   return env_var.GetString();
10610 }
10611 
10612 // Parses 'str' for a 32-bit signed integer.  If successful, writes
10613 // the result to *value and returns true; otherwise leaves *value
10614 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)10615 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
10616   // Parses the environment variable as a decimal integer.
10617   char* end = NULL;
10618   const long long_value = strtol(str, &end, 10);  // NOLINT
10619 
10620   // Has strtol() consumed all characters in the string?
10621   if (*end != '\0') {
10622     // No - an invalid character was encountered.
10623     Message msg;
10624     msg << "WARNING: " << src_text
10625         << " is expected to be a 32-bit integer, but actually"
10626         << " has value \"" << str << "\".\n";
10627     printf("%s", msg.GetString().c_str());
10628     fflush(stdout);
10629     return false;
10630   }
10631 
10632   // Is the parsed value in the range of an Int32?
10633   const Int32 result = static_cast<Int32>(long_value);
10634   if (long_value == LONG_MAX || long_value == LONG_MIN ||
10635       // The parsed value overflows as a long.  (strtol() returns
10636       // LONG_MAX or LONG_MIN when the input overflows.)
10637       result != long_value
10638       // The parsed value overflows as an Int32.
10639       ) {
10640     Message msg;
10641     msg << "WARNING: " << src_text
10642         << " is expected to be a 32-bit integer, but actually"
10643         << " has value " << str << ", which overflows.\n";
10644     printf("%s", msg.GetString().c_str());
10645     fflush(stdout);
10646     return false;
10647   }
10648 
10649   *value = result;
10650   return true;
10651 }
10652 
10653 // Reads and returns the Boolean environment variable corresponding to
10654 // the given flag; if it's not set, returns default_value.
10655 //
10656 // The value is considered true iff it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)10657 bool BoolFromGTestEnv(const char* flag, bool default_value) {
10658 #if defined(GTEST_GET_BOOL_FROM_ENV_)
10659   return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
10660 #else
10661   const std::string env_var = FlagToEnvVar(flag);
10662   const char* const string_value = posix::GetEnv(env_var.c_str());
10663   return string_value == NULL ?
10664       default_value : strcmp(string_value, "0") != 0;
10665 #endif  // defined(GTEST_GET_BOOL_FROM_ENV_)
10666 }
10667 
10668 // Reads and returns a 32-bit integer stored in the environment
10669 // variable corresponding to the given flag; if it isn't set or
10670 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)10671 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
10672 #if defined(GTEST_GET_INT32_FROM_ENV_)
10673   return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
10674 #else
10675   const std::string env_var = FlagToEnvVar(flag);
10676   const char* const string_value = posix::GetEnv(env_var.c_str());
10677   if (string_value == NULL) {
10678     // The environment variable is not set.
10679     return default_value;
10680   }
10681 
10682   Int32 result = default_value;
10683   if (!ParseInt32(Message() << "Environment variable " << env_var,
10684                   string_value, &result)) {
10685     printf("The default value %s is used.\n",
10686            (Message() << default_value).GetString().c_str());
10687     fflush(stdout);
10688     return default_value;
10689   }
10690 
10691   return result;
10692 #endif  // defined(GTEST_GET_INT32_FROM_ENV_)
10693 }
10694 
10695 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
10696 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
10697 // system.  The value of XML_OUTPUT_FILE is a filename without the
10698 // "xml:" prefix of GTEST_OUTPUT.
10699 // Note that this is meant to be called at the call site so it does
10700 // not check that the flag is 'output'
10701 // In essence this checks an env variable called XML_OUTPUT_FILE
10702 // and if it is set we prepend "xml:" to its value, if it not set we return ""
OutputFlagAlsoCheckEnvVar()10703 std::string OutputFlagAlsoCheckEnvVar(){
10704   std::string default_value_for_output_flag = "";
10705   const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
10706   if (NULL != xml_output_file_env) {
10707     default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
10708   }
10709   return default_value_for_output_flag;
10710 }
10711 
10712 // Reads and returns the string environment variable corresponding to
10713 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)10714 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
10715 #if defined(GTEST_GET_STRING_FROM_ENV_)
10716   return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
10717 #else
10718   const std::string env_var = FlagToEnvVar(flag);
10719   const char* const value = posix::GetEnv(env_var.c_str());
10720   return value == NULL ? default_value : value;
10721 #endif  // defined(GTEST_GET_STRING_FROM_ENV_)
10722 }
10723 
10724 }  // namespace internal
10725 }  // namespace testing
10726 // Copyright 2007, Google Inc.
10727 // All rights reserved.
10728 //
10729 // Redistribution and use in source and binary forms, with or without
10730 // modification, are permitted provided that the following conditions are
10731 // met:
10732 //
10733 //     * Redistributions of source code must retain the above copyright
10734 // notice, this list of conditions and the following disclaimer.
10735 //     * Redistributions in binary form must reproduce the above
10736 // copyright notice, this list of conditions and the following disclaimer
10737 // in the documentation and/or other materials provided with the
10738 // distribution.
10739 //     * Neither the name of Google Inc. nor the names of its
10740 // contributors may be used to endorse or promote products derived from
10741 // this software without specific prior written permission.
10742 //
10743 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10744 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10745 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10746 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10747 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10748 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10749 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10750 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10751 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10752 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10753 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10754 
10755 
10756 // Google Test - The Google C++ Testing and Mocking Framework
10757 //
10758 // This file implements a universal value printer that can print a
10759 // value of any type T:
10760 //
10761 //   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
10762 //
10763 // It uses the << operator when possible, and prints the bytes in the
10764 // object otherwise.  A user can override its behavior for a class
10765 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
10766 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
10767 // defines Foo.
10768 
10769 #include <stdio.h>
10770 #include <cctype>
10771 #include <cwchar>
10772 #include <ostream>  // NOLINT
10773 #include <string>
10774 
10775 namespace testing {
10776 
10777 namespace {
10778 
10779 using ::std::ostream;
10780 
10781 // Prints a segment of bytes in the given object.
10782 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10783 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10784 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintByteSegmentInObjectTo(const unsigned char * obj_bytes,size_t start,size_t count,ostream * os)10785 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
10786                                 size_t count, ostream* os) {
10787   char text[5] = "";
10788   for (size_t i = 0; i != count; i++) {
10789     const size_t j = start + i;
10790     if (i != 0) {
10791       // Organizes the bytes into groups of 2 for easy parsing by
10792       // human.
10793       if ((j % 2) == 0)
10794         *os << ' ';
10795       else
10796         *os << '-';
10797     }
10798     GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
10799     *os << text;
10800   }
10801 }
10802 
10803 // Prints the bytes in the given value to the given ostream.
PrintBytesInObjectToImpl(const unsigned char * obj_bytes,size_t count,ostream * os)10804 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
10805                               ostream* os) {
10806   // Tells the user how big the object is.
10807   *os << count << "-byte object <";
10808 
10809   const size_t kThreshold = 132;
10810   const size_t kChunkSize = 64;
10811   // If the object size is bigger than kThreshold, we'll have to omit
10812   // some details by printing only the first and the last kChunkSize
10813   // bytes.
10814   // FIXME: let the user control the threshold using a flag.
10815   if (count < kThreshold) {
10816     PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
10817   } else {
10818     PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
10819     *os << " ... ";
10820     // Rounds up to 2-byte boundary.
10821     const size_t resume_pos = (count - kChunkSize + 1)/2*2;
10822     PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
10823   }
10824   *os << ">";
10825 }
10826 
10827 }  // namespace
10828 
10829 namespace internal2 {
10830 
10831 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
10832 // given object.  The delegation simplifies the implementation, which
10833 // uses the << operator and thus is easier done outside of the
10834 // ::testing::internal namespace, which contains a << operator that
10835 // sometimes conflicts with the one in STL.
PrintBytesInObjectTo(const unsigned char * obj_bytes,size_t count,ostream * os)10836 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
10837                           ostream* os) {
10838   PrintBytesInObjectToImpl(obj_bytes, count, os);
10839 }
10840 
10841 }  // namespace internal2
10842 
10843 namespace internal {
10844 
10845 // Depending on the value of a char (or wchar_t), we print it in one
10846 // of three formats:
10847 //   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
10848 //   - as a hexadecimal escape sequence (e.g. '\x7F'), or
10849 //   - as a special escape sequence (e.g. '\r', '\n').
10850 enum CharFormat {
10851   kAsIs,
10852   kHexEscape,
10853   kSpecialEscape
10854 };
10855 
10856 // Returns true if c is a printable ASCII character.  We test the
10857 // value of c directly instead of calling isprint(), which is buggy on
10858 // Windows Mobile.
IsPrintableAscii(wchar_t c)10859 inline bool IsPrintableAscii(wchar_t c) {
10860   return 0x20 <= c && c <= 0x7E;
10861 }
10862 
10863 // Prints a wide or narrow char c as a character literal without the
10864 // quotes, escaping it when necessary; returns how c was formatted.
10865 // The template argument UnsignedChar is the unsigned version of Char,
10866 // which is the type of c.
10867 template <typename UnsignedChar, typename Char>
PrintAsCharLiteralTo(Char c,ostream * os)10868 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
10869   switch (static_cast<wchar_t>(c)) {
10870     case L'\0':
10871       *os << "\\0";
10872       break;
10873     case L'\'':
10874       *os << "\\'";
10875       break;
10876     case L'\\':
10877       *os << "\\\\";
10878       break;
10879     case L'\a':
10880       *os << "\\a";
10881       break;
10882     case L'\b':
10883       *os << "\\b";
10884       break;
10885     case L'\f':
10886       *os << "\\f";
10887       break;
10888     case L'\n':
10889       *os << "\\n";
10890       break;
10891     case L'\r':
10892       *os << "\\r";
10893       break;
10894     case L'\t':
10895       *os << "\\t";
10896       break;
10897     case L'\v':
10898       *os << "\\v";
10899       break;
10900     default:
10901       if (IsPrintableAscii(c)) {
10902         *os << static_cast<char>(c);
10903         return kAsIs;
10904       } else {
10905         ostream::fmtflags flags = os->flags();
10906         *os << "\\x" << std::hex << std::uppercase
10907             << static_cast<int>(static_cast<UnsignedChar>(c));
10908         os->flags(flags);
10909         return kHexEscape;
10910       }
10911   }
10912   return kSpecialEscape;
10913 }
10914 
10915 // Prints a wchar_t c as if it's part of a string literal, escaping it when
10916 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(wchar_t c,ostream * os)10917 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
10918   switch (c) {
10919     case L'\'':
10920       *os << "'";
10921       return kAsIs;
10922     case L'"':
10923       *os << "\\\"";
10924       return kSpecialEscape;
10925     default:
10926       return PrintAsCharLiteralTo<wchar_t>(c, os);
10927   }
10928 }
10929 
10930 // Prints a char c as if it's part of a string literal, escaping it when
10931 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char c,ostream * os)10932 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
10933   return PrintAsStringLiteralTo(
10934       static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
10935 }
10936 
10937 // Prints a wide or narrow character c and its code.  '\0' is printed
10938 // as "'\\0'", other unprintable characters are also properly escaped
10939 // using the standard C++ escape sequence.  The template argument
10940 // UnsignedChar is the unsigned version of Char, which is the type of c.
10941 template <typename UnsignedChar, typename Char>
PrintCharAndCodeTo(Char c,ostream * os)10942 void PrintCharAndCodeTo(Char c, ostream* os) {
10943   // First, print c as a literal in the most readable form we can find.
10944   *os << ((sizeof(c) > 1) ? "L'" : "'");
10945   const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
10946   *os << "'";
10947 
10948   // To aid user debugging, we also print c's code in decimal, unless
10949   // it's 0 (in which case c was printed as '\\0', making the code
10950   // obvious).
10951   if (c == 0)
10952     return;
10953   *os << " (" << static_cast<int>(c);
10954 
10955   // For more convenience, we print c's code again in hexadecimal,
10956   // unless c was already printed in the form '\x##' or the code is in
10957   // [1, 9].
10958   if (format == kHexEscape || (1 <= c && c <= 9)) {
10959     // Do nothing.
10960   } else {
10961     *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
10962   }
10963   *os << ")";
10964 }
10965 
PrintTo(unsigned char c,::std::ostream * os)10966 void PrintTo(unsigned char c, ::std::ostream* os) {
10967   PrintCharAndCodeTo<unsigned char>(c, os);
10968 }
PrintTo(signed char c,::std::ostream * os)10969 void PrintTo(signed char c, ::std::ostream* os) {
10970   PrintCharAndCodeTo<unsigned char>(c, os);
10971 }
10972 
10973 // Prints a wchar_t as a symbol if it is printable or as its internal
10974 // code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
PrintTo(wchar_t wc,ostream * os)10975 void PrintTo(wchar_t wc, ostream* os) {
10976   PrintCharAndCodeTo<wchar_t>(wc, os);
10977 }
10978 
10979 // Prints the given array of characters to the ostream.  CharType must be either
10980 // char or wchar_t.
10981 // The array starts at begin, the length is len, it may include '\0' characters
10982 // and may not be NUL-terminated.
10983 template <typename CharType>
10984 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10985 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10986 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintCharsAsStringTo(const CharType * begin,size_t len,ostream * os)10987 static CharFormat PrintCharsAsStringTo(
10988     const CharType* begin, size_t len, ostream* os) {
10989   const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
10990   *os << kQuoteBegin;
10991   bool is_previous_hex = false;
10992   CharFormat print_format = kAsIs;
10993   for (size_t index = 0; index < len; ++index) {
10994     const CharType cur = begin[index];
10995     if (is_previous_hex && IsXDigit(cur)) {
10996       // Previous character is of '\x..' form and this character can be
10997       // interpreted as another hexadecimal digit in its number. Break string to
10998       // disambiguate.
10999       *os << "\" " << kQuoteBegin;
11000     }
11001     is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
11002     // Remember if any characters required hex escaping.
11003     if (is_previous_hex) {
11004       print_format = kHexEscape;
11005     }
11006   }
11007   *os << "\"";
11008   return print_format;
11009 }
11010 
11011 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
11012 // 'begin'.  CharType must be either char or wchar_t.
11013 template <typename CharType>
11014 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11015 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11016 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
UniversalPrintCharArray(const CharType * begin,size_t len,ostream * os)11017 static void UniversalPrintCharArray(
11018     const CharType* begin, size_t len, ostream* os) {
11019   // The code
11020   //   const char kFoo[] = "foo";
11021   // generates an array of 4, not 3, elements, with the last one being '\0'.
11022   //
11023   // Therefore when printing a char array, we don't print the last element if
11024   // it's '\0', such that the output matches the string literal as it's
11025   // written in the source code.
11026   if (len > 0 && begin[len - 1] == '\0') {
11027     PrintCharsAsStringTo(begin, len - 1, os);
11028     return;
11029   }
11030 
11031   // If, however, the last element in the array is not '\0', e.g.
11032   //    const char kFoo[] = { 'f', 'o', 'o' };
11033   // we must print the entire array.  We also print a message to indicate
11034   // that the array is not NUL-terminated.
11035   PrintCharsAsStringTo(begin, len, os);
11036   *os << " (no terminating NUL)";
11037 }
11038 
11039 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
UniversalPrintArray(const char * begin,size_t len,ostream * os)11040 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
11041   UniversalPrintCharArray(begin, len, os);
11042 }
11043 
11044 // Prints a (const) wchar_t array of 'len' elements, starting at address
11045 // 'begin'.
UniversalPrintArray(const wchar_t * begin,size_t len,ostream * os)11046 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
11047   UniversalPrintCharArray(begin, len, os);
11048 }
11049 
11050 // Prints the given C string to the ostream.
PrintTo(const char * s,ostream * os)11051 void PrintTo(const char* s, ostream* os) {
11052   if (s == NULL) {
11053     *os << "NULL";
11054   } else {
11055     *os << ImplicitCast_<const void*>(s) << " pointing to ";
11056     PrintCharsAsStringTo(s, strlen(s), os);
11057   }
11058 }
11059 
11060 // MSVC compiler can be configured to define whar_t as a typedef
11061 // of unsigned short. Defining an overload for const wchar_t* in that case
11062 // would cause pointers to unsigned shorts be printed as wide strings,
11063 // possibly accessing more memory than intended and causing invalid
11064 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
11065 // wchar_t is implemented as a native type.
11066 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
11067 // Prints the given wide C string to the ostream.
PrintTo(const wchar_t * s,ostream * os)11068 void PrintTo(const wchar_t* s, ostream* os) {
11069   if (s == NULL) {
11070     *os << "NULL";
11071   } else {
11072     *os << ImplicitCast_<const void*>(s) << " pointing to ";
11073     PrintCharsAsStringTo(s, std::wcslen(s), os);
11074   }
11075 }
11076 #endif  // wchar_t is native
11077 
11078 namespace {
11079 
ContainsUnprintableControlCodes(const char * str,size_t length)11080 bool ContainsUnprintableControlCodes(const char* str, size_t length) {
11081   const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11082 
11083   for (size_t i = 0; i < length; i++) {
11084     unsigned char ch = *s++;
11085     if (std::iscntrl(ch)) {
11086         switch (ch) {
11087         case '\t':
11088         case '\n':
11089         case '\r':
11090           break;
11091         default:
11092           return true;
11093         }
11094       }
11095   }
11096   return false;
11097 }
11098 
IsUTF8TrailByte(unsigned char t)11099 bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
11100 
IsValidUTF8(const char * str,size_t length)11101 bool IsValidUTF8(const char* str, size_t length) {
11102   const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11103 
11104   for (size_t i = 0; i < length;) {
11105     unsigned char lead = s[i++];
11106 
11107     if (lead <= 0x7f) {
11108       continue;  // single-byte character (ASCII) 0..7F
11109     }
11110     if (lead < 0xc2) {
11111       return false;  // trail byte or non-shortest form
11112     } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
11113       ++i;  // 2-byte character
11114     } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
11115                IsUTF8TrailByte(s[i]) &&
11116                IsUTF8TrailByte(s[i + 1]) &&
11117                // check for non-shortest form and surrogate
11118                (lead != 0xe0 || s[i] >= 0xa0) &&
11119                (lead != 0xed || s[i] < 0xa0)) {
11120       i += 2;  // 3-byte character
11121     } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
11122                IsUTF8TrailByte(s[i]) &&
11123                IsUTF8TrailByte(s[i + 1]) &&
11124                IsUTF8TrailByte(s[i + 2]) &&
11125                // check for non-shortest form
11126                (lead != 0xf0 || s[i] >= 0x90) &&
11127                (lead != 0xf4 || s[i] < 0x90)) {
11128       i += 3;  // 4-byte character
11129     } else {
11130       return false;
11131     }
11132   }
11133   return true;
11134 }
11135 
ConditionalPrintAsText(const char * str,size_t length,ostream * os)11136 void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
11137   if (!ContainsUnprintableControlCodes(str, length) &&
11138       IsValidUTF8(str, length)) {
11139     *os << "\n    As Text: \"" << str << "\"";
11140   }
11141 }
11142 
11143 }  // anonymous namespace
11144 
11145 // Prints a ::string object.
11146 #if GTEST_HAS_GLOBAL_STRING
PrintStringTo(const::string & s,ostream * os)11147 void PrintStringTo(const ::string& s, ostream* os) {
11148   if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11149     if (GTEST_FLAG(print_utf8)) {
11150       ConditionalPrintAsText(s.data(), s.size(), os);
11151     }
11152   }
11153 }
11154 #endif  // GTEST_HAS_GLOBAL_STRING
11155 
PrintStringTo(const::std::string & s,ostream * os)11156 void PrintStringTo(const ::std::string& s, ostream* os) {
11157   if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11158     if (GTEST_FLAG(print_utf8)) {
11159       ConditionalPrintAsText(s.data(), s.size(), os);
11160     }
11161   }
11162 }
11163 
11164 // Prints a ::wstring object.
11165 #if GTEST_HAS_GLOBAL_WSTRING
PrintWideStringTo(const::wstring & s,ostream * os)11166 void PrintWideStringTo(const ::wstring& s, ostream* os) {
11167   PrintCharsAsStringTo(s.data(), s.size(), os);
11168 }
11169 #endif  // GTEST_HAS_GLOBAL_WSTRING
11170 
11171 #if GTEST_HAS_STD_WSTRING
PrintWideStringTo(const::std::wstring & s,ostream * os)11172 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
11173   PrintCharsAsStringTo(s.data(), s.size(), os);
11174 }
11175 #endif  // GTEST_HAS_STD_WSTRING
11176 
11177 }  // namespace internal
11178 
11179 }  // namespace testing
11180 // Copyright 2008, Google Inc.
11181 // All rights reserved.
11182 //
11183 // Redistribution and use in source and binary forms, with or without
11184 // modification, are permitted provided that the following conditions are
11185 // met:
11186 //
11187 //     * Redistributions of source code must retain the above copyright
11188 // notice, this list of conditions and the following disclaimer.
11189 //     * Redistributions in binary form must reproduce the above
11190 // copyright notice, this list of conditions and the following disclaimer
11191 // in the documentation and/or other materials provided with the
11192 // distribution.
11193 //     * Neither the name of Google Inc. nor the names of its
11194 // contributors may be used to endorse or promote products derived from
11195 // this software without specific prior written permission.
11196 //
11197 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11198 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11199 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11200 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11201 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11202 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11203 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11204 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11205 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11206 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11207 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11208 
11209 //
11210 // The Google C++ Testing and Mocking Framework (Google Test)
11211 
11212 
11213 namespace testing {
11214 
11215 using internal::GetUnitTestImpl;
11216 
11217 // Gets the summary of the failure message by omitting the stack trace
11218 // in it.
ExtractSummary(const char * message)11219 std::string TestPartResult::ExtractSummary(const char* message) {
11220   const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
11221   return stack_trace == NULL ? message :
11222       std::string(message, stack_trace);
11223 }
11224 
11225 // Prints a TestPartResult object.
operator <<(std::ostream & os,const TestPartResult & result)11226 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
11227   return os
11228       << result.file_name() << ":" << result.line_number() << ": "
11229       << (result.type() == TestPartResult::kSuccess ? "Success" :
11230           result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
11231           "Non-fatal failure") << ":\n"
11232       << result.message() << std::endl;
11233 }
11234 
11235 // Appends a TestPartResult to the array.
Append(const TestPartResult & result)11236 void TestPartResultArray::Append(const TestPartResult& result) {
11237   array_.push_back(result);
11238 }
11239 
11240 // Returns the TestPartResult at the given index (0-based).
GetTestPartResult(int index) const11241 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
11242   if (index < 0 || index >= size()) {
11243     printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
11244     internal::posix::Abort();
11245   }
11246 
11247   return array_[index];
11248 }
11249 
11250 // Returns the number of TestPartResult objects in the array.
size() const11251 int TestPartResultArray::size() const {
11252   return static_cast<int>(array_.size());
11253 }
11254 
11255 namespace internal {
11256 
HasNewFatalFailureHelper()11257 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
11258     : has_new_fatal_failure_(false),
11259       original_reporter_(GetUnitTestImpl()->
11260                          GetTestPartResultReporterForCurrentThread()) {
11261   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
11262 }
11263 
~HasNewFatalFailureHelper()11264 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
11265   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
11266       original_reporter_);
11267 }
11268 
ReportTestPartResult(const TestPartResult & result)11269 void HasNewFatalFailureHelper::ReportTestPartResult(
11270     const TestPartResult& result) {
11271   if (result.fatally_failed())
11272     has_new_fatal_failure_ = true;
11273   original_reporter_->ReportTestPartResult(result);
11274 }
11275 
11276 }  // namespace internal
11277 
11278 }  // namespace testing
11279 // Copyright 2008 Google Inc.
11280 // All Rights Reserved.
11281 //
11282 // Redistribution and use in source and binary forms, with or without
11283 // modification, are permitted provided that the following conditions are
11284 // met:
11285 //
11286 //     * Redistributions of source code must retain the above copyright
11287 // notice, this list of conditions and the following disclaimer.
11288 //     * Redistributions in binary form must reproduce the above
11289 // copyright notice, this list of conditions and the following disclaimer
11290 // in the documentation and/or other materials provided with the
11291 // distribution.
11292 //     * Neither the name of Google Inc. nor the names of its
11293 // contributors may be used to endorse or promote products derived from
11294 // this software without specific prior written permission.
11295 //
11296 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11297 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11298 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11299 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11300 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11301 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11302 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11303 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11304 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11305 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11306 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11307 
11308 
11309 
11310 
11311 namespace testing {
11312 namespace internal {
11313 
11314 #if GTEST_HAS_TYPED_TEST_P
11315 
11316 // Skips to the first non-space char in str. Returns an empty string if str
11317 // contains only whitespace characters.
SkipSpaces(const char * str)11318 static const char* SkipSpaces(const char* str) {
11319   while (IsSpace(*str))
11320     str++;
11321   return str;
11322 }
11323 
SplitIntoTestNames(const char * src)11324 static std::vector<std::string> SplitIntoTestNames(const char* src) {
11325   std::vector<std::string> name_vec;
11326   src = SkipSpaces(src);
11327   for (; src != NULL; src = SkipComma(src)) {
11328     name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
11329   }
11330   return name_vec;
11331 }
11332 
11333 // Verifies that registered_tests match the test names in
11334 // registered_tests_; returns registered_tests if successful, or
11335 // aborts the program otherwise.
VerifyRegisteredTestNames(const char * file,int line,const char * registered_tests)11336 const char* TypedTestCasePState::VerifyRegisteredTestNames(
11337     const char* file, int line, const char* registered_tests) {
11338   typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
11339   registered_ = true;
11340 
11341   std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
11342 
11343   Message errors;
11344 
11345   std::set<std::string> tests;
11346   for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
11347        name_it != name_vec.end(); ++name_it) {
11348     const std::string& name = *name_it;
11349     if (tests.count(name) != 0) {
11350       errors << "Test " << name << " is listed more than once.\n";
11351       continue;
11352     }
11353 
11354     bool found = false;
11355     for (RegisteredTestIter it = registered_tests_.begin();
11356          it != registered_tests_.end();
11357          ++it) {
11358       if (name == it->first) {
11359         found = true;
11360         break;
11361       }
11362     }
11363 
11364     if (found) {
11365       tests.insert(name);
11366     } else {
11367       errors << "No test named " << name
11368              << " can be found in this test case.\n";
11369     }
11370   }
11371 
11372   for (RegisteredTestIter it = registered_tests_.begin();
11373        it != registered_tests_.end();
11374        ++it) {
11375     if (tests.count(it->first) == 0) {
11376       errors << "You forgot to list test " << it->first << ".\n";
11377     }
11378   }
11379 
11380   const std::string& errors_str = errors.GetString();
11381   if (errors_str != "") {
11382     fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
11383             errors_str.c_str());
11384     fflush(stderr);
11385     posix::Abort();
11386   }
11387 
11388   return registered_tests;
11389 }
11390 
11391 #endif  // GTEST_HAS_TYPED_TEST_P
11392 
11393 }  // namespace internal
11394 }  // namespace testing
11395