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 // Author: mheule@google.com (Markus Heule)
31 //
32 // Google C++ Testing Framework (Google Test)
33 //
34 // Sometimes it's desirable to build Google Test by compiling a single file.
35 // This file serves this purpose.
36 
37 // This line ensures that gtest.h can be compiled on its own, even
38 // when it's fused.
39 #include "gtest/gtest.h"
40 
41 // The following lines pull in the real gtest *.cc files.
42 // Copyright 2005, Google Inc.
43 // All rights reserved.
44 //
45 // Redistribution and use in source and binary forms, with or without
46 // modification, are permitted provided that the following conditions are
47 // met:
48 //
49 //     * Redistributions of source code must retain the above copyright
50 // notice, this list of conditions and the following disclaimer.
51 //     * Redistributions in binary form must reproduce the above
52 // copyright notice, this list of conditions and the following disclaimer
53 // in the documentation and/or other materials provided with the
54 // distribution.
55 //     * Neither the name of Google Inc. nor the names of its
56 // contributors may be used to endorse or promote products derived from
57 // this software without specific prior written permission.
58 //
59 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70 //
71 // Author: wan@google.com (Zhanyong Wan)
72 //
73 // The Google C++ Testing Framework (Google Test)
74 
75 // Copyright 2007, Google Inc.
76 // All rights reserved.
77 //
78 // Redistribution and use in source and binary forms, with or without
79 // modification, are permitted provided that the following conditions are
80 // met:
81 //
82 //     * Redistributions of source code must retain the above copyright
83 // notice, this list of conditions and the following disclaimer.
84 //     * Redistributions in binary form must reproduce the above
85 // copyright notice, this list of conditions and the following disclaimer
86 // in the documentation and/or other materials provided with the
87 // distribution.
88 //     * Neither the name of Google Inc. nor the names of its
89 // contributors may be used to endorse or promote products derived from
90 // this software without specific prior written permission.
91 //
92 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
93 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
94 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
95 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
96 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
99 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
100 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
101 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
102 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
103 //
104 // Author: wan@google.com (Zhanyong Wan)
105 //
106 // Utilities for testing Google Test itself and code that uses Google Test
107 // (e.g. frameworks built on top of Google Test).
108 
109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
111 
112 
113 namespace testing {
114 
115 // This helper class can be used to mock out Google Test failure reporting
116 // so that we can test Google Test or code that builds on Google Test.
117 //
118 // An object of this class appends a TestPartResult object to the
119 // TestPartResultArray object given in the constructor whenever a Google Test
120 // failure is reported. It can either intercept only failures that are
121 // generated in the same thread that created this object or it can intercept
122 // all generated failures. The scope of this mock object can be controlled with
123 // the second argument to the two arguments constructor.
124 class GTEST_API_ ScopedFakeTestPartResultReporter
125     : public TestPartResultReporterInterface {
126  public:
127   // The two possible mocking modes of this object.
128   enum InterceptMode {
129     INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
130     INTERCEPT_ALL_THREADS           // Intercepts all failures.
131   };
132 
133   // The c'tor sets this object as the test part result reporter used
134   // by Google Test.  The 'result' parameter specifies where to report the
135   // results. This reporter will only catch failures generated in the current
136   // thread. DEPRECATED
137   explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
138 
139   // Same as above, but you can choose the interception scope of this object.
140   ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
141                                    TestPartResultArray* result);
142 
143   // The d'tor restores the previous test part result reporter.
144   virtual ~ScopedFakeTestPartResultReporter();
145 
146   // Appends the TestPartResult object to the TestPartResultArray
147   // received in the constructor.
148   //
149   // This method is from the TestPartResultReporterInterface
150   // interface.
151   virtual void ReportTestPartResult(const TestPartResult& result);
152  private:
153   void Init();
154 
155   const InterceptMode intercept_mode_;
156   TestPartResultReporterInterface* old_reporter_;
157   TestPartResultArray* const result_;
158 
159   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
160 };
161 
162 namespace internal {
163 
164 // A helper class for implementing EXPECT_FATAL_FAILURE() and
165 // EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
166 // TestPartResultArray contains exactly one failure that has the given
167 // type and contains the given substring.  If that's not the case, a
168 // non-fatal failure will be generated.
169 class GTEST_API_ SingleFailureChecker {
170  public:
171   // The constructor remembers the arguments.
172   SingleFailureChecker(const TestPartResultArray* results,
173                        TestPartResult::Type type,
174                        const string& substr);
175   ~SingleFailureChecker();
176  private:
177   const TestPartResultArray* const results_;
178   const TestPartResult::Type type_;
179   const string substr_;
180 
181   GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
182 };
183 
184 }  // namespace internal
185 
186 }  // namespace testing
187 
188 // A set of macros for testing Google Test assertions or code that's expected
189 // to generate Google Test fatal failures.  It verifies that the given
190 // statement will cause exactly one fatal Google Test failure with 'substr'
191 // being part of the failure message.
192 //
193 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
194 // affects and considers failures generated in the current thread and
195 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
196 //
197 // The verification of the assertion is done correctly even when the statement
198 // throws an exception or aborts the current function.
199 //
200 // Known restrictions:
201 //   - 'statement' cannot reference local non-static variables or
202 //     non-static members of the current object.
203 //   - 'statement' cannot return a value.
204 //   - You cannot stream a failure message to this macro.
205 //
206 // Note that even though the implementations of the following two
207 // macros are much alike, we cannot refactor them to use a common
208 // helper macro, due to some peculiarity in how the preprocessor
209 // works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
210 // gtest_unittest.cc will fail to compile if we do that.
211 #define EXPECT_FATAL_FAILURE(statement, substr) \
212   do { \
213     class GTestExpectFatalFailureHelper {\
214      public:\
215       static void Execute() { statement; }\
216     };\
217     ::testing::TestPartResultArray gtest_failures;\
218     ::testing::internal::SingleFailureChecker gtest_checker(\
219         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
220     {\
221       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
222           ::testing::ScopedFakeTestPartResultReporter:: \
223           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
224       GTestExpectFatalFailureHelper::Execute();\
225     }\
226   } while (::testing::internal::AlwaysFalse())
227 
228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
229   do { \
230     class GTestExpectFatalFailureHelper {\
231      public:\
232       static void Execute() { statement; }\
233     };\
234     ::testing::TestPartResultArray gtest_failures;\
235     ::testing::internal::SingleFailureChecker gtest_checker(\
236         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
237     {\
238       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239           ::testing::ScopedFakeTestPartResultReporter:: \
240           INTERCEPT_ALL_THREADS, &gtest_failures);\
241       GTestExpectFatalFailureHelper::Execute();\
242     }\
243   } while (::testing::internal::AlwaysFalse())
244 
245 // A macro for testing Google Test assertions or code that's expected to
246 // generate Google Test non-fatal failures.  It asserts that the given
247 // statement will cause exactly one non-fatal Google Test failure with 'substr'
248 // being part of the failure message.
249 //
250 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
251 // affects and considers failures generated in the current thread and
252 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
253 //
254 // 'statement' is allowed to reference local variables and members of
255 // the current object.
256 //
257 // The verification of the assertion is done correctly even when the statement
258 // throws an exception or aborts the current function.
259 //
260 // Known restrictions:
261 //   - You cannot stream a failure message to this macro.
262 //
263 // Note that even though the implementations of the following two
264 // macros are much alike, we cannot refactor them to use a common
265 // helper macro, due to some peculiarity in how the preprocessor
266 // works.  If we do that, the code won't compile when the user gives
267 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
268 // expands to code containing an unprotected comma.  The
269 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
270 // catches that.
271 //
272 // For the same reason, we have to write
273 //   if (::testing::internal::AlwaysTrue()) { statement; }
274 // instead of
275 //   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
276 // to avoid an MSVC warning on unreachable code.
277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
278   do {\
279     ::testing::TestPartResultArray gtest_failures;\
280     ::testing::internal::SingleFailureChecker gtest_checker(\
281         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
282         (substr));\
283     {\
284       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
285           ::testing::ScopedFakeTestPartResultReporter:: \
286           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
287       if (::testing::internal::AlwaysTrue()) { statement; }\
288     }\
289   } while (::testing::internal::AlwaysFalse())
290 
291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
292   do {\
293     ::testing::TestPartResultArray gtest_failures;\
294     ::testing::internal::SingleFailureChecker gtest_checker(\
295         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
296         (substr));\
297     {\
298       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
299           ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
300           &gtest_failures);\
301       if (::testing::internal::AlwaysTrue()) { statement; }\
302     }\
303   } while (::testing::internal::AlwaysFalse())
304 
305 #endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
306 
307 #include <ctype.h>
308 #include <math.h>
309 #include <stdarg.h>
310 #include <stdio.h>
311 #include <stdlib.h>
312 #include <time.h>
313 #include <wchar.h>
314 #include <wctype.h>
315 
316 #include <algorithm>
317 #include <iomanip>
318 #include <limits>
319 #include <list>
320 #include <map>
321 #include <ostream>  // NOLINT
322 #include <sstream>
323 #include <vector>
324 
325 #if GTEST_OS_LINUX
326 
327 // TODO(kenton@google.com): Use autoconf to detect availability of
328 // gettimeofday().
329 # define GTEST_HAS_GETTIMEOFDAY_ 1
330 
331 # include <fcntl.h>  // NOLINT
332 # include <limits.h>  // NOLINT
333 # include <sched.h>  // NOLINT
334 // Declares vsnprintf().  This header is not available on Windows.
335 # include <strings.h>  // NOLINT
336 # include <sys/mman.h>  // NOLINT
337 # include <sys/time.h>  // NOLINT
338 # include <unistd.h>  // NOLINT
339 # include <string>
340 
341 #elif GTEST_OS_SYMBIAN
342 # define GTEST_HAS_GETTIMEOFDAY_ 1
343 # include <sys/time.h>  // NOLINT
344 
345 #elif GTEST_OS_ZOS
346 # define GTEST_HAS_GETTIMEOFDAY_ 1
347 # include <sys/time.h>  // NOLINT
348 
349 // On z/OS we additionally need strings.h for strcasecmp.
350 # include <strings.h>  // NOLINT
351 
352 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
353 
354 # include <windows.h>  // NOLINT
355 # undef min
356 
357 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
358 
359 # include <io.h>  // NOLINT
360 # include <sys/timeb.h>  // NOLINT
361 # include <sys/types.h>  // NOLINT
362 # include <sys/stat.h>  // NOLINT
363 
364 # if GTEST_OS_WINDOWS_MINGW
365 // MinGW has gettimeofday() but not _ftime64().
366 // TODO(kenton@google.com): Use autoconf to detect availability of
367 //   gettimeofday().
368 // TODO(kenton@google.com): There are other ways to get the time on
369 //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
370 //   supports these.  consider using them instead.
371 #  define GTEST_HAS_GETTIMEOFDAY_ 1
372 #  include <sys/time.h>  // NOLINT
373 # endif  // GTEST_OS_WINDOWS_MINGW
374 
375 // cpplint thinks that the header is already included, so we want to
376 // silence it.
377 # include <windows.h>  // NOLINT
378 # undef min
379 
380 #else
381 
382 // Assume other platforms have gettimeofday().
383 // TODO(kenton@google.com): Use autoconf to detect availability of
384 //   gettimeofday().
385 # define GTEST_HAS_GETTIMEOFDAY_ 1
386 
387 // cpplint thinks that the header is already included, so we want to
388 // silence it.
389 # include <sys/time.h>  // NOLINT
390 # include <unistd.h>  // NOLINT
391 
392 #endif  // GTEST_OS_LINUX
393 
394 #if GTEST_HAS_EXCEPTIONS
395 # include <stdexcept>
396 #endif
397 
398 #if GTEST_CAN_STREAM_RESULTS_
399 # include <arpa/inet.h>  // NOLINT
400 # include <netdb.h>  // NOLINT
401 # include <sys/socket.h>  // NOLINT
402 # include <sys/types.h>  // NOLINT
403 #endif
404 
405 // Indicates that this translation unit is part of Google Test's
406 // implementation.  It must come before gtest-internal-inl.h is
407 // included, or there will be a compiler error.  This trick is to
408 // prevent a user from accidentally including gtest-internal-inl.h in
409 // his code.
410 #define GTEST_IMPLEMENTATION_ 1
411 // Copyright 2005, Google Inc.
412 // All rights reserved.
413 //
414 // Redistribution and use in source and binary forms, with or without
415 // modification, are permitted provided that the following conditions are
416 // met:
417 //
418 //     * Redistributions of source code must retain the above copyright
419 // notice, this list of conditions and the following disclaimer.
420 //     * Redistributions in binary form must reproduce the above
421 // copyright notice, this list of conditions and the following disclaimer
422 // in the documentation and/or other materials provided with the
423 // distribution.
424 //     * Neither the name of Google Inc. nor the names of its
425 // contributors may be used to endorse or promote products derived from
426 // this software without specific prior written permission.
427 //
428 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
429 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
430 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
431 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
432 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
433 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
434 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
435 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
436 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
437 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
438 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
439 
440 // Utility functions and classes used by the Google C++ testing framework.
441 //
442 // Author: wan@google.com (Zhanyong Wan)
443 //
444 // This file contains purely Google Test's internal implementation.  Please
445 // DO NOT #INCLUDE IT IN A USER PROGRAM.
446 
447 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
448 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
449 
450 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
451 // part of Google Test's implementation; otherwise it's undefined.
452 #if !GTEST_IMPLEMENTATION_
453 // If this file is included from the user's code, just say no.
454 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
455 # error "It must not be included except by Google Test itself."
456 #endif  // GTEST_IMPLEMENTATION_
457 
458 #ifndef _WIN32_WCE
459 # include <errno.h>
460 #endif  // !_WIN32_WCE
461 #include <stddef.h>
462 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
463 #include <string.h>  // For memmove.
464 
465 #include <algorithm>
466 #include <string>
467 #include <vector>
468 
469 
470 #if GTEST_CAN_STREAM_RESULTS_
471 # include <arpa/inet.h>  // NOLINT
472 # include <netdb.h>  // NOLINT
473 #endif
474 
475 #if GTEST_OS_WINDOWS
476 # include <windows.h>  // NOLINT
477 #endif  // GTEST_OS_WINDOWS
478 
479 
480 namespace testing {
481 
482 // Declares the flags.
483 //
484 // We don't want the users to modify this flag in the code, but want
485 // Google Test's own unit tests to be able to access it. Therefore we
486 // declare it here as opposed to in gtest.h.
487 GTEST_DECLARE_bool_(death_test_use_fork);
488 
489 namespace internal {
490 
491 // The value of GetTestTypeId() as seen from within the Google Test
492 // library.  This is solely for testing GetTestTypeId().
493 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
494 
495 // Names of the flags (needed for parsing Google Test flags).
496 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
497 const char kBreakOnFailureFlag[] = "break_on_failure";
498 const char kCatchExceptionsFlag[] = "catch_exceptions";
499 const char kColorFlag[] = "color";
500 const char kFilterFlag[] = "filter";
501 const char kListTestsFlag[] = "list_tests";
502 const char kOutputFlag[] = "output";
503 const char kPrintTimeFlag[] = "print_time";
504 const char kRandomSeedFlag[] = "random_seed";
505 const char kRepeatFlag[] = "repeat";
506 const char kShuffleFlag[] = "shuffle";
507 const char kStackTraceDepthFlag[] = "stack_trace_depth";
508 const char kStreamResultToFlag[] = "stream_result_to";
509 const char kThrowOnFailureFlag[] = "throw_on_failure";
510 const char kFlagfileFlag[] = "flagfile";
511 
512 // A valid random seed must be in [1, kMaxRandomSeed].
513 const int kMaxRandomSeed = 99999;
514 
515 // g_help_flag is true iff the --help flag or an equivalent form is
516 // specified on the command line.
517 GTEST_API_ extern bool g_help_flag;
518 
519 // Returns the current time in milliseconds.
520 GTEST_API_ TimeInMillis GetTimeInMillis();
521 
522 // Returns true iff Google Test should use colors in the output.
523 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
524 
525 // Formats the given time in milliseconds as seconds.
526 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
527 
528 // Converts the given time in milliseconds to a date string in the ISO 8601
529 // format, without the timezone information.  N.B.: due to the use the
530 // non-reentrant localtime() function, this function is not thread safe.  Do
531 // not use it in any code that can be called from multiple threads.
532 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
533 
534 // Parses a string for an Int32 flag, in the form of "--flag=value".
535 //
536 // On success, stores the value of the flag in *value, and returns
537 // true.  On failure, returns false without changing *value.
538 GTEST_API_ bool ParseInt32Flag(
539     const char* str, const char* flag, Int32* value);
540 
541 // Returns a random seed in range [1, kMaxRandomSeed] based on the
542 // given --gtest_random_seed flag value.
GetRandomSeedFromFlag(Int32 random_seed_flag)543 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
544   const unsigned int raw_seed = (random_seed_flag == 0) ?
545       static_cast<unsigned int>(GetTimeInMillis()) :
546       static_cast<unsigned int>(random_seed_flag);
547 
548   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
549   // it's easy to type.
550   const int normalized_seed =
551       static_cast<int>((raw_seed - 1U) %
552                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
553   return normalized_seed;
554 }
555 
556 // Returns the first valid random seed after 'seed'.  The behavior is
557 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
558 // considered to be 1.
GetNextRandomSeed(int seed)559 inline int GetNextRandomSeed(int seed) {
560   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
561       << "Invalid random seed " << seed << " - must be in [1, "
562       << kMaxRandomSeed << "].";
563   const int next_seed = seed + 1;
564   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
565 }
566 
567 // This class saves the values of all Google Test flags in its c'tor, and
568 // restores them in its d'tor.
569 class GTestFlagSaver {
570  public:
571   // The c'tor.
GTestFlagSaver()572   GTestFlagSaver() {
573     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
574     break_on_failure_ = GTEST_FLAG(break_on_failure);
575     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
576     color_ = GTEST_FLAG(color);
577     death_test_style_ = GTEST_FLAG(death_test_style);
578     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
579     filter_ = GTEST_FLAG(filter);
580     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
581     list_tests_ = GTEST_FLAG(list_tests);
582     output_ = GTEST_FLAG(output);
583     print_time_ = GTEST_FLAG(print_time);
584     random_seed_ = GTEST_FLAG(random_seed);
585     repeat_ = GTEST_FLAG(repeat);
586     shuffle_ = GTEST_FLAG(shuffle);
587     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
588     stream_result_to_ = GTEST_FLAG(stream_result_to);
589     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
590   }
591 
592   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver()593   ~GTestFlagSaver() {
594     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
595     GTEST_FLAG(break_on_failure) = break_on_failure_;
596     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
597     GTEST_FLAG(color) = color_;
598     GTEST_FLAG(death_test_style) = death_test_style_;
599     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
600     GTEST_FLAG(filter) = filter_;
601     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
602     GTEST_FLAG(list_tests) = list_tests_;
603     GTEST_FLAG(output) = output_;
604     GTEST_FLAG(print_time) = print_time_;
605     GTEST_FLAG(random_seed) = random_seed_;
606     GTEST_FLAG(repeat) = repeat_;
607     GTEST_FLAG(shuffle) = shuffle_;
608     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
609     GTEST_FLAG(stream_result_to) = stream_result_to_;
610     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
611   }
612 
613  private:
614   // Fields for saving the original values of flags.
615   bool also_run_disabled_tests_;
616   bool break_on_failure_;
617   bool catch_exceptions_;
618   std::string color_;
619   std::string death_test_style_;
620   bool death_test_use_fork_;
621   std::string filter_;
622   std::string internal_run_death_test_;
623   bool list_tests_;
624   std::string output_;
625   bool print_time_;
626   internal::Int32 random_seed_;
627   internal::Int32 repeat_;
628   bool shuffle_;
629   internal::Int32 stack_trace_depth_;
630   std::string stream_result_to_;
631   bool throw_on_failure_;
632 } GTEST_ATTRIBUTE_UNUSED_;
633 
634 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
635 // code_point parameter is of type UInt32 because wchar_t may not be
636 // wide enough to contain a code point.
637 // If the code_point is not a valid Unicode code point
638 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
639 // to "(Invalid Unicode 0xXXXXXXXX)".
640 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
641 
642 // Converts a wide string to a narrow string in UTF-8 encoding.
643 // The wide string is assumed to have the following encoding:
644 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
645 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
646 // Parameter str points to a null-terminated wide string.
647 // Parameter num_chars may additionally limit the number
648 // of wchar_t characters processed. -1 is used when the entire string
649 // should be processed.
650 // If the string contains code points that are not valid Unicode code points
651 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
652 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
653 // and contains invalid UTF-16 surrogate pairs, values in those pairs
654 // will be encoded as individual Unicode characters from Basic Normal Plane.
655 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
656 
657 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
658 // if the variable is present. If a file already exists at this location, this
659 // function will write over it. If the variable is present, but the file cannot
660 // be created, prints an error and exits.
661 void WriteToShardStatusFileIfNeeded();
662 
663 // Checks whether sharding is enabled by examining the relevant
664 // environment variable values. If the variables are present,
665 // but inconsistent (e.g., shard_index >= total_shards), prints
666 // an error and exits. If in_subprocess_for_death_test, sharding is
667 // disabled because it must only be applied to the original test
668 // process. Otherwise, we could filter out death tests we intended to execute.
669 GTEST_API_ bool ShouldShard(const char* total_shards_str,
670                             const char* shard_index_str,
671                             bool in_subprocess_for_death_test);
672 
673 // Parses the environment variable var as an Int32. If it is unset,
674 // returns default_val. If it is not an Int32, prints an error and
675 // and aborts.
676 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
677 
678 // Given the total number of shards, the shard index, and the test id,
679 // returns true iff the test should be run on this shard. The test id is
680 // some arbitrary but unique non-negative integer assigned to each test
681 // method. Assumes that 0 <= shard_index < total_shards.
682 GTEST_API_ bool ShouldRunTestOnShard(
683     int total_shards, int shard_index, int test_id);
684 
685 // STL container utilities.
686 
687 // Returns the number of elements in the given container that satisfy
688 // the given predicate.
689 template <class Container, typename Predicate>
CountIf(const Container & c,Predicate predicate)690 inline int CountIf(const Container& c, Predicate predicate) {
691   // Implemented as an explicit loop since std::count_if() in libCstd on
692   // Solaris has a non-standard signature.
693   int count = 0;
694   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
695     if (predicate(*it))
696       ++count;
697   }
698   return count;
699 }
700 
701 // Applies a function/functor to each element in the container.
702 template <class Container, typename Functor>
ForEach(const Container & c,Functor functor)703 void ForEach(const Container& c, Functor functor) {
704   std::for_each(c.begin(), c.end(), functor);
705 }
706 
707 // Returns the i-th element of the vector, or default_value if i is not
708 // in range [0, v.size()).
709 template <typename E>
GetElementOr(const std::vector<E> & v,int i,E default_value)710 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
711   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
712 }
713 
714 // Performs an in-place shuffle of a range of the vector's elements.
715 // 'begin' and 'end' are element indices as an STL-style range;
716 // i.e. [begin, end) are shuffled, where 'end' == size() means to
717 // shuffle to the end of the vector.
718 template <typename E>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)719 void ShuffleRange(internal::Random* random, int begin, int end,
720                   std::vector<E>* v) {
721   const int size = static_cast<int>(v->size());
722   GTEST_CHECK_(0 <= begin && begin <= size)
723       << "Invalid shuffle range start " << begin << ": must be in range [0, "
724       << size << "].";
725   GTEST_CHECK_(begin <= end && end <= size)
726       << "Invalid shuffle range finish " << end << ": must be in range ["
727       << begin << ", " << size << "].";
728 
729   // Fisher-Yates shuffle, from
730   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
731   for (int range_width = end - begin; range_width >= 2; range_width--) {
732     const int last_in_range = begin + range_width - 1;
733     const int selected = begin + random->Generate(range_width);
734     std::swap((*v)[selected], (*v)[last_in_range]);
735   }
736 }
737 
738 // Performs an in-place shuffle of the vector's elements.
739 template <typename E>
Shuffle(internal::Random * random,std::vector<E> * v)740 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
741   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
742 }
743 
744 // A function for deleting an object.  Handy for being used as a
745 // functor.
746 template <typename T>
Delete(T * x)747 static void Delete(T* x) {
748   delete x;
749 }
750 
751 // A predicate that checks the key of a TestProperty against a known key.
752 //
753 // TestPropertyKeyIs is copyable.
754 class TestPropertyKeyIs {
755  public:
756   // Constructor.
757   //
758   // TestPropertyKeyIs has NO default constructor.
TestPropertyKeyIs(const std::string & key)759   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
760 
761   // Returns true iff the test name of test property matches on key_.
operator ()(const TestProperty & test_property) const762   bool operator()(const TestProperty& test_property) const {
763     return test_property.key() == key_;
764   }
765 
766  private:
767   std::string key_;
768 };
769 
770 // Class UnitTestOptions.
771 //
772 // This class contains functions for processing options the user
773 // specifies when running the tests.  It has only static members.
774 //
775 // In most cases, the user can specify an option using either an
776 // environment variable or a command line flag.  E.g. you can set the
777 // test filter using either GTEST_FILTER or --gtest_filter.  If both
778 // the variable and the flag are present, the latter overrides the
779 // former.
780 class GTEST_API_ UnitTestOptions {
781  public:
782   // Functions for processing the gtest_output flag.
783 
784   // Returns the output format, or "" for normal printed output.
785   static std::string GetOutputFormat();
786 
787   // Returns the absolute path of the requested output file, or the
788   // default (test_detail.xml in the original working directory) if
789   // none was explicitly specified.
790   static std::string GetAbsolutePathToOutputFile();
791 
792   // Functions for processing the gtest_filter flag.
793 
794   // Returns true iff the wildcard pattern matches the string.  The
795   // first ':' or '\0' character in pattern marks the end of it.
796   //
797   // This recursive algorithm isn't very efficient, but is clear and
798   // works well enough for matching test names, which are short.
799   static bool PatternMatchesString(const char *pattern, const char *str);
800 
801   // Returns true iff the user-specified filter matches the test case
802   // name and the test name.
803   static bool FilterMatchesTest(const std::string &test_case_name,
804                                 const std::string &test_name);
805 
806 #if GTEST_OS_WINDOWS
807   // Function for supporting the gtest_catch_exception flag.
808 
809   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
810   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
811   // This function is useful as an __except condition.
812   static int GTestShouldProcessSEH(DWORD exception_code);
813 #endif  // GTEST_OS_WINDOWS
814 
815   // Returns true if "name" matches the ':' separated list of glob-style
816   // filters in "filter".
817   static bool MatchesFilter(const std::string& name, const char* filter);
818 };
819 
820 // Returns the current application's name, removing directory path if that
821 // is present.  Used by UnitTestOptions::GetOutputFile.
822 GTEST_API_ FilePath GetCurrentExecutableName();
823 
824 // The role interface for getting the OS stack trace as a string.
825 class OsStackTraceGetterInterface {
826  public:
OsStackTraceGetterInterface()827   OsStackTraceGetterInterface() {}
~OsStackTraceGetterInterface()828   virtual ~OsStackTraceGetterInterface() {}
829 
830   // Returns the current OS stack trace as an std::string.  Parameters:
831   //
832   //   max_depth  - the maximum number of stack frames to be included
833   //                in the trace.
834   //   skip_count - the number of top frames to be skipped; doesn't count
835   //                against max_depth.
836   virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
837 
838   // UponLeavingGTest() should be called immediately before Google Test calls
839   // user code. It saves some information about the current stack that
840   // CurrentStackTrace() will use to find and hide Google Test stack frames.
841   virtual void UponLeavingGTest() = 0;
842 
843   // This string is inserted in place of stack frames that are part of
844   // Google Test's implementation.
845   static const char* const kElidedFramesMarker;
846 
847  private:
848   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
849 };
850 
851 // A working implementation of the OsStackTraceGetterInterface interface.
852 class OsStackTraceGetter : public OsStackTraceGetterInterface {
853  public:
OsStackTraceGetter()854   OsStackTraceGetter() {}
855 
856   virtual string CurrentStackTrace(int max_depth, int skip_count);
857   virtual void UponLeavingGTest();
858 
859  private:
860   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
861 };
862 
863 // Information about a Google Test trace point.
864 struct TraceInfo {
865   const char* file;
866   int line;
867   std::string message;
868 };
869 
870 // This is the default global test part result reporter used in UnitTestImpl.
871 // This class should only be used by UnitTestImpl.
872 class DefaultGlobalTestPartResultReporter
873   : public TestPartResultReporterInterface {
874  public:
875   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
876   // Implements the TestPartResultReporterInterface. Reports the test part
877   // result in the current test.
878   virtual void ReportTestPartResult(const TestPartResult& result);
879 
880  private:
881   UnitTestImpl* const unit_test_;
882 
883   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
884 };
885 
886 // This is the default per thread test part result reporter used in
887 // UnitTestImpl. This class should only be used by UnitTestImpl.
888 class DefaultPerThreadTestPartResultReporter
889     : public TestPartResultReporterInterface {
890  public:
891   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
892   // Implements the TestPartResultReporterInterface. The implementation just
893   // delegates to the current global test part result reporter of *unit_test_.
894   virtual void ReportTestPartResult(const TestPartResult& result);
895 
896  private:
897   UnitTestImpl* const unit_test_;
898 
899   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
900 };
901 
902 // The private implementation of the UnitTest class.  We don't protect
903 // the methods under a mutex, as this class is not accessible by a
904 // user and the UnitTest class that delegates work to this class does
905 // proper locking.
906 class GTEST_API_ UnitTestImpl {
907  public:
908   explicit UnitTestImpl(UnitTest* parent);
909   virtual ~UnitTestImpl();
910 
911   // There are two different ways to register your own TestPartResultReporter.
912   // You can register your own repoter to listen either only for test results
913   // from the current thread or for results from all threads.
914   // By default, each per-thread test result repoter just passes a new
915   // TestPartResult to the global test result reporter, which registers the
916   // test part result for the currently running test.
917 
918   // Returns the global test part result reporter.
919   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
920 
921   // Sets the global test part result reporter.
922   void SetGlobalTestPartResultReporter(
923       TestPartResultReporterInterface* reporter);
924 
925   // Returns the test part result reporter for the current thread.
926   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
927 
928   // Sets the test part result reporter for the current thread.
929   void SetTestPartResultReporterForCurrentThread(
930       TestPartResultReporterInterface* reporter);
931 
932   // Gets the number of successful test cases.
933   int successful_test_case_count() const;
934 
935   // Gets the number of failed test cases.
936   int failed_test_case_count() const;
937 
938   // Gets the number of all test cases.
939   int total_test_case_count() const;
940 
941   // Gets the number of all test cases that contain at least one test
942   // that should run.
943   int test_case_to_run_count() const;
944 
945   // Gets the number of successful tests.
946   int successful_test_count() const;
947 
948   // Gets the number of failed tests.
949   int failed_test_count() const;
950 
951   // Gets the number of disabled tests that will be reported in the XML report.
952   int reportable_disabled_test_count() const;
953 
954   // Gets the number of disabled tests.
955   int disabled_test_count() const;
956 
957   // Gets the number of tests to be printed in the XML report.
958   int reportable_test_count() const;
959 
960   // Gets the number of all tests.
961   int total_test_count() const;
962 
963   // Gets the number of tests that should run.
964   int test_to_run_count() const;
965 
966   // Gets the time of the test program start, in ms from the start of the
967   // UNIX epoch.
start_timestamp() const968   TimeInMillis start_timestamp() const { return start_timestamp_; }
969 
970   // Gets the elapsed time, in milliseconds.
elapsed_time() const971   TimeInMillis elapsed_time() const { return elapsed_time_; }
972 
973   // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const974   bool Passed() const { return !Failed(); }
975 
976   // Returns true iff the unit test failed (i.e. some test case failed
977   // or something outside of all tests failed).
Failed() const978   bool Failed() const {
979     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
980   }
981 
982   // Gets the i-th test case among all the test cases. i can range from 0 to
983   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const984   const TestCase* GetTestCase(int i) const {
985     const int index = GetElementOr(test_case_indices_, i, -1);
986     return index < 0 ? NULL : test_cases_[i];
987   }
988 
989   // Gets the i-th test case among all the test cases. i can range from 0 to
990   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)991   TestCase* GetMutableTestCase(int i) {
992     const int index = GetElementOr(test_case_indices_, i, -1);
993     return index < 0 ? NULL : test_cases_[index];
994   }
995 
996   // Provides access to the event listener list.
listeners()997   TestEventListeners* listeners() { return &listeners_; }
998 
999   // Returns the TestResult for the test that's currently running, or
1000   // the TestResult for the ad hoc test if no test is running.
1001   TestResult* current_test_result();
1002 
1003   // Returns the TestResult for the ad hoc test.
ad_hoc_test_result() const1004   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1005 
1006   // Sets the OS stack trace getter.
1007   //
1008   // Does nothing if the input and the current OS stack trace getter
1009   // are the same; otherwise, deletes the old getter and makes the
1010   // input the current getter.
1011   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1012 
1013   // Returns the current OS stack trace getter if it is not NULL;
1014   // otherwise, creates an OsStackTraceGetter, makes it the current
1015   // getter, and returns it.
1016   OsStackTraceGetterInterface* os_stack_trace_getter();
1017 
1018   // Returns the current OS stack trace as an std::string.
1019   //
1020   // The maximum number of stack frames to be included is specified by
1021   // the gtest_stack_trace_depth flag.  The skip_count parameter
1022   // specifies the number of top frames to be skipped, which doesn't
1023   // count against the number of frames to be included.
1024   //
1025   // For example, if Foo() calls Bar(), which in turn calls
1026   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1027   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1028   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1029 
1030   // Finds and returns a TestCase with the given name.  If one doesn't
1031   // exist, creates one and returns it.
1032   //
1033   // Arguments:
1034   //
1035   //   test_case_name: name of the test case
1036   //   type_param:     the name of the test's type parameter, or NULL if
1037   //                   this is not a typed or a type-parameterized test.
1038   //   set_up_tc:      pointer to the function that sets up the test case
1039   //   tear_down_tc:   pointer to the function that tears down the test case
1040   TestCase* GetTestCase(const char* test_case_name,
1041                         const char* type_param,
1042                         Test::SetUpTestCaseFunc set_up_tc,
1043                         Test::TearDownTestCaseFunc tear_down_tc);
1044 
1045   // Adds a TestInfo to the unit test.
1046   //
1047   // Arguments:
1048   //
1049   //   set_up_tc:    pointer to the function that sets up the test case
1050   //   tear_down_tc: pointer to the function that tears down the test case
1051   //   test_info:    the TestInfo object
AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc,TestInfo * test_info)1052   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1053                    Test::TearDownTestCaseFunc tear_down_tc,
1054                    TestInfo* test_info) {
1055     // In order to support thread-safe death tests, we need to
1056     // remember the original working directory when the test program
1057     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
1058     // the user may have changed the current directory before calling
1059     // RUN_ALL_TESTS().  Therefore we capture the current directory in
1060     // AddTestInfo(), which is called to register a TEST or TEST_F
1061     // before main() is reached.
1062     if (original_working_dir_.IsEmpty()) {
1063       original_working_dir_.Set(FilePath::GetCurrentDir());
1064       GTEST_CHECK_(!original_working_dir_.IsEmpty())
1065           << "Failed to get the current working directory.";
1066     }
1067 
1068     GetTestCase(test_info->test_case_name(),
1069                 test_info->type_param(),
1070                 set_up_tc,
1071                 tear_down_tc)->AddTestInfo(test_info);
1072   }
1073 
1074 #if GTEST_HAS_PARAM_TEST
1075   // Returns ParameterizedTestCaseRegistry object used to keep track of
1076   // value-parameterized tests and instantiate and register them.
parameterized_test_registry()1077   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1078     return parameterized_test_registry_;
1079   }
1080 #endif  // GTEST_HAS_PARAM_TEST
1081 
1082   // Sets the TestCase object for the test that's currently running.
set_current_test_case(TestCase * a_current_test_case)1083   void set_current_test_case(TestCase* a_current_test_case) {
1084     current_test_case_ = a_current_test_case;
1085   }
1086 
1087   // Sets the TestInfo object for the test that's currently running.  If
1088   // current_test_info is NULL, the assertion results will be stored in
1089   // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)1090   void set_current_test_info(TestInfo* a_current_test_info) {
1091     current_test_info_ = a_current_test_info;
1092   }
1093 
1094   // Registers all parameterized tests defined using TEST_P and
1095   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1096   // combination. This method can be called more then once; it has guards
1097   // protecting from registering the tests more then once.  If
1098   // value-parameterized tests are disabled, RegisterParameterizedTests is
1099   // present but does nothing.
1100   void RegisterParameterizedTests();
1101 
1102   // Runs all tests in this UnitTest object, prints the result, and
1103   // returns true if all tests are successful.  If any exception is
1104   // thrown during a test, this test is considered to be failed, but
1105   // the rest of the tests will still be run.
1106   bool RunAllTests();
1107 
1108   // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()1109   void ClearNonAdHocTestResult() {
1110     ForEach(test_cases_, TestCase::ClearTestCaseResult);
1111   }
1112 
1113   // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()1114   void ClearAdHocTestResult() {
1115     ad_hoc_test_result_.Clear();
1116   }
1117 
1118   // Adds a TestProperty to the current TestResult object when invoked in a
1119   // context of a test or a test case, or to the global property set. If the
1120   // result already contains a property with the same key, the value will be
1121   // updated.
1122   void RecordProperty(const TestProperty& test_property);
1123 
1124   enum ReactionToSharding {
1125     HONOR_SHARDING_PROTOCOL,
1126     IGNORE_SHARDING_PROTOCOL
1127   };
1128 
1129   // Matches the full name of each test against the user-specified
1130   // filter to decide whether the test should run, then records the
1131   // result in each TestCase and TestInfo object.
1132   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1133   // based on sharding variables in the environment.
1134   // Returns the number of tests that should run.
1135   int FilterTests(ReactionToSharding shard_tests);
1136 
1137   // Prints the names of the tests matching the user-specified filter flag.
1138   void ListTestsMatchingFilter();
1139 
current_test_case() const1140   const TestCase* current_test_case() const { return current_test_case_; }
current_test_info()1141   TestInfo* current_test_info() { return current_test_info_; }
current_test_info() const1142   const TestInfo* current_test_info() const { return current_test_info_; }
1143 
1144   // Returns the vector of environments that need to be set-up/torn-down
1145   // before/after the tests are run.
environments()1146   std::vector<Environment*>& environments() { return environments_; }
1147 
1148   // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()1149   std::vector<TraceInfo>& gtest_trace_stack() {
1150     return *(gtest_trace_stack_.pointer());
1151   }
gtest_trace_stack() const1152   const std::vector<TraceInfo>& gtest_trace_stack() const {
1153     return gtest_trace_stack_.get();
1154   }
1155 
1156 #if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()1157   void InitDeathTestSubprocessControlInfo() {
1158     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1159   }
1160   // Returns a pointer to the parsed --gtest_internal_run_death_test
1161   // flag, or NULL if that flag was not specified.
1162   // This information is useful only in a death test child process.
1163   // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag() const1164   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1165     return internal_run_death_test_flag_.get();
1166   }
1167 
1168   // Returns a pointer to the current death test factory.
death_test_factory()1169   internal::DeathTestFactory* death_test_factory() {
1170     return death_test_factory_.get();
1171   }
1172 
1173   void SuppressTestEventsIfInSubprocess();
1174 
1175   friend class ReplaceDeathTestFactory;
1176 #endif  // GTEST_HAS_DEATH_TEST
1177 
1178   // Initializes the event listener performing XML output as specified by
1179   // UnitTestOptions. Must not be called before InitGoogleTest.
1180   void ConfigureXmlOutput();
1181 
1182 #if GTEST_CAN_STREAM_RESULTS_
1183   // Initializes the event listener for streaming test results to a socket.
1184   // Must not be called before InitGoogleTest.
1185   void ConfigureStreamingOutput();
1186 #endif
1187 
1188   // Performs initialization dependent upon flag values obtained in
1189   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
1190   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
1191   // this function is also called from RunAllTests.  Since this function can be
1192   // called more than once, it has to be idempotent.
1193   void PostFlagParsingInit();
1194 
1195   // Gets the random seed used at the start of the current test iteration.
random_seed() const1196   int random_seed() const { return random_seed_; }
1197 
1198   // Gets the random number generator.
random()1199   internal::Random* random() { return &random_; }
1200 
1201   // Shuffles all test cases, and the tests within each test case,
1202   // making sure that death tests are still run first.
1203   void ShuffleTests();
1204 
1205   // Restores the test cases and tests to their order before the first shuffle.
1206   void UnshuffleTests();
1207 
1208   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1209   // UnitTest::Run() starts.
catch_exceptions() const1210   bool catch_exceptions() const { return catch_exceptions_; }
1211 
1212  private:
1213   friend class ::testing::UnitTest;
1214 
1215   // Used by UnitTest::Run() to capture the state of
1216   // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)1217   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1218 
1219   // The UnitTest object that owns this implementation object.
1220   UnitTest* const parent_;
1221 
1222   // The working directory when the first TEST() or TEST_F() was
1223   // executed.
1224   internal::FilePath original_working_dir_;
1225 
1226   // The default test part result reporters.
1227   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1228   DefaultPerThreadTestPartResultReporter
1229       default_per_thread_test_part_result_reporter_;
1230 
1231   // Points to (but doesn't own) the global test part result reporter.
1232   TestPartResultReporterInterface* global_test_part_result_repoter_;
1233 
1234   // Protects read and write access to global_test_part_result_reporter_.
1235   internal::Mutex global_test_part_result_reporter_mutex_;
1236 
1237   // Points to (but doesn't own) the per-thread test part result reporter.
1238   internal::ThreadLocal<TestPartResultReporterInterface*>
1239       per_thread_test_part_result_reporter_;
1240 
1241   // The vector of environments that need to be set-up/torn-down
1242   // before/after the tests are run.
1243   std::vector<Environment*> environments_;
1244 
1245   // The vector of TestCases in their original order.  It owns the
1246   // elements in the vector.
1247   std::vector<TestCase*> test_cases_;
1248 
1249   // Provides a level of indirection for the test case list to allow
1250   // easy shuffling and restoring the test case order.  The i-th
1251   // element of this vector is the index of the i-th test case in the
1252   // shuffled order.
1253   std::vector<int> test_case_indices_;
1254 
1255 #if GTEST_HAS_PARAM_TEST
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 #endif  // GTEST_HAS_PARAM_TEST
1263 
1264   // Index of the last death test case registered.  Initially -1.
1265   int last_death_test_case_;
1266 
1267   // This points to the TestCase for the currently running test.  It
1268   // changes as Google Test goes through one test case after another.
1269   // When no test is running, this is set to NULL and Google Test
1270   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
1271   TestCase* current_test_case_;
1272 
1273   // This points to the TestInfo for the currently running test.  It
1274   // changes as Google Test goes through one test after another.  When
1275   // no test is running, this is set to NULL and Google Test stores
1276   // assertion results in ad_hoc_test_result_.  Initially NULL.
1277   TestInfo* current_test_info_;
1278 
1279   // Normally, a user only writes assertions inside a TEST or TEST_F,
1280   // or inside a function called by a TEST or TEST_F.  Since Google
1281   // Test keeps track of which test is current running, it can
1282   // associate such an assertion with the test it belongs to.
1283   //
1284   // If an assertion is encountered when no TEST or TEST_F is running,
1285   // Google Test attributes the assertion result to an imaginary "ad hoc"
1286   // test, and records the result in ad_hoc_test_result_.
1287   TestResult ad_hoc_test_result_;
1288 
1289   // The list of event listeners that can be used to track events inside
1290   // Google Test.
1291   TestEventListeners listeners_;
1292 
1293   // The OS stack trace getter.  Will be deleted when the UnitTest
1294   // object is destructed.  By default, an OsStackTraceGetter is used,
1295   // but the user can set this field to use a custom getter if that is
1296   // desired.
1297   OsStackTraceGetterInterface* os_stack_trace_getter_;
1298 
1299   // True iff PostFlagParsingInit() has been called.
1300   bool post_flag_parse_init_performed_;
1301 
1302   // The random number seed used at the beginning of the test run.
1303   int random_seed_;
1304 
1305   // Our random number generator.
1306   internal::Random random_;
1307 
1308   // The time of the test program start, in ms from the start of the
1309   // UNIX epoch.
1310   TimeInMillis start_timestamp_;
1311 
1312   // How long the test took to run, in milliseconds.
1313   TimeInMillis elapsed_time_;
1314 
1315 #if GTEST_HAS_DEATH_TEST
1316   // The decomposed components of the gtest_internal_run_death_test flag,
1317   // parsed when RUN_ALL_TESTS is called.
1318   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1319   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1320 #endif  // GTEST_HAS_DEATH_TEST
1321 
1322   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1323   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1324 
1325   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1326   // starts.
1327   bool catch_exceptions_;
1328 
1329   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1330 };  // class UnitTestImpl
1331 
1332 // Convenience function for accessing the global UnitTest
1333 // implementation object.
GetUnitTestImpl()1334 inline UnitTestImpl* GetUnitTestImpl() {
1335   return UnitTest::GetInstance()->impl();
1336 }
1337 
1338 #if GTEST_USES_SIMPLE_RE
1339 
1340 // Internal helper functions for implementing the simple regular
1341 // expression matcher.
1342 GTEST_API_ bool IsInSet(char ch, const char* str);
1343 GTEST_API_ bool IsAsciiDigit(char ch);
1344 GTEST_API_ bool IsAsciiPunct(char ch);
1345 GTEST_API_ bool IsRepeat(char ch);
1346 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1347 GTEST_API_ bool IsAsciiWordChar(char ch);
1348 GTEST_API_ bool IsValidEscape(char ch);
1349 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1350 GTEST_API_ bool ValidateRegex(const char* regex);
1351 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1352 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1353     bool escaped, char ch, char repeat, const char* regex, const char* str);
1354 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1355 
1356 #endif  // GTEST_USES_SIMPLE_RE
1357 
1358 // Parses the command line for Google Test flags, without initializing
1359 // other parts of Google Test.
1360 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1361 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1362 
1363 #if GTEST_HAS_DEATH_TEST
1364 
1365 // Returns the message describing the last system error, regardless of the
1366 // platform.
1367 GTEST_API_ std::string GetLastErrnoDescription();
1368 
1369 // Attempts to parse a string into a positive integer pointed to by the
1370 // number parameter.  Returns true if that is possible.
1371 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1372 // it here.
1373 template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)1374 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1375   // Fail fast if the given string does not begin with a digit;
1376   // this bypasses strtoXXX's "optional leading whitespace and plus
1377   // or minus sign" semantics, which are undesirable here.
1378   if (str.empty() || !IsDigit(str[0])) {
1379     return false;
1380   }
1381   errno = 0;
1382 
1383   char* end;
1384   // BiggestConvertible is the largest integer type that system-provided
1385   // string-to-number conversion routines can return.
1386 
1387 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1388 
1389   // MSVC and C++ Builder define __int64 instead of the standard long long.
1390   typedef unsigned __int64 BiggestConvertible;
1391   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1392 
1393 # else
1394 
1395   typedef unsigned long long BiggestConvertible;  // NOLINT
1396   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1397 
1398 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
1399 
1400   const bool parse_success = *end == '\0' && errno == 0;
1401 
1402   // TODO(vladl@google.com): Convert this to compile time assertion when it is
1403   // available.
1404   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1405 
1406   const Integer result = static_cast<Integer>(parsed);
1407   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1408     *number = result;
1409     return true;
1410   }
1411   return false;
1412 }
1413 #endif  // GTEST_HAS_DEATH_TEST
1414 
1415 // TestResult contains some private methods that should be hidden from
1416 // Google Test user but are required for testing. This class allow our tests
1417 // to access them.
1418 //
1419 // This class is supplied only for the purpose of testing Google Test's own
1420 // constructs. Do not use it in user tests, either directly or indirectly.
1421 class TestResultAccessor {
1422  public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1423   static void RecordProperty(TestResult* test_result,
1424                              const std::string& xml_element,
1425                              const TestProperty& property) {
1426     test_result->RecordProperty(xml_element, property);
1427   }
1428 
ClearTestPartResults(TestResult * test_result)1429   static void ClearTestPartResults(TestResult* test_result) {
1430     test_result->ClearTestPartResults();
1431   }
1432 
test_part_results(const TestResult & test_result)1433   static const std::vector<testing::TestPartResult>& test_part_results(
1434       const TestResult& test_result) {
1435     return test_result.test_part_results();
1436   }
1437 };
1438 
1439 #if GTEST_CAN_STREAM_RESULTS_
1440 
1441 // Streams test results to the given port on the given host machine.
1442 class GTEST_API_ StreamingListener : public EmptyTestEventListener {
1443  public:
1444   // Abstract base class for writing strings to a socket.
1445   class AbstractSocketWriter {
1446    public:
~AbstractSocketWriter()1447     virtual ~AbstractSocketWriter() {}
1448 
1449     // Sends a string to the socket.
1450     virtual void Send(const string& message) = 0;
1451 
1452     // Closes the socket.
CloseConnection()1453     virtual void CloseConnection() {}
1454 
1455     // Sends a string and a newline to the socket.
SendLn(const string & message)1456     void SendLn(const string& message) {
1457       Send(message + "\n");
1458     }
1459   };
1460 
1461   // Concrete class for actually writing strings to a socket.
1462   class SocketWriter : public AbstractSocketWriter {
1463    public:
SocketWriter(const string & host,const string & port)1464     SocketWriter(const string& host, const string& port)
1465         : sockfd_(-1), host_name_(host), port_num_(port) {
1466       MakeConnection();
1467     }
1468 
~SocketWriter()1469     virtual ~SocketWriter() {
1470       if (sockfd_ != -1)
1471         CloseConnection();
1472     }
1473 
1474     // Sends a string to the socket.
Send(const string & message)1475     virtual void Send(const string& message) {
1476       GTEST_CHECK_(sockfd_ != -1)
1477           << "Send() can be called only when there is a connection.";
1478 
1479       const int len = static_cast<int>(message.length());
1480       if (write(sockfd_, message.c_str(), len) != len) {
1481         GTEST_LOG_(WARNING)
1482             << "stream_result_to: failed to stream to "
1483             << host_name_ << ":" << port_num_;
1484       }
1485     }
1486 
1487    private:
1488     // Creates a client socket and connects to the server.
1489     void MakeConnection();
1490 
1491     // Closes the socket.
CloseConnection()1492     void CloseConnection() {
1493       GTEST_CHECK_(sockfd_ != -1)
1494           << "CloseConnection() can be called only when there is a connection.";
1495 
1496       close(sockfd_);
1497       sockfd_ = -1;
1498     }
1499 
1500     int sockfd_;  // socket file descriptor
1501     const string host_name_;
1502     const string port_num_;
1503 
1504     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1505   };  // class SocketWriter
1506 
1507   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1508   static string UrlEncode(const char* str);
1509 
StreamingListener(const string & host,const string & port)1510   StreamingListener(const string& host, const string& port)
1511       : socket_writer_(new SocketWriter(host, port)) { Start(); }
1512 
StreamingListener(AbstractSocketWriter * socket_writer)1513   explicit StreamingListener(AbstractSocketWriter* socket_writer)
1514       : socket_writer_(socket_writer) { Start(); }
1515 
OnTestProgramStart(const UnitTest &)1516   void OnTestProgramStart(const UnitTest& /* unit_test */) {
1517     SendLn("event=TestProgramStart");
1518   }
1519 
OnTestProgramEnd(const UnitTest & unit_test)1520   void OnTestProgramEnd(const UnitTest& unit_test) {
1521     // Note that Google Test current only report elapsed time for each
1522     // test iteration, not for the entire test program.
1523     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1524 
1525     // Notify the streaming server to stop.
1526     socket_writer_->CloseConnection();
1527   }
1528 
OnTestIterationStart(const UnitTest &,int iteration)1529   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1530     SendLn("event=TestIterationStart&iteration=" +
1531            StreamableToString(iteration));
1532   }
1533 
OnTestIterationEnd(const UnitTest & unit_test,int)1534   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1535     SendLn("event=TestIterationEnd&passed=" +
1536            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1537            StreamableToString(unit_test.elapsed_time()) + "ms");
1538   }
1539 
OnTestCaseStart(const TestCase & test_case)1540   void OnTestCaseStart(const TestCase& test_case) {
1541     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1542   }
1543 
OnTestCaseEnd(const TestCase & test_case)1544   void OnTestCaseEnd(const TestCase& test_case) {
1545     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1546            + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1547            + "ms");
1548   }
1549 
OnTestStart(const TestInfo & test_info)1550   void OnTestStart(const TestInfo& test_info) {
1551     SendLn(std::string("event=TestStart&name=") + test_info.name());
1552   }
1553 
OnTestEnd(const TestInfo & test_info)1554   void OnTestEnd(const TestInfo& test_info) {
1555     SendLn("event=TestEnd&passed=" +
1556            FormatBool((test_info.result())->Passed()) +
1557            "&elapsed_time=" +
1558            StreamableToString((test_info.result())->elapsed_time()) + "ms");
1559   }
1560 
OnTestPartResult(const TestPartResult & test_part_result)1561   void OnTestPartResult(const TestPartResult& test_part_result) {
1562     const char* file_name = test_part_result.file_name();
1563     if (file_name == NULL)
1564       file_name = "";
1565     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1566            "&line=" + StreamableToString(test_part_result.line_number()) +
1567            "&message=" + UrlEncode(test_part_result.message()));
1568   }
1569 
1570  private:
1571   // Sends the given message and a newline to the socket.
SendLn(const string & message)1572   void SendLn(const string& message) { socket_writer_->SendLn(message); }
1573 
1574   // Called at the start of streaming to notify the receiver what
1575   // protocol we are using.
Start()1576   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1577 
FormatBool(bool value)1578   string FormatBool(bool value) { return value ? "1" : "0"; }
1579 
1580   const scoped_ptr<AbstractSocketWriter> socket_writer_;
1581 
1582   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1583 };  // class StreamingListener
1584 
1585 #endif  // GTEST_CAN_STREAM_RESULTS_
1586 
1587 }  // namespace internal
1588 }  // namespace testing
1589 
1590 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
1591 #undef GTEST_IMPLEMENTATION_
1592 
1593 #if GTEST_OS_WINDOWS
1594 # define vsnprintf _vsnprintf
1595 #endif  // GTEST_OS_WINDOWS
1596 
1597 namespace testing {
1598 
1599 using internal::CountIf;
1600 using internal::ForEach;
1601 using internal::GetElementOr;
1602 using internal::Shuffle;
1603 
1604 // Constants.
1605 
1606 // A test whose test case name or test name matches this filter is
1607 // disabled and not run.
1608 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1609 
1610 // A test case whose name matches this filter is considered a death
1611 // test case and will be run before test cases whose name doesn't
1612 // match this filter.
1613 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1614 
1615 // A test filter that matches everything.
1616 static const char kUniversalFilter[] = "*";
1617 
1618 // The default output file for XML output.
1619 static const char kDefaultOutputFile[] = "test_detail.xml";
1620 
1621 // The environment variable name for the test shard index.
1622 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1623 // The environment variable name for the total number of test shards.
1624 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1625 // The environment variable name for the test shard status file.
1626 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1627 
1628 namespace internal {
1629 
1630 // The text used in failure messages to indicate the start of the
1631 // stack trace.
1632 const char kStackTraceMarker[] = "\nStack trace:\n";
1633 
1634 // g_help_flag is true iff the --help flag or an equivalent form is
1635 // specified on the command line.
1636 bool g_help_flag = false;
1637 
1638 }  // namespace internal
1639 
GetDefaultFilter()1640 static const char* GetDefaultFilter() {
1641 #ifdef GTEST_TEST_FILTER_ENV_VAR_
1642   const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);
1643   if (testbridge_test_only != NULL) {
1644     return testbridge_test_only;
1645   }
1646 #endif  // GTEST_TEST_FILTER_ENV_VAR_
1647   return kUniversalFilter;
1648 }
1649 
1650 GTEST_DEFINE_bool_(
1651     also_run_disabled_tests,
1652     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1653     "Run disabled tests too, in addition to the tests normally being run.");
1654 
1655 GTEST_DEFINE_bool_(
1656     break_on_failure,
1657     internal::BoolFromGTestEnv("break_on_failure", false),
1658     "True iff a failed assertion should be a debugger break-point.");
1659 
1660 GTEST_DEFINE_bool_(
1661     catch_exceptions,
1662     internal::BoolFromGTestEnv("catch_exceptions", true),
1663     "True iff " GTEST_NAME_
1664     " should catch exceptions and treat them as test failures.");
1665 
1666 GTEST_DEFINE_string_(
1667     color,
1668     internal::StringFromGTestEnv("color", "auto"),
1669     "Whether to use colors in the output.  Valid values: yes, no, "
1670     "and auto.  'auto' means to use colors if the output is "
1671     "being sent to a terminal and the TERM environment variable "
1672     "is set to a terminal type that supports colors.");
1673 
1674 GTEST_DEFINE_string_(
1675     filter,
1676     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1677     "A colon-separated list of glob (not regex) patterns "
1678     "for filtering the tests to run, optionally followed by a "
1679     "'-' and a : separated list of negative patterns (tests to "
1680     "exclude).  A test is run if it matches one of the positive "
1681     "patterns and does not match any of the negative patterns.");
1682 
1683 GTEST_DEFINE_bool_(list_tests, false,
1684                    "List all tests without running them.");
1685 
1686 GTEST_DEFINE_string_(
1687     output,
1688     internal::StringFromGTestEnv("output", ""),
1689     "A format (currently must be \"xml\"), optionally followed "
1690     "by a colon and an output file name or directory. A directory "
1691     "is indicated by a trailing pathname separator. "
1692     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1693     "If a directory is specified, output files will be created "
1694     "within that directory, with file-names based on the test "
1695     "executable's name and, if necessary, made unique by adding "
1696     "digits.");
1697 
1698 GTEST_DEFINE_bool_(
1699     print_time,
1700     internal::BoolFromGTestEnv("print_time", true),
1701     "True iff " GTEST_NAME_
1702     " should display elapsed time in text output.");
1703 
1704 GTEST_DEFINE_int32_(
1705     random_seed,
1706     internal::Int32FromGTestEnv("random_seed", 0),
1707     "Random number seed to use when shuffling test orders.  Must be in range "
1708     "[1, 99999], or 0 to use a seed based on the current time.");
1709 
1710 GTEST_DEFINE_int32_(
1711     repeat,
1712     internal::Int32FromGTestEnv("repeat", 1),
1713     "How many times to repeat each test.  Specify a negative number "
1714     "for repeating forever.  Useful for shaking out flaky tests.");
1715 
1716 GTEST_DEFINE_bool_(
1717     show_internal_stack_frames, false,
1718     "True iff " GTEST_NAME_ " should include internal stack frames when "
1719     "printing test failure stack traces.");
1720 
1721 GTEST_DEFINE_bool_(
1722     shuffle,
1723     internal::BoolFromGTestEnv("shuffle", false),
1724     "True iff " GTEST_NAME_
1725     " should randomize tests' order on every run.");
1726 
1727 GTEST_DEFINE_int32_(
1728     stack_trace_depth,
1729     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1730     "The maximum number of stack frames to print when an "
1731     "assertion fails.  The valid range is 0 through 100, inclusive.");
1732 
1733 GTEST_DEFINE_string_(
1734     stream_result_to,
1735     internal::StringFromGTestEnv("stream_result_to", ""),
1736     "This flag specifies the host name and the port number on which to stream "
1737     "test results. Example: \"localhost:555\". The flag is effective only on "
1738     "Linux.");
1739 
1740 GTEST_DEFINE_bool_(
1741     throw_on_failure,
1742     internal::BoolFromGTestEnv("throw_on_failure", false),
1743     "When this flag is specified, a failed assertion will throw an exception "
1744     "if exceptions are enabled or exit the program with a non-zero code "
1745     "otherwise.");
1746 
1747 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1748 GTEST_DEFINE_string_(
1749     flagfile,
1750     internal::StringFromGTestEnv("flagfile", ""),
1751     "This flag specifies the flagfile to read command-line flags from.");
1752 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
1753 
1754 namespace internal {
1755 
1756 // Generates a random number from [0, range), using a Linear
1757 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
1758 // than kMaxRange.
Generate(UInt32 range)1759 UInt32 Random::Generate(UInt32 range) {
1760   // These constants are the same as are used in glibc's rand(3).
1761   state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1762 
1763   GTEST_CHECK_(range > 0)
1764       << "Cannot generate a number in the range [0, 0).";
1765   GTEST_CHECK_(range <= kMaxRange)
1766       << "Generation of a number in [0, " << range << ") was requested, "
1767       << "but this can only generate numbers in [0, " << kMaxRange << ").";
1768 
1769   // Converting via modulus introduces a bit of downward bias, but
1770   // it's simple, and a linear congruential generator isn't too good
1771   // to begin with.
1772   return state_ % range;
1773 }
1774 
1775 // GTestIsInitialized() returns true iff the user has initialized
1776 // Google Test.  Useful for catching the user mistake of not initializing
1777 // Google Test before calling RUN_ALL_TESTS().
GTestIsInitialized()1778 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1779 
1780 // Iterates over a vector of TestCases, keeping a running sum of the
1781 // results of calling a given int-returning method on each.
1782 // Returns the sum.
SumOverTestCaseList(const std::vector<TestCase * > & case_list,int (TestCase::* method)()const)1783 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1784                                int (TestCase::*method)() const) {
1785   int sum = 0;
1786   for (size_t i = 0; i < case_list.size(); i++) {
1787     sum += (case_list[i]->*method)();
1788   }
1789   return sum;
1790 }
1791 
1792 // Returns true iff the test case passed.
TestCasePassed(const TestCase * test_case)1793 static bool TestCasePassed(const TestCase* test_case) {
1794   return test_case->should_run() && test_case->Passed();
1795 }
1796 
1797 // Returns true iff the test case failed.
TestCaseFailed(const TestCase * test_case)1798 static bool TestCaseFailed(const TestCase* test_case) {
1799   return test_case->should_run() && test_case->Failed();
1800 }
1801 
1802 // Returns true iff test_case contains at least one test that should
1803 // run.
ShouldRunTestCase(const TestCase * test_case)1804 static bool ShouldRunTestCase(const TestCase* test_case) {
1805   return test_case->should_run();
1806 }
1807 
1808 // AssertHelper constructor.
AssertHelper(TestPartResult::Type type,const char * file,int line,const char * message)1809 AssertHelper::AssertHelper(TestPartResult::Type type,
1810                            const char* file,
1811                            int line,
1812                            const char* message)
1813     : data_(new AssertHelperData(type, file, line, message)) {
1814 }
1815 
~AssertHelper()1816 AssertHelper::~AssertHelper() {
1817   delete data_;
1818 }
1819 
1820 // Message assignment, for assertion streaming support.
operator =(const Message & message) const1821 void AssertHelper::operator=(const Message& message) const {
1822   UnitTest::GetInstance()->
1823     AddTestPartResult(data_->type, data_->file, data_->line,
1824                       AppendUserMessage(data_->message, message),
1825                       UnitTest::GetInstance()->impl()
1826                       ->CurrentOsStackTraceExceptTop(1)
1827                       // Skips the stack frame for this function itself.
1828                       );  // NOLINT
1829 }
1830 
1831 // Mutex for linked pointers.
1832 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1833 
1834 // A copy of all command line arguments.  Set by InitGoogleTest().
1835 ::std::vector<testing::internal::string> g_argvs;
1836 
GetArgvs()1837 const ::std::vector<testing::internal::string>& GetArgvs() {
1838 #if defined(GTEST_CUSTOM_GET_ARGVS_)
1839   return GTEST_CUSTOM_GET_ARGVS_();
1840 #else  // defined(GTEST_CUSTOM_GET_ARGVS_)
1841   return g_argvs;
1842 #endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
1843 }
1844 
1845 // Returns the current application's name, removing directory path if that
1846 // is present.
GetCurrentExecutableName()1847 FilePath GetCurrentExecutableName() {
1848   FilePath result;
1849 
1850 #if GTEST_OS_WINDOWS
1851   result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
1852 #else
1853   result.Set(FilePath(GetArgvs()[0]));
1854 #endif  // GTEST_OS_WINDOWS
1855 
1856   return result.RemoveDirectoryName();
1857 }
1858 
1859 // Functions for processing the gtest_output flag.
1860 
1861 // Returns the output format, or "" for normal printed output.
GetOutputFormat()1862 std::string UnitTestOptions::GetOutputFormat() {
1863   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1864   if (gtest_output_flag == NULL) return std::string("");
1865 
1866   const char* const colon = strchr(gtest_output_flag, ':');
1867   return (colon == NULL) ?
1868       std::string(gtest_output_flag) :
1869       std::string(gtest_output_flag, colon - gtest_output_flag);
1870 }
1871 
1872 // Returns the name of the requested output file, or the default if none
1873 // was explicitly specified.
GetAbsolutePathToOutputFile()1874 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1875   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1876   if (gtest_output_flag == NULL)
1877     return "";
1878 
1879   const char* const colon = strchr(gtest_output_flag, ':');
1880   if (colon == NULL)
1881     return internal::FilePath::ConcatPaths(
1882         internal::FilePath(
1883             UnitTest::GetInstance()->original_working_dir()),
1884         internal::FilePath(kDefaultOutputFile)).string();
1885 
1886   internal::FilePath output_name(colon + 1);
1887   if (!output_name.IsAbsolutePath())
1888     // TODO(wan@google.com): on Windows \some\path is not an absolute
1889     // path (as its meaning depends on the current drive), yet the
1890     // following logic for turning it into an absolute path is wrong.
1891     // Fix it.
1892     output_name = internal::FilePath::ConcatPaths(
1893         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1894         internal::FilePath(colon + 1));
1895 
1896   if (!output_name.IsDirectory())
1897     return output_name.string();
1898 
1899   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1900       output_name, internal::GetCurrentExecutableName(),
1901       GetOutputFormat().c_str()));
1902   return result.string();
1903 }
1904 
1905 // Returns true iff the wildcard pattern matches the string.  The
1906 // first ':' or '\0' character in pattern marks the end of it.
1907 //
1908 // This recursive algorithm isn't very efficient, but is clear and
1909 // works well enough for matching test names, which are short.
PatternMatchesString(const char * pattern,const char * str)1910 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1911                                            const char *str) {
1912   switch (*pattern) {
1913     case '\0':
1914     case ':':  // Either ':' or '\0' marks the end of the pattern.
1915       return *str == '\0';
1916     case '?':  // Matches any single character.
1917       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1918     case '*':  // Matches any string (possibly empty) of characters.
1919       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1920           PatternMatchesString(pattern + 1, str);
1921     default:  // Non-special character.  Matches itself.
1922       return *pattern == *str &&
1923           PatternMatchesString(pattern + 1, str + 1);
1924   }
1925 }
1926 
MatchesFilter(const std::string & name,const char * filter)1927 bool UnitTestOptions::MatchesFilter(
1928     const std::string& name, const char* filter) {
1929   const char *cur_pattern = filter;
1930   for (;;) {
1931     if (PatternMatchesString(cur_pattern, name.c_str())) {
1932       return true;
1933     }
1934 
1935     // Finds the next pattern in the filter.
1936     cur_pattern = strchr(cur_pattern, ':');
1937 
1938     // Returns if no more pattern can be found.
1939     if (cur_pattern == NULL) {
1940       return false;
1941     }
1942 
1943     // Skips the pattern separater (the ':' character).
1944     cur_pattern++;
1945   }
1946 }
1947 
1948 // Returns true iff the user-specified filter matches the test case
1949 // name and the test name.
FilterMatchesTest(const std::string & test_case_name,const std::string & test_name)1950 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
1951                                         const std::string &test_name) {
1952   const std::string& full_name = test_case_name + "." + test_name.c_str();
1953 
1954   // Split --gtest_filter at '-', if there is one, to separate into
1955   // positive filter and negative filter portions
1956   const char* const p = GTEST_FLAG(filter).c_str();
1957   const char* const dash = strchr(p, '-');
1958   std::string positive;
1959   std::string negative;
1960   if (dash == NULL) {
1961     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
1962     negative = "";
1963   } else {
1964     positive = std::string(p, dash);   // Everything up to the dash
1965     negative = std::string(dash + 1);  // Everything after the dash
1966     if (positive.empty()) {
1967       // Treat '-test1' as the same as '*-test1'
1968       positive = kUniversalFilter;
1969     }
1970   }
1971 
1972   // A filter is a colon-separated list of patterns.  It matches a
1973   // test if any pattern in it matches the test.
1974   return (MatchesFilter(full_name, positive.c_str()) &&
1975           !MatchesFilter(full_name, negative.c_str()));
1976 }
1977 
1978 #if GTEST_HAS_SEH
1979 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1980 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1981 // This function is useful as an __except condition.
GTestShouldProcessSEH(DWORD exception_code)1982 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1983   // Google Test should handle a SEH exception if:
1984   //   1. the user wants it to, AND
1985   //   2. this is not a breakpoint exception, AND
1986   //   3. this is not a C++ exception (VC++ implements them via SEH,
1987   //      apparently).
1988   //
1989   // SEH exception code for C++ exceptions.
1990   // (see http://support.microsoft.com/kb/185294 for more information).
1991   const DWORD kCxxExceptionCode = 0xe06d7363;
1992 
1993   bool should_handle = true;
1994 
1995   if (!GTEST_FLAG(catch_exceptions))
1996     should_handle = false;
1997   else if (exception_code == EXCEPTION_BREAKPOINT)
1998     should_handle = false;
1999   else if (exception_code == kCxxExceptionCode)
2000     should_handle = false;
2001 
2002   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2003 }
2004 #endif  // GTEST_HAS_SEH
2005 
2006 }  // namespace internal
2007 
2008 // The c'tor sets this object as the test part result reporter used by
2009 // Google Test.  The 'result' parameter specifies where to report the
2010 // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter(TestPartResultArray * result)2011 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2012     TestPartResultArray* result)
2013     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2014       result_(result) {
2015   Init();
2016 }
2017 
2018 // The c'tor sets this object as the test part result reporter used by
2019 // Google Test.  The 'result' parameter specifies where to report the
2020 // results.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,TestPartResultArray * result)2021 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2022     InterceptMode intercept_mode, TestPartResultArray* result)
2023     : intercept_mode_(intercept_mode),
2024       result_(result) {
2025   Init();
2026 }
2027 
Init()2028 void ScopedFakeTestPartResultReporter::Init() {
2029   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2030   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2031     old_reporter_ = impl->GetGlobalTestPartResultReporter();
2032     impl->SetGlobalTestPartResultReporter(this);
2033   } else {
2034     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2035     impl->SetTestPartResultReporterForCurrentThread(this);
2036   }
2037 }
2038 
2039 // The d'tor restores the test part result reporter used by Google Test
2040 // before.
~ScopedFakeTestPartResultReporter()2041 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2042   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2043   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2044     impl->SetGlobalTestPartResultReporter(old_reporter_);
2045   } else {
2046     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2047   }
2048 }
2049 
2050 // Increments the test part result count and remembers the result.
2051 // This method is from the TestPartResultReporterInterface interface.
ReportTestPartResult(const TestPartResult & result)2052 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2053     const TestPartResult& result) {
2054   result_->Append(result);
2055 }
2056 
2057 namespace internal {
2058 
2059 // Returns the type ID of ::testing::Test.  We should always call this
2060 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2061 // testing::Test.  This is to work around a suspected linker bug when
2062 // using Google Test as a framework on Mac OS X.  The bug causes
2063 // GetTypeId< ::testing::Test>() to return different values depending
2064 // on whether the call is from the Google Test framework itself or
2065 // from user test code.  GetTestTypeId() is guaranteed to always
2066 // return the same value, as it always calls GetTypeId<>() from the
2067 // gtest.cc, which is within the Google Test framework.
GetTestTypeId()2068 TypeId GetTestTypeId() {
2069   return GetTypeId<Test>();
2070 }
2071 
2072 // The value of GetTestTypeId() as seen from within the Google Test
2073 // library.  This is solely for testing GetTestTypeId().
2074 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2075 
2076 // This predicate-formatter checks that 'results' contains a test part
2077 // failure of the given type and that the failure message contains the
2078 // given substring.
HasOneFailure(const char *,const char *,const char *,const TestPartResultArray & results,TestPartResult::Type type,const string & substr)2079 AssertionResult HasOneFailure(const char* /* results_expr */,
2080                               const char* /* type_expr */,
2081                               const char* /* substr_expr */,
2082                               const TestPartResultArray& results,
2083                               TestPartResult::Type type,
2084                               const string& substr) {
2085   const std::string expected(type == TestPartResult::kFatalFailure ?
2086                         "1 fatal failure" :
2087                         "1 non-fatal failure");
2088   Message msg;
2089   if (results.size() != 1) {
2090     msg << "Expected: " << expected << "\n"
2091         << "  Actual: " << results.size() << " failures";
2092     for (int i = 0; i < results.size(); i++) {
2093       msg << "\n" << results.GetTestPartResult(i);
2094     }
2095     return AssertionFailure() << msg;
2096   }
2097 
2098   const TestPartResult& r = results.GetTestPartResult(0);
2099   if (r.type() != type) {
2100     return AssertionFailure() << "Expected: " << expected << "\n"
2101                               << "  Actual:\n"
2102                               << r;
2103   }
2104 
2105   if (strstr(r.message(), substr.c_str()) == NULL) {
2106     return AssertionFailure() << "Expected: " << expected << " containing \""
2107                               << substr << "\"\n"
2108                               << "  Actual:\n"
2109                               << r;
2110   }
2111 
2112   return AssertionSuccess();
2113 }
2114 
2115 // The constructor of SingleFailureChecker remembers where to look up
2116 // test part results, what type of failure we expect, and what
2117 // substring the failure message should contain.
SingleFailureChecker(const TestPartResultArray * results,TestPartResult::Type type,const string & substr)2118 SingleFailureChecker:: SingleFailureChecker(
2119     const TestPartResultArray* results,
2120     TestPartResult::Type type,
2121     const string& substr)
2122     : results_(results),
2123       type_(type),
2124       substr_(substr) {}
2125 
2126 // The destructor of SingleFailureChecker verifies that the given
2127 // TestPartResultArray contains exactly one failure that has the given
2128 // type and contains the given substring.  If that's not the case, a
2129 // non-fatal failure will be generated.
~SingleFailureChecker()2130 SingleFailureChecker::~SingleFailureChecker() {
2131   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2132 }
2133 
DefaultGlobalTestPartResultReporter(UnitTestImpl * unit_test)2134 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2135     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2136 
ReportTestPartResult(const TestPartResult & result)2137 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2138     const TestPartResult& result) {
2139   unit_test_->current_test_result()->AddTestPartResult(result);
2140   unit_test_->listeners()->repeater()->OnTestPartResult(result);
2141 }
2142 
DefaultPerThreadTestPartResultReporter(UnitTestImpl * unit_test)2143 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2144     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2145 
ReportTestPartResult(const TestPartResult & result)2146 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2147     const TestPartResult& result) {
2148   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2149 }
2150 
2151 // Returns the global test part result reporter.
2152 TestPartResultReporterInterface*
GetGlobalTestPartResultReporter()2153 UnitTestImpl::GetGlobalTestPartResultReporter() {
2154   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2155   return global_test_part_result_repoter_;
2156 }
2157 
2158 // Sets the global test part result reporter.
SetGlobalTestPartResultReporter(TestPartResultReporterInterface * reporter)2159 void UnitTestImpl::SetGlobalTestPartResultReporter(
2160     TestPartResultReporterInterface* reporter) {
2161   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2162   global_test_part_result_repoter_ = reporter;
2163 }
2164 
2165 // Returns the test part result reporter for the current thread.
2166 TestPartResultReporterInterface*
GetTestPartResultReporterForCurrentThread()2167 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2168   return per_thread_test_part_result_reporter_.get();
2169 }
2170 
2171 // Sets the test part result reporter for the current thread.
SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface * reporter)2172 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2173     TestPartResultReporterInterface* reporter) {
2174   per_thread_test_part_result_reporter_.set(reporter);
2175 }
2176 
2177 // Gets the number of successful test cases.
successful_test_case_count() const2178 int UnitTestImpl::successful_test_case_count() const {
2179   return CountIf(test_cases_, TestCasePassed);
2180 }
2181 
2182 // Gets the number of failed test cases.
failed_test_case_count() const2183 int UnitTestImpl::failed_test_case_count() const {
2184   return CountIf(test_cases_, TestCaseFailed);
2185 }
2186 
2187 // Gets the number of all test cases.
total_test_case_count() const2188 int UnitTestImpl::total_test_case_count() const {
2189   return static_cast<int>(test_cases_.size());
2190 }
2191 
2192 // Gets the number of all test cases that contain at least one test
2193 // that should run.
test_case_to_run_count() const2194 int UnitTestImpl::test_case_to_run_count() const {
2195   return CountIf(test_cases_, ShouldRunTestCase);
2196 }
2197 
2198 // Gets the number of successful tests.
successful_test_count() const2199 int UnitTestImpl::successful_test_count() const {
2200   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2201 }
2202 
2203 // Gets the number of failed tests.
failed_test_count() const2204 int UnitTestImpl::failed_test_count() const {
2205   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2206 }
2207 
2208 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const2209 int UnitTestImpl::reportable_disabled_test_count() const {
2210   return SumOverTestCaseList(test_cases_,
2211                              &TestCase::reportable_disabled_test_count);
2212 }
2213 
2214 // Gets the number of disabled tests.
disabled_test_count() const2215 int UnitTestImpl::disabled_test_count() const {
2216   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2217 }
2218 
2219 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const2220 int UnitTestImpl::reportable_test_count() const {
2221   return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2222 }
2223 
2224 // Gets the number of all tests.
total_test_count() const2225 int UnitTestImpl::total_test_count() const {
2226   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2227 }
2228 
2229 // Gets the number of tests that should run.
test_to_run_count() const2230 int UnitTestImpl::test_to_run_count() const {
2231   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2232 }
2233 
2234 // Returns the current OS stack trace as an std::string.
2235 //
2236 // The maximum number of stack frames to be included is specified by
2237 // the gtest_stack_trace_depth flag.  The skip_count parameter
2238 // specifies the number of top frames to be skipped, which doesn't
2239 // count against the number of frames to be included.
2240 //
2241 // For example, if Foo() calls Bar(), which in turn calls
2242 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2243 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
CurrentOsStackTraceExceptTop(int skip_count)2244 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2245   return os_stack_trace_getter()->CurrentStackTrace(
2246       static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2247       skip_count + 1
2248       // Skips the user-specified number of frames plus this function
2249       // itself.
2250       );  // NOLINT
2251 }
2252 
2253 // Returns the current time in milliseconds.
GetTimeInMillis()2254 TimeInMillis GetTimeInMillis() {
2255 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2256   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2257   // http://analogous.blogspot.com/2005/04/epoch.html
2258   const TimeInMillis kJavaEpochToWinFileTimeDelta =
2259     static_cast<TimeInMillis>(116444736UL) * 100000UL;
2260   const DWORD kTenthMicrosInMilliSecond = 10000;
2261 
2262   SYSTEMTIME now_systime;
2263   FILETIME now_filetime;
2264   ULARGE_INTEGER now_int64;
2265   // TODO(kenton@google.com): Shouldn't this just use
2266   //   GetSystemTimeAsFileTime()?
2267   GetSystemTime(&now_systime);
2268   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2269     now_int64.LowPart = now_filetime.dwLowDateTime;
2270     now_int64.HighPart = now_filetime.dwHighDateTime;
2271     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2272       kJavaEpochToWinFileTimeDelta;
2273     return now_int64.QuadPart;
2274   }
2275   return 0;
2276 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2277   __timeb64 now;
2278 
2279   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2280   // (deprecated function) there.
2281   // TODO(kenton@google.com): Use GetTickCount()?  Or use
2282   //   SystemTimeToFileTime()
2283   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
2284   _ftime64(&now);
2285   GTEST_DISABLE_MSC_WARNINGS_POP_()
2286 
2287   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2288 #elif GTEST_HAS_GETTIMEOFDAY_
2289   struct timeval now;
2290   gettimeofday(&now, NULL);
2291   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2292 #else
2293 # error "Don't know how to get the current time on your system."
2294 #endif
2295 }
2296 
2297 // Utilities
2298 
2299 // class String.
2300 
2301 #if GTEST_OS_WINDOWS_MOBILE
2302 // Creates a UTF-16 wide string from the given ANSI string, allocating
2303 // memory using new. The caller is responsible for deleting the return
2304 // value using delete[]. Returns the wide string, or NULL if the
2305 // input is NULL.
AnsiToUtf16(const char * ansi)2306 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2307   if (!ansi) return NULL;
2308   const int length = strlen(ansi);
2309   const int unicode_length =
2310       MultiByteToWideChar(CP_ACP, 0, ansi, length,
2311                           NULL, 0);
2312   WCHAR* unicode = new WCHAR[unicode_length + 1];
2313   MultiByteToWideChar(CP_ACP, 0, ansi, length,
2314                       unicode, unicode_length);
2315   unicode[unicode_length] = 0;
2316   return unicode;
2317 }
2318 
2319 // Creates an ANSI string from the given wide string, allocating
2320 // memory using new. The caller is responsible for deleting the return
2321 // value using delete[]. Returns the ANSI string, or NULL if the
2322 // input is NULL.
Utf16ToAnsi(LPCWSTR utf16_str)2323 const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
2324   if (!utf16_str) return NULL;
2325   const int ansi_length =
2326       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2327                           NULL, 0, NULL, NULL);
2328   char* ansi = new char[ansi_length + 1];
2329   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2330                       ansi, ansi_length, NULL, NULL);
2331   ansi[ansi_length] = 0;
2332   return ansi;
2333 }
2334 
2335 #endif  // GTEST_OS_WINDOWS_MOBILE
2336 
2337 // Compares two C strings.  Returns true iff they have the same content.
2338 //
2339 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
2340 // C string is considered different to any non-NULL C string,
2341 // including the empty string.
CStringEquals(const char * lhs,const char * rhs)2342 bool String::CStringEquals(const char * lhs, const char * rhs) {
2343   if ( lhs == NULL ) return rhs == NULL;
2344 
2345   if ( rhs == NULL ) return false;
2346 
2347   return strcmp(lhs, rhs) == 0;
2348 }
2349 
2350 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2351 
2352 // Converts an array of wide chars to a narrow string using the UTF-8
2353 // encoding, and streams the result to the given Message object.
StreamWideCharsToMessage(const wchar_t * wstr,size_t length,Message * msg)2354 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2355                                      Message* msg) {
2356   for (size_t i = 0; i != length; ) {  // NOLINT
2357     if (wstr[i] != L'\0') {
2358       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2359       while (i != length && wstr[i] != L'\0')
2360         i++;
2361     } else {
2362       *msg << '\0';
2363       i++;
2364     }
2365   }
2366 }
2367 
2368 #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2369 
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)2370 void SplitString(const ::std::string& str, char delimiter,
2371                  ::std::vector< ::std::string>* dest) {
2372   ::std::vector< ::std::string> parsed;
2373   ::std::string::size_type pos = 0;
2374   while (::testing::internal::AlwaysTrue()) {
2375     const ::std::string::size_type colon = str.find(delimiter, pos);
2376     if (colon == ::std::string::npos) {
2377       parsed.push_back(str.substr(pos));
2378       break;
2379     } else {
2380       parsed.push_back(str.substr(pos, colon - pos));
2381       pos = colon + 1;
2382     }
2383   }
2384   dest->swap(parsed);
2385 }
2386 
2387 }  // namespace internal
2388 
2389 // Constructs an empty Message.
2390 // We allocate the stringstream separately because otherwise each use of
2391 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2392 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2393 // the stack space.
Message()2394 Message::Message() : ss_(new ::std::stringstream) {
2395   // By default, we want there to be enough precision when printing
2396   // a double to a Message.
2397   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2398 }
2399 
2400 // These two overloads allow streaming a wide C string to a Message
2401 // using the UTF-8 encoding.
operator <<(const wchar_t * wide_c_str)2402 Message& Message::operator <<(const wchar_t* wide_c_str) {
2403   return *this << internal::String::ShowWideCString(wide_c_str);
2404 }
operator <<(wchar_t * wide_c_str)2405 Message& Message::operator <<(wchar_t* wide_c_str) {
2406   return *this << internal::String::ShowWideCString(wide_c_str);
2407 }
2408 
2409 #if GTEST_HAS_STD_WSTRING
2410 // Converts the given wide string to a narrow string using the UTF-8
2411 // encoding, and streams the result to this Message object.
operator <<(const::std::wstring & wstr)2412 Message& Message::operator <<(const ::std::wstring& wstr) {
2413   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2414   return *this;
2415 }
2416 #endif  // GTEST_HAS_STD_WSTRING
2417 
2418 #if GTEST_HAS_GLOBAL_WSTRING
2419 // Converts the given wide string to a narrow string using the UTF-8
2420 // encoding, and streams the result to this Message object.
operator <<(const::wstring & wstr)2421 Message& Message::operator <<(const ::wstring& wstr) {
2422   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2423   return *this;
2424 }
2425 #endif  // GTEST_HAS_GLOBAL_WSTRING
2426 
2427 // Gets the text streamed to this object so far as an std::string.
2428 // Each '\0' character in the buffer is replaced with "\\0".
GetString() const2429 std::string Message::GetString() const {
2430   return internal::StringStreamToString(ss_.get());
2431 }
2432 
2433 // AssertionResult constructors.
2434 // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult & other)2435 AssertionResult::AssertionResult(const AssertionResult& other)
2436     : success_(other.success_),
2437       message_(other.message_.get() != NULL ?
2438                new ::std::string(*other.message_) :
2439                static_cast< ::std::string*>(NULL)) {
2440 }
2441 
2442 // Swaps two AssertionResults.
swap(AssertionResult & other)2443 void AssertionResult::swap(AssertionResult& other) {
2444   using std::swap;
2445   swap(success_, other.success_);
2446   swap(message_, other.message_);
2447 }
2448 
2449 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
operator !() const2450 AssertionResult AssertionResult::operator!() const {
2451   AssertionResult negation(!success_);
2452   if (message_.get() != NULL)
2453     negation << *message_;
2454   return negation;
2455 }
2456 
2457 // Makes a successful assertion result.
AssertionSuccess()2458 AssertionResult AssertionSuccess() {
2459   return AssertionResult(true);
2460 }
2461 
2462 // Makes a failed assertion result.
AssertionFailure()2463 AssertionResult AssertionFailure() {
2464   return AssertionResult(false);
2465 }
2466 
2467 // Makes a failed assertion result with the given failure message.
2468 // Deprecated; use AssertionFailure() << message.
AssertionFailure(const Message & message)2469 AssertionResult AssertionFailure(const Message& message) {
2470   return AssertionFailure() << message;
2471 }
2472 
2473 namespace internal {
2474 
2475 namespace edit_distance {
CalculateOptimalEdits(const std::vector<size_t> & left,const std::vector<size_t> & right)2476 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2477                                             const std::vector<size_t>& right) {
2478   std::vector<std::vector<double> > costs(
2479       left.size() + 1, std::vector<double>(right.size() + 1));
2480   std::vector<std::vector<EditType> > best_move(
2481       left.size() + 1, std::vector<EditType>(right.size() + 1));
2482 
2483   // Populate for empty right.
2484   for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2485     costs[l_i][0] = static_cast<double>(l_i);
2486     best_move[l_i][0] = kRemove;
2487   }
2488   // Populate for empty left.
2489   for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2490     costs[0][r_i] = static_cast<double>(r_i);
2491     best_move[0][r_i] = kAdd;
2492   }
2493 
2494   for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2495     for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2496       if (left[l_i] == right[r_i]) {
2497         // Found a match. Consume it.
2498         costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2499         best_move[l_i + 1][r_i + 1] = kMatch;
2500         continue;
2501       }
2502 
2503       const double add = costs[l_i + 1][r_i];
2504       const double remove = costs[l_i][r_i + 1];
2505       const double replace = costs[l_i][r_i];
2506       if (add < remove && add < replace) {
2507         costs[l_i + 1][r_i + 1] = add + 1;
2508         best_move[l_i + 1][r_i + 1] = kAdd;
2509       } else if (remove < add && remove < replace) {
2510         costs[l_i + 1][r_i + 1] = remove + 1;
2511         best_move[l_i + 1][r_i + 1] = kRemove;
2512       } else {
2513         // We make replace a little more expensive than add/remove to lower
2514         // their priority.
2515         costs[l_i + 1][r_i + 1] = replace + 1.00001;
2516         best_move[l_i + 1][r_i + 1] = kReplace;
2517       }
2518     }
2519   }
2520 
2521   // Reconstruct the best path. We do it in reverse order.
2522   std::vector<EditType> best_path;
2523   for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2524     EditType move = best_move[l_i][r_i];
2525     best_path.push_back(move);
2526     l_i -= move != kAdd;
2527     r_i -= move != kRemove;
2528   }
2529   std::reverse(best_path.begin(), best_path.end());
2530   return best_path;
2531 }
2532 
2533 namespace {
2534 
2535 // Helper class to convert string into ids with deduplication.
2536 class InternalStrings {
2537  public:
GetId(const std::string & str)2538   size_t GetId(const std::string& str) {
2539     IdMap::iterator it = ids_.find(str);
2540     if (it != ids_.end()) return it->second;
2541     size_t id = ids_.size();
2542     return ids_[str] = id;
2543   }
2544 
2545  private:
2546   typedef std::map<std::string, size_t> IdMap;
2547   IdMap ids_;
2548 };
2549 
2550 }  // namespace
2551 
CalculateOptimalEdits(const std::vector<std::string> & left,const std::vector<std::string> & right)2552 std::vector<EditType> CalculateOptimalEdits(
2553     const std::vector<std::string>& left,
2554     const std::vector<std::string>& right) {
2555   std::vector<size_t> left_ids, right_ids;
2556   {
2557     InternalStrings intern_table;
2558     for (size_t i = 0; i < left.size(); ++i) {
2559       left_ids.push_back(intern_table.GetId(left[i]));
2560     }
2561     for (size_t i = 0; i < right.size(); ++i) {
2562       right_ids.push_back(intern_table.GetId(right[i]));
2563     }
2564   }
2565   return CalculateOptimalEdits(left_ids, right_ids);
2566 }
2567 
2568 namespace {
2569 
2570 // Helper class that holds the state for one hunk and prints it out to the
2571 // stream.
2572 // It reorders adds/removes when possible to group all removes before all
2573 // adds. It also adds the hunk header before printint into the stream.
2574 class Hunk {
2575  public:
Hunk(size_t left_start,size_t right_start)2576   Hunk(size_t left_start, size_t right_start)
2577       : left_start_(left_start),
2578         right_start_(right_start),
2579         adds_(),
2580         removes_(),
2581         common_() {}
2582 
PushLine(char edit,const char * line)2583   void PushLine(char edit, const char* line) {
2584     switch (edit) {
2585       case ' ':
2586         ++common_;
2587         FlushEdits();
2588         hunk_.push_back(std::make_pair(' ', line));
2589         break;
2590       case '-':
2591         ++removes_;
2592         hunk_removes_.push_back(std::make_pair('-', line));
2593         break;
2594       case '+':
2595         ++adds_;
2596         hunk_adds_.push_back(std::make_pair('+', line));
2597         break;
2598     }
2599   }
2600 
PrintTo(std::ostream * os)2601   void PrintTo(std::ostream* os) {
2602     PrintHeader(os);
2603     FlushEdits();
2604     for (std::list<std::pair<char, const char*> >::const_iterator it =
2605              hunk_.begin();
2606          it != hunk_.end(); ++it) {
2607       *os << it->first << it->second << "\n";
2608     }
2609   }
2610 
has_edits() const2611   bool has_edits() const { return adds_ || removes_; }
2612 
2613  private:
FlushEdits()2614   void FlushEdits() {
2615     hunk_.splice(hunk_.end(), hunk_removes_);
2616     hunk_.splice(hunk_.end(), hunk_adds_);
2617   }
2618 
2619   // Print a unified diff header for one hunk.
2620   // The format is
2621   //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2622   // where the left/right parts are ommitted if unnecessary.
PrintHeader(std::ostream * ss) const2623   void PrintHeader(std::ostream* ss) const {
2624     *ss << "@@ ";
2625     if (removes_) {
2626       *ss << "-" << left_start_ << "," << (removes_ + common_);
2627     }
2628     if (removes_ && adds_) {
2629       *ss << " ";
2630     }
2631     if (adds_) {
2632       *ss << "+" << right_start_ << "," << (adds_ + common_);
2633     }
2634     *ss << " @@\n";
2635   }
2636 
2637   size_t left_start_, right_start_;
2638   size_t adds_, removes_, common_;
2639   std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2640 };
2641 
2642 }  // namespace
2643 
2644 // Create a list of diff hunks in Unified diff format.
2645 // Each hunk has a header generated by PrintHeader above plus a body with
2646 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
2647 // addition.
2648 // 'context' represents the desired unchanged prefix/suffix around the diff.
2649 // If two hunks are close enough that their contexts overlap, then they are
2650 // joined into one hunk.
CreateUnifiedDiff(const std::vector<std::string> & left,const std::vector<std::string> & right,size_t context)2651 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2652                               const std::vector<std::string>& right,
2653                               size_t context) {
2654   const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2655 
2656   size_t l_i = 0, r_i = 0, edit_i = 0;
2657   std::stringstream ss;
2658   while (edit_i < edits.size()) {
2659     // Find first edit.
2660     while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2661       ++l_i;
2662       ++r_i;
2663       ++edit_i;
2664     }
2665 
2666     // Find the first line to include in the hunk.
2667     const size_t prefix_context = std::min(l_i, context);
2668     Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2669     for (size_t i = prefix_context; i > 0; --i) {
2670       hunk.PushLine(' ', left[l_i - i].c_str());
2671     }
2672 
2673     // Iterate the edits until we found enough suffix for the hunk or the input
2674     // is over.
2675     size_t n_suffix = 0;
2676     for (; edit_i < edits.size(); ++edit_i) {
2677       if (n_suffix >= context) {
2678         // Continue only if the next hunk is very close.
2679         std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2680         while (it != edits.end() && *it == kMatch) ++it;
2681         if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2682           // There is no next edit or it is too far away.
2683           break;
2684         }
2685       }
2686 
2687       EditType edit = edits[edit_i];
2688       // Reset count when a non match is found.
2689       n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2690 
2691       if (edit == kMatch || edit == kRemove || edit == kReplace) {
2692         hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2693       }
2694       if (edit == kAdd || edit == kReplace) {
2695         hunk.PushLine('+', right[r_i].c_str());
2696       }
2697 
2698       // Advance indices, depending on edit type.
2699       l_i += edit != kAdd;
2700       r_i += edit != kRemove;
2701     }
2702 
2703     if (!hunk.has_edits()) {
2704       // We are done. We don't want this hunk.
2705       break;
2706     }
2707 
2708     hunk.PrintTo(&ss);
2709   }
2710   return ss.str();
2711 }
2712 
2713 }  // namespace edit_distance
2714 
2715 namespace {
2716 
2717 // The string representation of the values received in EqFailure() are already
2718 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2719 // characters the same.
SplitEscapedString(const std::string & str)2720 std::vector<std::string> SplitEscapedString(const std::string& str) {
2721   std::vector<std::string> lines;
2722   size_t start = 0, end = str.size();
2723   if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2724     ++start;
2725     --end;
2726   }
2727   bool escaped = false;
2728   for (size_t i = start; i + 1 < end; ++i) {
2729     if (escaped) {
2730       escaped = false;
2731       if (str[i] == 'n') {
2732         lines.push_back(str.substr(start, i - start - 1));
2733         start = i + 1;
2734       }
2735     } else {
2736       escaped = str[i] == '\\';
2737     }
2738   }
2739   lines.push_back(str.substr(start, end - start));
2740   return lines;
2741 }
2742 
2743 }  // namespace
2744 
2745 // Constructs and returns the message for an equality assertion
2746 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2747 //
2748 // The first four parameters are the expressions used in the assertion
2749 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
2750 // where foo is 5 and bar is 6, we have:
2751 //
2752 //   lhs_expression: "foo"
2753 //   rhs_expression: "bar"
2754 //   lhs_value:      "5"
2755 //   rhs_value:      "6"
2756 //
2757 // The ignoring_case parameter is true iff the assertion is a
2758 // *_STRCASEEQ*.  When it's true, the string "Ignoring case" will
2759 // 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)2760 AssertionResult EqFailure(const char* lhs_expression,
2761                           const char* rhs_expression,
2762                           const std::string& lhs_value,
2763                           const std::string& rhs_value,
2764                           bool ignoring_case) {
2765   Message msg;
2766   msg << "      Expected: " << lhs_expression;
2767   if (lhs_value != lhs_expression) {
2768     msg << "\n      Which is: " << lhs_value;
2769   }
2770   msg << "\nTo be equal to: " << rhs_expression;
2771   if (rhs_value != rhs_expression) {
2772     msg << "\n      Which is: " << rhs_value;
2773   }
2774 
2775   if (ignoring_case) {
2776     msg << "\nIgnoring case";
2777   }
2778 
2779   if (!lhs_value.empty() && !rhs_value.empty()) {
2780     const std::vector<std::string> lhs_lines =
2781         SplitEscapedString(lhs_value);
2782     const std::vector<std::string> rhs_lines =
2783         SplitEscapedString(rhs_value);
2784     if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2785       msg << "\nWith diff:\n"
2786           << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
2787     }
2788   }
2789 
2790   return AssertionFailure() << msg;
2791 }
2792 
2793 // 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)2794 std::string GetBoolAssertionFailureMessage(
2795     const AssertionResult& assertion_result,
2796     const char* expression_text,
2797     const char* actual_predicate_value,
2798     const char* expected_predicate_value) {
2799   const char* actual_message = assertion_result.message();
2800   Message msg;
2801   msg << "Value of: " << expression_text
2802       << "\n  Actual: " << actual_predicate_value;
2803   if (actual_message[0] != '\0')
2804     msg << " (" << actual_message << ")";
2805   msg << "\nExpected: " << expected_predicate_value;
2806   return msg.GetString();
2807 }
2808 
2809 // 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)2810 AssertionResult DoubleNearPredFormat(const char* expr1,
2811                                      const char* expr2,
2812                                      const char* abs_error_expr,
2813                                      double val1,
2814                                      double val2,
2815                                      double abs_error) {
2816   const double diff = fabs(val1 - val2);
2817   if (diff <= abs_error) return AssertionSuccess();
2818 
2819   // TODO(wan): do not print the value of an expression if it's
2820   // already a literal.
2821   return AssertionFailure()
2822       << "The difference between " << expr1 << " and " << expr2
2823       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2824       << expr1 << " evaluates to " << val1 << ",\n"
2825       << expr2 << " evaluates to " << val2 << ", and\n"
2826       << abs_error_expr << " evaluates to " << abs_error << ".";
2827 }
2828 
2829 
2830 // Helper template for implementing FloatLE() and DoubleLE().
2831 template <typename RawType>
FloatingPointLE(const char * expr1,const char * expr2,RawType val1,RawType val2)2832 AssertionResult FloatingPointLE(const char* expr1,
2833                                 const char* expr2,
2834                                 RawType val1,
2835                                 RawType val2) {
2836   // Returns success if val1 is less than val2,
2837   if (val1 < val2) {
2838     return AssertionSuccess();
2839   }
2840 
2841   // or if val1 is almost equal to val2.
2842   const FloatingPoint<RawType> lhs(val1), rhs(val2);
2843   if (lhs.AlmostEquals(rhs)) {
2844     return AssertionSuccess();
2845   }
2846 
2847   // Note that the above two checks will both fail if either val1 or
2848   // val2 is NaN, as the IEEE floating-point standard requires that
2849   // any predicate involving a NaN must return false.
2850 
2851   ::std::stringstream val1_ss;
2852   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2853           << val1;
2854 
2855   ::std::stringstream val2_ss;
2856   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2857           << val2;
2858 
2859   return AssertionFailure()
2860       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2861       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
2862       << StringStreamToString(&val2_ss);
2863 }
2864 
2865 }  // namespace internal
2866 
2867 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2868 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
FloatLE(const char * expr1,const char * expr2,float val1,float val2)2869 AssertionResult FloatLE(const char* expr1, const char* expr2,
2870                         float val1, float val2) {
2871   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2872 }
2873 
2874 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2875 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
DoubleLE(const char * expr1,const char * expr2,double val1,double val2)2876 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2877                          double val1, double val2) {
2878   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2879 }
2880 
2881 namespace internal {
2882 
2883 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2884 // arguments.
CmpHelperEQ(const char * lhs_expression,const char * rhs_expression,BiggestInt lhs,BiggestInt rhs)2885 AssertionResult CmpHelperEQ(const char* lhs_expression,
2886                             const char* rhs_expression,
2887                             BiggestInt lhs,
2888                             BiggestInt rhs) {
2889   if (lhs == rhs) {
2890     return AssertionSuccess();
2891   }
2892 
2893   return EqFailure(lhs_expression,
2894                    rhs_expression,
2895                    FormatForComparisonFailureMessage(lhs, rhs),
2896                    FormatForComparisonFailureMessage(rhs, lhs),
2897                    false);
2898 }
2899 
2900 // A macro for implementing the helper functions needed to implement
2901 // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
2902 // just to avoid copy-and-paste of similar code.
2903 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2904 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2905                                    BiggestInt val1, BiggestInt val2) {\
2906   if (val1 op val2) {\
2907     return AssertionSuccess();\
2908   } else {\
2909     return AssertionFailure() \
2910         << "Expected: (" << expr1 << ") " #op " (" << expr2\
2911         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2912         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2913   }\
2914 }
2915 
2916 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2917 // enum arguments.
2918 GTEST_IMPL_CMP_HELPER_(NE, !=)
2919 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2920 // enum arguments.
2921 GTEST_IMPL_CMP_HELPER_(LE, <=)
2922 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2923 // enum arguments.
2924 GTEST_IMPL_CMP_HELPER_(LT, < )
2925 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2926 // enum arguments.
2927 GTEST_IMPL_CMP_HELPER_(GE, >=)
2928 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2929 // enum arguments.
2930 GTEST_IMPL_CMP_HELPER_(GT, > )
2931 
2932 #undef GTEST_IMPL_CMP_HELPER_
2933 
2934 // The helper function for {ASSERT|EXPECT}_STREQ.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)2935 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2936                                const char* rhs_expression,
2937                                const char* lhs,
2938                                const char* rhs) {
2939   if (String::CStringEquals(lhs, rhs)) {
2940     return AssertionSuccess();
2941   }
2942 
2943   return EqFailure(lhs_expression,
2944                    rhs_expression,
2945                    PrintToString(lhs),
2946                    PrintToString(rhs),
2947                    false);
2948 }
2949 
2950 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)2951 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
2952                                    const char* rhs_expression,
2953                                    const char* lhs,
2954                                    const char* rhs) {
2955   if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
2956     return AssertionSuccess();
2957   }
2958 
2959   return EqFailure(lhs_expression,
2960                    rhs_expression,
2961                    PrintToString(lhs),
2962                    PrintToString(rhs),
2963                    true);
2964 }
2965 
2966 // The helper function for {ASSERT|EXPECT}_STRNE.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)2967 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2968                                const char* s2_expression,
2969                                const char* s1,
2970                                const char* s2) {
2971   if (!String::CStringEquals(s1, s2)) {
2972     return AssertionSuccess();
2973   } else {
2974     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2975                               << s2_expression << "), actual: \""
2976                               << s1 << "\" vs \"" << s2 << "\"";
2977   }
2978 }
2979 
2980 // The helper function for {ASSERT|EXPECT}_STRCASENE.
CmpHelperSTRCASENE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)2981 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2982                                    const char* s2_expression,
2983                                    const char* s1,
2984                                    const char* s2) {
2985   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2986     return AssertionSuccess();
2987   } else {
2988     return AssertionFailure()
2989         << "Expected: (" << s1_expression << ") != ("
2990         << s2_expression << ") (ignoring case), actual: \""
2991         << s1 << "\" vs \"" << s2 << "\"";
2992   }
2993 }
2994 
2995 }  // namespace internal
2996 
2997 namespace {
2998 
2999 // Helper functions for implementing IsSubString() and IsNotSubstring().
3000 
3001 // This group of overloaded functions return true iff needle is a
3002 // substring of haystack.  NULL is considered a substring of itself
3003 // only.
3004 
IsSubstringPred(const char * needle,const char * haystack)3005 bool IsSubstringPred(const char* needle, const char* haystack) {
3006   if (needle == NULL || haystack == NULL)
3007     return needle == haystack;
3008 
3009   return strstr(haystack, needle) != NULL;
3010 }
3011 
IsSubstringPred(const wchar_t * needle,const wchar_t * haystack)3012 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3013   if (needle == NULL || haystack == NULL)
3014     return needle == haystack;
3015 
3016   return wcsstr(haystack, needle) != NULL;
3017 }
3018 
3019 // StringType here can be either ::std::string or ::std::wstring.
3020 template <typename StringType>
IsSubstringPred(const StringType & needle,const StringType & haystack)3021 bool IsSubstringPred(const StringType& needle,
3022                      const StringType& haystack) {
3023   return haystack.find(needle) != StringType::npos;
3024 }
3025 
3026 // This function implements either IsSubstring() or IsNotSubstring(),
3027 // depending on the value of the expected_to_be_substring parameter.
3028 // StringType here can be const char*, const wchar_t*, ::std::string,
3029 // or ::std::wstring.
3030 template <typename StringType>
IsSubstringImpl(bool expected_to_be_substring,const char * needle_expr,const char * haystack_expr,const StringType & needle,const StringType & haystack)3031 AssertionResult IsSubstringImpl(
3032     bool expected_to_be_substring,
3033     const char* needle_expr, const char* haystack_expr,
3034     const StringType& needle, const StringType& haystack) {
3035   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3036     return AssertionSuccess();
3037 
3038   const bool is_wide_string = sizeof(needle[0]) > 1;
3039   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3040   return AssertionFailure()
3041       << "Value of: " << needle_expr << "\n"
3042       << "  Actual: " << begin_string_quote << needle << "\"\n"
3043       << "Expected: " << (expected_to_be_substring ? "" : "not ")
3044       << "a substring of " << haystack_expr << "\n"
3045       << "Which is: " << begin_string_quote << haystack << "\"";
3046 }
3047 
3048 }  // namespace
3049 
3050 // IsSubstring() and IsNotSubstring() check whether needle is a
3051 // substring of haystack (NULL is considered a substring of itself
3052 // only), and return an appropriate error message when they fail.
3053 
IsSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3054 AssertionResult IsSubstring(
3055     const char* needle_expr, const char* haystack_expr,
3056     const char* needle, const char* haystack) {
3057   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3058 }
3059 
IsSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3060 AssertionResult IsSubstring(
3061     const char* needle_expr, const char* haystack_expr,
3062     const wchar_t* needle, const wchar_t* haystack) {
3063   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3064 }
3065 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)3066 AssertionResult IsNotSubstring(
3067     const char* needle_expr, const char* haystack_expr,
3068     const char* needle, const char* haystack) {
3069   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3070 }
3071 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)3072 AssertionResult IsNotSubstring(
3073     const char* needle_expr, const char* haystack_expr,
3074     const wchar_t* needle, const wchar_t* haystack) {
3075   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3076 }
3077 
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3078 AssertionResult IsSubstring(
3079     const char* needle_expr, const char* haystack_expr,
3080     const ::std::string& needle, const ::std::string& haystack) {
3081   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3082 }
3083 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)3084 AssertionResult IsNotSubstring(
3085     const char* needle_expr, const char* haystack_expr,
3086     const ::std::string& needle, const ::std::string& haystack) {
3087   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3088 }
3089 
3090 #if GTEST_HAS_STD_WSTRING
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3091 AssertionResult IsSubstring(
3092     const char* needle_expr, const char* haystack_expr,
3093     const ::std::wstring& needle, const ::std::wstring& haystack) {
3094   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3095 }
3096 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)3097 AssertionResult IsNotSubstring(
3098     const char* needle_expr, const char* haystack_expr,
3099     const ::std::wstring& needle, const ::std::wstring& haystack) {
3100   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3101 }
3102 #endif  // GTEST_HAS_STD_WSTRING
3103 
3104 namespace internal {
3105 
3106 #if GTEST_OS_WINDOWS
3107 
3108 namespace {
3109 
3110 // Helper function for IsHRESULT{SuccessFailure} predicates
HRESULTFailureHelper(const char * expr,const char * expected,long hr)3111 AssertionResult HRESULTFailureHelper(const char* expr,
3112                                      const char* expected,
3113                                      long hr) {  // NOLINT
3114 # if GTEST_OS_WINDOWS_MOBILE
3115 
3116   // Windows CE doesn't support FormatMessage.
3117   const char error_text[] = "";
3118 
3119 # else
3120 
3121   // Looks up the human-readable system message for the HRESULT code
3122   // and since we're not passing any params to FormatMessage, we don't
3123   // want inserts expanded.
3124   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3125                        FORMAT_MESSAGE_IGNORE_INSERTS;
3126   const DWORD kBufSize = 4096;
3127   // Gets the system's human readable message string for this HRESULT.
3128   char error_text[kBufSize] = { '\0' };
3129   DWORD message_length = ::FormatMessageA(kFlags,
3130                                           0,  // no source, we're asking system
3131                                           hr,  // the error
3132                                           0,  // no line width restrictions
3133                                           error_text,  // output buffer
3134                                           kBufSize,  // buf size
3135                                           NULL);  // no arguments for inserts
3136   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3137   for (; message_length && IsSpace(error_text[message_length - 1]);
3138           --message_length) {
3139     error_text[message_length - 1] = '\0';
3140   }
3141 
3142 # endif  // GTEST_OS_WINDOWS_MOBILE
3143 
3144   const std::string error_hex("0x" + String::FormatHexInt(hr));
3145   return ::testing::AssertionFailure()
3146       << "Expected: " << expr << " " << expected << ".\n"
3147       << "  Actual: " << error_hex << " " << error_text << "\n";
3148 }
3149 
3150 }  // namespace
3151 
IsHRESULTSuccess(const char * expr,long hr)3152 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
3153   if (SUCCEEDED(hr)) {
3154     return AssertionSuccess();
3155   }
3156   return HRESULTFailureHelper(expr, "succeeds", hr);
3157 }
3158 
IsHRESULTFailure(const char * expr,long hr)3159 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
3160   if (FAILED(hr)) {
3161     return AssertionSuccess();
3162   }
3163   return HRESULTFailureHelper(expr, "fails", hr);
3164 }
3165 
3166 #endif  // GTEST_OS_WINDOWS
3167 
3168 // Utility functions for encoding Unicode text (wide strings) in
3169 // UTF-8.
3170 
3171 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
3172 // like this:
3173 //
3174 // Code-point length   Encoding
3175 //   0 -  7 bits       0xxxxxxx
3176 //   8 - 11 bits       110xxxxx 10xxxxxx
3177 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
3178 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3179 
3180 // The maximum code-point a one-byte UTF-8 sequence can represent.
3181 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
3182 
3183 // The maximum code-point a two-byte UTF-8 sequence can represent.
3184 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
3185 
3186 // The maximum code-point a three-byte UTF-8 sequence can represent.
3187 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3188 
3189 // The maximum code-point a four-byte UTF-8 sequence can represent.
3190 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3191 
3192 // Chops off the n lowest bits from a bit pattern.  Returns the n
3193 // lowest bits.  As a side effect, the original bit pattern will be
3194 // shifted to the right by n bits.
ChopLowBits(UInt32 * bits,int n)3195 inline UInt32 ChopLowBits(UInt32* bits, int n) {
3196   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
3197   *bits >>= n;
3198   return low_bits;
3199 }
3200 
3201 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
3202 // code_point parameter is of type UInt32 because wchar_t may not be
3203 // wide enough to contain a code point.
3204 // If the code_point is not a valid Unicode code point
3205 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3206 // to "(Invalid Unicode 0xXXXXXXXX)".
CodePointToUtf8(UInt32 code_point)3207 std::string CodePointToUtf8(UInt32 code_point) {
3208   if (code_point > kMaxCodePoint4) {
3209     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
3210   }
3211 
3212   char str[5];  // Big enough for the largest valid code point.
3213   if (code_point <= kMaxCodePoint1) {
3214     str[1] = '\0';
3215     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
3216   } else if (code_point <= kMaxCodePoint2) {
3217     str[2] = '\0';
3218     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3219     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
3220   } else if (code_point <= kMaxCodePoint3) {
3221     str[3] = '\0';
3222     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3223     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3224     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
3225   } else {  // code_point <= kMaxCodePoint4
3226     str[4] = '\0';
3227     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3228     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3229     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
3230     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
3231   }
3232   return str;
3233 }
3234 
3235 // The following two functions only make sense if the the system
3236 // uses UTF-16 for wide string encoding. All supported systems
3237 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
3238 
3239 // Determines if the arguments constitute UTF-16 surrogate pair
3240 // and thus should be combined into a single Unicode code point
3241 // using CreateCodePointFromUtf16SurrogatePair.
IsUtf16SurrogatePair(wchar_t first,wchar_t second)3242 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3243   return sizeof(wchar_t) == 2 &&
3244       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3245 }
3246 
3247 // Creates a Unicode code point from UTF16 surrogate pair.
CreateCodePointFromUtf16SurrogatePair(wchar_t first,wchar_t second)3248 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3249                                                     wchar_t second) {
3250   const UInt32 mask = (1 << 10) - 1;
3251   return (sizeof(wchar_t) == 2) ?
3252       (((first & mask) << 10) | (second & mask)) + 0x10000 :
3253       // This function should not be called when the condition is
3254       // false, but we provide a sensible default in case it is.
3255       static_cast<UInt32>(first);
3256 }
3257 
3258 // Converts a wide string to a narrow string in UTF-8 encoding.
3259 // The wide string is assumed to have the following encoding:
3260 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
3261 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3262 // Parameter str points to a null-terminated wide string.
3263 // Parameter num_chars may additionally limit the number
3264 // of wchar_t characters processed. -1 is used when the entire string
3265 // should be processed.
3266 // If the string contains code points that are not valid Unicode code points
3267 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3268 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3269 // and contains invalid UTF-16 surrogate pairs, values in those pairs
3270 // will be encoded as individual Unicode characters from Basic Normal Plane.
WideStringToUtf8(const wchar_t * str,int num_chars)3271 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3272   if (num_chars == -1)
3273     num_chars = static_cast<int>(wcslen(str));
3274 
3275   ::std::stringstream stream;
3276   for (int i = 0; i < num_chars; ++i) {
3277     UInt32 unicode_code_point;
3278 
3279     if (str[i] == L'\0') {
3280       break;
3281     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3282       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3283                                                                  str[i + 1]);
3284       i++;
3285     } else {
3286       unicode_code_point = static_cast<UInt32>(str[i]);
3287     }
3288 
3289     stream << CodePointToUtf8(unicode_code_point);
3290   }
3291   return StringStreamToString(&stream);
3292 }
3293 
3294 // Converts a wide C string to an std::string using the UTF-8 encoding.
3295 // NULL will be converted to "(null)".
ShowWideCString(const wchar_t * wide_c_str)3296 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3297   if (wide_c_str == NULL)  return "(null)";
3298 
3299   return internal::WideStringToUtf8(wide_c_str, -1);
3300 }
3301 
3302 // Compares two wide C strings.  Returns true iff they have the same
3303 // content.
3304 //
3305 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
3306 // C string is considered different to any non-NULL C string,
3307 // including the empty string.
WideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3308 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3309   if (lhs == NULL) return rhs == NULL;
3310 
3311   if (rhs == NULL) return false;
3312 
3313   return wcscmp(lhs, rhs) == 0;
3314 }
3315 
3316 // Helper function for *_STREQ on wide strings.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const wchar_t * lhs,const wchar_t * rhs)3317 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3318                                const char* rhs_expression,
3319                                const wchar_t* lhs,
3320                                const wchar_t* rhs) {
3321   if (String::WideCStringEquals(lhs, rhs)) {
3322     return AssertionSuccess();
3323   }
3324 
3325   return EqFailure(lhs_expression,
3326                    rhs_expression,
3327                    PrintToString(lhs),
3328                    PrintToString(rhs),
3329                    false);
3330 }
3331 
3332 // Helper function for *_STRNE on wide strings.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const wchar_t * s1,const wchar_t * s2)3333 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3334                                const char* s2_expression,
3335                                const wchar_t* s1,
3336                                const wchar_t* s2) {
3337   if (!String::WideCStringEquals(s1, s2)) {
3338     return AssertionSuccess();
3339   }
3340 
3341   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3342                             << s2_expression << "), actual: "
3343                             << PrintToString(s1)
3344                             << " vs " << PrintToString(s2);
3345 }
3346 
3347 // Compares two C strings, ignoring case.  Returns true iff they have
3348 // the same content.
3349 //
3350 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
3351 // NULL C string is considered different to any non-NULL C string,
3352 // including the empty string.
CaseInsensitiveCStringEquals(const char * lhs,const char * rhs)3353 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3354   if (lhs == NULL)
3355     return rhs == NULL;
3356   if (rhs == NULL)
3357     return false;
3358   return posix::StrCaseCmp(lhs, rhs) == 0;
3359 }
3360 
3361   // Compares two wide C strings, ignoring case.  Returns true iff they
3362   // have the same content.
3363   //
3364   // Unlike wcscasecmp(), this function can handle NULL argument(s).
3365   // A NULL C string is considered different to any non-NULL wide C string,
3366   // including the empty string.
3367   // NB: The implementations on different platforms slightly differ.
3368   // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3369   // environment variable. On GNU platform this method uses wcscasecmp
3370   // which compares according to LC_CTYPE category of the current locale.
3371   // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3372   // current locale.
CaseInsensitiveWideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3373 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3374                                               const wchar_t* rhs) {
3375   if (lhs == NULL) return rhs == NULL;
3376 
3377   if (rhs == NULL) return false;
3378 
3379 #if GTEST_OS_WINDOWS
3380   return _wcsicmp(lhs, rhs) == 0;
3381 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3382   return wcscasecmp(lhs, rhs) == 0;
3383 #else
3384   // Android, Mac OS X and Cygwin don't define wcscasecmp.
3385   // Other unknown OSes may not define it either.
3386   wint_t left, right;
3387   do {
3388     left = towlower(*lhs++);
3389     right = towlower(*rhs++);
3390   } while (left && left == right);
3391   return left == right;
3392 #endif  // OS selector
3393 }
3394 
3395 // Returns true iff str ends with the given suffix, ignoring case.
3396 // Any string is considered to end with an empty suffix.
EndsWithCaseInsensitive(const std::string & str,const std::string & suffix)3397 bool String::EndsWithCaseInsensitive(
3398     const std::string& str, const std::string& suffix) {
3399   const size_t str_len = str.length();
3400   const size_t suffix_len = suffix.length();
3401   return (str_len >= suffix_len) &&
3402          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3403                                       suffix.c_str());
3404 }
3405 
3406 // Formats an int value as "%02d".
FormatIntWidth2(int value)3407 std::string String::FormatIntWidth2(int value) {
3408   std::stringstream ss;
3409   ss << std::setfill('0') << std::setw(2) << value;
3410   return ss.str();
3411 }
3412 
3413 // Formats an int value as "%X".
FormatHexInt(int value)3414 std::string String::FormatHexInt(int value) {
3415   std::stringstream ss;
3416   ss << std::hex << std::uppercase << value;
3417   return ss.str();
3418 }
3419 
3420 // Formats a byte as "%02X".
FormatByte(unsigned char value)3421 std::string String::FormatByte(unsigned char value) {
3422   std::stringstream ss;
3423   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3424      << static_cast<unsigned int>(value);
3425   return ss.str();
3426 }
3427 
3428 // Converts the buffer in a stringstream to an std::string, converting NUL
3429 // bytes to "\\0" along the way.
StringStreamToString(::std::stringstream * ss)3430 std::string StringStreamToString(::std::stringstream* ss) {
3431   const ::std::string& str = ss->str();
3432   const char* const start = str.c_str();
3433   const char* const end = start + str.length();
3434 
3435   std::string result;
3436   result.reserve(2 * (end - start));
3437   for (const char* ch = start; ch != end; ++ch) {
3438     if (*ch == '\0') {
3439       result += "\\0";  // Replaces NUL with "\\0";
3440     } else {
3441       result += *ch;
3442     }
3443   }
3444 
3445   return result;
3446 }
3447 
3448 // Appends the user-supplied message to the Google-Test-generated message.
AppendUserMessage(const std::string & gtest_msg,const Message & user_msg)3449 std::string AppendUserMessage(const std::string& gtest_msg,
3450                               const Message& user_msg) {
3451   // Appends the user message if it's non-empty.
3452   const std::string user_msg_string = user_msg.GetString();
3453   if (user_msg_string.empty()) {
3454     return gtest_msg;
3455   }
3456 
3457   return gtest_msg + "\n" + user_msg_string;
3458 }
3459 
3460 }  // namespace internal
3461 
3462 // class TestResult
3463 
3464 // Creates an empty TestResult.
TestResult()3465 TestResult::TestResult()
3466     : death_test_count_(0),
3467       elapsed_time_(0) {
3468 }
3469 
3470 // D'tor.
~TestResult()3471 TestResult::~TestResult() {
3472 }
3473 
3474 // Returns the i-th test part result among all the results. i can
3475 // range from 0 to total_part_count() - 1. If i is not in that range,
3476 // aborts the program.
GetTestPartResult(int i) const3477 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3478   if (i < 0 || i >= total_part_count())
3479     internal::posix::Abort();
3480   return test_part_results_.at(i);
3481 }
3482 
3483 // Returns the i-th test property. i can range from 0 to
3484 // test_property_count() - 1. If i is not in that range, aborts the
3485 // program.
GetTestProperty(int i) const3486 const TestProperty& TestResult::GetTestProperty(int i) const {
3487   if (i < 0 || i >= test_property_count())
3488     internal::posix::Abort();
3489   return test_properties_.at(i);
3490 }
3491 
3492 // Clears the test part results.
ClearTestPartResults()3493 void TestResult::ClearTestPartResults() {
3494   test_part_results_.clear();
3495 }
3496 
3497 // Adds a test part result to the list.
AddTestPartResult(const TestPartResult & test_part_result)3498 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3499   test_part_results_.push_back(test_part_result);
3500 }
3501 
3502 // Adds a test property to the list. If a property with the same key as the
3503 // supplied property is already represented, the value of this test_property
3504 // replaces the old value for that key.
RecordProperty(const std::string & xml_element,const TestProperty & test_property)3505 void TestResult::RecordProperty(const std::string& xml_element,
3506                                 const TestProperty& test_property) {
3507   if (!ValidateTestProperty(xml_element, test_property)) {
3508     return;
3509   }
3510   internal::MutexLock lock(&test_properites_mutex_);
3511   const std::vector<TestProperty>::iterator property_with_matching_key =
3512       std::find_if(test_properties_.begin(), test_properties_.end(),
3513                    internal::TestPropertyKeyIs(test_property.key()));
3514   if (property_with_matching_key == test_properties_.end()) {
3515     test_properties_.push_back(test_property);
3516     return;
3517   }
3518   property_with_matching_key->SetValue(test_property.value());
3519 }
3520 
3521 // The list of reserved attributes used in the <testsuites> element of XML
3522 // output.
3523 static const char* const kReservedTestSuitesAttributes[] = {
3524   "disabled",
3525   "errors",
3526   "failures",
3527   "name",
3528   "random_seed",
3529   "tests",
3530   "time",
3531   "timestamp"
3532 };
3533 
3534 // The list of reserved attributes used in the <testsuite> element of XML
3535 // output.
3536 static const char* const kReservedTestSuiteAttributes[] = {
3537   "disabled",
3538   "errors",
3539   "failures",
3540   "name",
3541   "tests",
3542   "time"
3543 };
3544 
3545 // The list of reserved attributes used in the <testcase> element of XML output.
3546 static const char* const kReservedTestCaseAttributes[] = {
3547   "classname",
3548   "name",
3549   "status",
3550   "time",
3551   "type_param",
3552   "value_param"
3553 };
3554 
3555 template <int kSize>
ArrayAsVector(const char * const (& array)[kSize])3556 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3557   return std::vector<std::string>(array, array + kSize);
3558 }
3559 
GetReservedAttributesForElement(const std::string & xml_element)3560 static std::vector<std::string> GetReservedAttributesForElement(
3561     const std::string& xml_element) {
3562   if (xml_element == "testsuites") {
3563     return ArrayAsVector(kReservedTestSuitesAttributes);
3564   } else if (xml_element == "testsuite") {
3565     return ArrayAsVector(kReservedTestSuiteAttributes);
3566   } else if (xml_element == "testcase") {
3567     return ArrayAsVector(kReservedTestCaseAttributes);
3568   } else {
3569     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3570   }
3571   // This code is unreachable but some compilers may not realizes that.
3572   return std::vector<std::string>();
3573 }
3574 
FormatWordList(const std::vector<std::string> & words)3575 static std::string FormatWordList(const std::vector<std::string>& words) {
3576   Message word_list;
3577   for (size_t i = 0; i < words.size(); ++i) {
3578     if (i > 0 && words.size() > 2) {
3579       word_list << ", ";
3580     }
3581     if (i == words.size() - 1) {
3582       word_list << "and ";
3583     }
3584     word_list << "'" << words[i] << "'";
3585   }
3586   return word_list.GetString();
3587 }
3588 
ValidateTestPropertyName(const std::string & property_name,const std::vector<std::string> & reserved_names)3589 bool ValidateTestPropertyName(const std::string& property_name,
3590                               const std::vector<std::string>& reserved_names) {
3591   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3592           reserved_names.end()) {
3593     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3594                   << " (" << FormatWordList(reserved_names)
3595                   << " are reserved by " << GTEST_NAME_ << ")";
3596     return false;
3597   }
3598   return true;
3599 }
3600 
3601 // Adds a failure if the key is a reserved attribute of the element named
3602 // xml_element.  Returns true if the property is valid.
ValidateTestProperty(const std::string & xml_element,const TestProperty & test_property)3603 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3604                                       const TestProperty& test_property) {
3605   return ValidateTestPropertyName(test_property.key(),
3606                                   GetReservedAttributesForElement(xml_element));
3607 }
3608 
3609 // Clears the object.
Clear()3610 void TestResult::Clear() {
3611   test_part_results_.clear();
3612   test_properties_.clear();
3613   death_test_count_ = 0;
3614   elapsed_time_ = 0;
3615 }
3616 
3617 // Returns true iff the test failed.
Failed() const3618 bool TestResult::Failed() const {
3619   for (int i = 0; i < total_part_count(); ++i) {
3620     if (GetTestPartResult(i).failed())
3621       return true;
3622   }
3623   return false;
3624 }
3625 
3626 // Returns true iff the test part fatally failed.
TestPartFatallyFailed(const TestPartResult & result)3627 static bool TestPartFatallyFailed(const TestPartResult& result) {
3628   return result.fatally_failed();
3629 }
3630 
3631 // Returns true iff the test fatally failed.
HasFatalFailure() const3632 bool TestResult::HasFatalFailure() const {
3633   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3634 }
3635 
3636 // Returns true iff the test part non-fatally failed.
TestPartNonfatallyFailed(const TestPartResult & result)3637 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3638   return result.nonfatally_failed();
3639 }
3640 
3641 // Returns true iff the test has a non-fatal failure.
HasNonfatalFailure() const3642 bool TestResult::HasNonfatalFailure() const {
3643   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3644 }
3645 
3646 // Gets the number of all test parts.  This is the sum of the number
3647 // of successful test parts and the number of failed test parts.
total_part_count() const3648 int TestResult::total_part_count() const {
3649   return static_cast<int>(test_part_results_.size());
3650 }
3651 
3652 // Returns the number of the test properties.
test_property_count() const3653 int TestResult::test_property_count() const {
3654   return static_cast<int>(test_properties_.size());
3655 }
3656 
3657 // class Test
3658 
3659 // Creates a Test object.
3660 
3661 // The c'tor saves the states of all flags.
Test()3662 Test::Test()
3663     : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3664 }
3665 
3666 // The d'tor restores the states of all flags.  The actual work is
3667 // done by the d'tor of the gtest_flag_saver_ field, and thus not
3668 // visible here.
~Test()3669 Test::~Test() {
3670 }
3671 
3672 // Sets up the test fixture.
3673 //
3674 // A sub-class may override this.
SetUp()3675 void Test::SetUp() {
3676 }
3677 
3678 // Tears down the test fixture.
3679 //
3680 // A sub-class may override this.
TearDown()3681 void Test::TearDown() {
3682 }
3683 
3684 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,const std::string & value)3685 void Test::RecordProperty(const std::string& key, const std::string& value) {
3686   UnitTest::GetInstance()->RecordProperty(key, value);
3687 }
3688 
3689 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,int value)3690 void Test::RecordProperty(const std::string& key, int value) {
3691   Message value_message;
3692   value_message << value;
3693   RecordProperty(key, value_message.GetString().c_str());
3694 }
3695 
3696 namespace internal {
3697 
ReportFailureInUnknownLocation(TestPartResult::Type result_type,const std::string & message)3698 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3699                                     const std::string& message) {
3700   // This function is a friend of UnitTest and as such has access to
3701   // AddTestPartResult.
3702   UnitTest::GetInstance()->AddTestPartResult(
3703       result_type,
3704       NULL,  // No info about the source file where the exception occurred.
3705       -1,    // We have no info on which line caused the exception.
3706       message,
3707       "");   // No stack trace, either.
3708 }
3709 
3710 }  // namespace internal
3711 
3712 // Google Test requires all tests in the same test case to use the same test
3713 // fixture class.  This function checks if the current test has the
3714 // same fixture class as the first test in the current test case.  If
3715 // yes, it returns true; otherwise it generates a Google Test failure and
3716 // returns false.
HasSameFixtureClass()3717 bool Test::HasSameFixtureClass() {
3718   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3719   const TestCase* const test_case = impl->current_test_case();
3720 
3721   // Info about the first test in the current test case.
3722   const TestInfo* const first_test_info = test_case->test_info_list()[0];
3723   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3724   const char* const first_test_name = first_test_info->name();
3725 
3726   // Info about the current test.
3727   const TestInfo* const this_test_info = impl->current_test_info();
3728   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3729   const char* const this_test_name = this_test_info->name();
3730 
3731   if (this_fixture_id != first_fixture_id) {
3732     // Is the first test defined using TEST?
3733     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3734     // Is this test defined using TEST?
3735     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3736 
3737     if (first_is_TEST || this_is_TEST) {
3738       // Both TEST and TEST_F appear in same test case, which is incorrect.
3739       // Tell the user how to fix this.
3740 
3741       // Gets the name of the TEST and the name of the TEST_F.  Note
3742       // that first_is_TEST and this_is_TEST cannot both be true, as
3743       // the fixture IDs are different for the two tests.
3744       const char* const TEST_name =
3745           first_is_TEST ? first_test_name : this_test_name;
3746       const char* const TEST_F_name =
3747           first_is_TEST ? this_test_name : first_test_name;
3748 
3749       ADD_FAILURE()
3750           << "All tests in the same test case must use the same test fixture\n"
3751           << "class, so mixing TEST_F and TEST in the same test case is\n"
3752           << "illegal.  In test case " << this_test_info->test_case_name()
3753           << ",\n"
3754           << "test " << TEST_F_name << " is defined using TEST_F but\n"
3755           << "test " << TEST_name << " is defined using TEST.  You probably\n"
3756           << "want to change the TEST to TEST_F or move it to another test\n"
3757           << "case.";
3758     } else {
3759       // Two fixture classes with the same name appear in two different
3760       // namespaces, which is not allowed. Tell the user how to fix this.
3761       ADD_FAILURE()
3762           << "All tests in the same test case must use the same test fixture\n"
3763           << "class.  However, in test case "
3764           << this_test_info->test_case_name() << ",\n"
3765           << "you defined test " << first_test_name
3766           << " and test " << this_test_name << "\n"
3767           << "using two different test fixture classes.  This can happen if\n"
3768           << "the two classes are from different namespaces or translation\n"
3769           << "units and have the same name.  You should probably rename one\n"
3770           << "of the classes to put the tests into different test cases.";
3771     }
3772     return false;
3773   }
3774 
3775   return true;
3776 }
3777 
3778 #if GTEST_HAS_SEH
3779 
3780 // Adds an "exception thrown" fatal failure to the current test.  This
3781 // function returns its result via an output parameter pointer because VC++
3782 // prohibits creation of objects with destructors on stack in functions
3783 // using __try (see error C2712).
FormatSehExceptionMessage(DWORD exception_code,const char * location)3784 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3785                                               const char* location) {
3786   Message message;
3787   message << "SEH exception with code 0x" << std::setbase(16) <<
3788     exception_code << std::setbase(10) << " thrown in " << location << ".";
3789 
3790   return new std::string(message.GetString());
3791 }
3792 
3793 #endif  // GTEST_HAS_SEH
3794 
3795 namespace internal {
3796 
3797 #if GTEST_HAS_EXCEPTIONS
3798 
3799 // Adds an "exception thrown" fatal failure to the current test.
FormatCxxExceptionMessage(const char * description,const char * location)3800 static std::string FormatCxxExceptionMessage(const char* description,
3801                                              const char* location) {
3802   Message message;
3803   if (description != NULL) {
3804     message << "C++ exception with description \"" << description << "\"";
3805   } else {
3806     message << "Unknown C++ exception";
3807   }
3808   message << " thrown in " << location << ".";
3809 
3810   return message.GetString();
3811 }
3812 
3813 static std::string PrintTestPartResultToString(
3814     const TestPartResult& test_part_result);
3815 
GoogleTestFailureException(const TestPartResult & failure)3816 GoogleTestFailureException::GoogleTestFailureException(
3817     const TestPartResult& failure)
3818     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3819 
3820 #endif  // GTEST_HAS_EXCEPTIONS
3821 
3822 // We put these helper functions in the internal namespace as IBM's xlC
3823 // compiler rejects the code if they were declared static.
3824 
3825 // Runs the given method and handles SEH exceptions it throws, when
3826 // SEH is supported; returns the 0-value for type Result in case of an
3827 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
3828 // exceptions in the same function.  Therefore, we provide a separate
3829 // wrapper function for handling SEH exceptions.)
3830 template <class T, typename Result>
HandleSehExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3831 Result HandleSehExceptionsInMethodIfSupported(
3832     T* object, Result (T::*method)(), const char* location) {
3833 #if GTEST_HAS_SEH
3834   __try {
3835     return (object->*method)();
3836   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
3837       GetExceptionCode())) {
3838     // We create the exception message on the heap because VC++ prohibits
3839     // creation of objects with destructors on stack in functions using __try
3840     // (see error C2712).
3841     std::string* exception_message = FormatSehExceptionMessage(
3842         GetExceptionCode(), location);
3843     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3844                                              *exception_message);
3845     delete exception_message;
3846     return static_cast<Result>(0);
3847   }
3848 #else
3849   (void)location;
3850   return (object->*method)();
3851 #endif  // GTEST_HAS_SEH
3852 }
3853 
3854 // Runs the given method and catches and reports C++ and/or SEH-style
3855 // exceptions, if they are supported; returns the 0-value for type
3856 // Result in case of an SEH exception.
3857 template <class T, typename Result>
HandleExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3858 Result HandleExceptionsInMethodIfSupported(
3859     T* object, Result (T::*method)(), const char* location) {
3860   // NOTE: The user code can affect the way in which Google Test handles
3861   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3862   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3863   // after the exception is caught and either report or re-throw the
3864   // exception based on the flag's value:
3865   //
3866   // try {
3867   //   // Perform the test method.
3868   // } catch (...) {
3869   //   if (GTEST_FLAG(catch_exceptions))
3870   //     // Report the exception as failure.
3871   //   else
3872   //     throw;  // Re-throws the original exception.
3873   // }
3874   //
3875   // However, the purpose of this flag is to allow the program to drop into
3876   // the debugger when the exception is thrown. On most platforms, once the
3877   // control enters the catch block, the exception origin information is
3878   // lost and the debugger will stop the program at the point of the
3879   // re-throw in this function -- instead of at the point of the original
3880   // throw statement in the code under test.  For this reason, we perform
3881   // the check early, sacrificing the ability to affect Google Test's
3882   // exception handling in the method where the exception is thrown.
3883   if (internal::GetUnitTestImpl()->catch_exceptions()) {
3884 #if GTEST_HAS_EXCEPTIONS
3885     try {
3886       return HandleSehExceptionsInMethodIfSupported(object, method, location);
3887     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
3888       // This exception type can only be thrown by a failed Google
3889       // Test assertion with the intention of letting another testing
3890       // framework catch it.  Therefore we just re-throw it.
3891       throw;
3892     } catch (const std::exception& e) {  // NOLINT
3893       internal::ReportFailureInUnknownLocation(
3894           TestPartResult::kFatalFailure,
3895           FormatCxxExceptionMessage(e.what(), location));
3896     } catch (...) {  // NOLINT
3897       internal::ReportFailureInUnknownLocation(
3898           TestPartResult::kFatalFailure,
3899           FormatCxxExceptionMessage(NULL, location));
3900     }
3901     return static_cast<Result>(0);
3902 #else
3903     return HandleSehExceptionsInMethodIfSupported(object, method, location);
3904 #endif  // GTEST_HAS_EXCEPTIONS
3905   } else {
3906     return (object->*method)();
3907   }
3908 }
3909 
3910 }  // namespace internal
3911 
3912 // Runs the test and updates the test result.
Run()3913 void Test::Run() {
3914   if (!HasSameFixtureClass()) return;
3915 
3916   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3917   impl->os_stack_trace_getter()->UponLeavingGTest();
3918   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3919   // We will run the test only if SetUp() was successful.
3920   if (!HasFatalFailure()) {
3921     impl->os_stack_trace_getter()->UponLeavingGTest();
3922     internal::HandleExceptionsInMethodIfSupported(
3923         this, &Test::TestBody, "the test body");
3924   }
3925 
3926   // However, we want to clean up as much as possible.  Hence we will
3927   // always call TearDown(), even if SetUp() or the test body has
3928   // failed.
3929   impl->os_stack_trace_getter()->UponLeavingGTest();
3930   internal::HandleExceptionsInMethodIfSupported(
3931       this, &Test::TearDown, "TearDown()");
3932 }
3933 
3934 // Returns true iff the current test has a fatal failure.
HasFatalFailure()3935 bool Test::HasFatalFailure() {
3936   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3937 }
3938 
3939 // Returns true iff the current test has a non-fatal failure.
HasNonfatalFailure()3940 bool Test::HasNonfatalFailure() {
3941   return internal::GetUnitTestImpl()->current_test_result()->
3942       HasNonfatalFailure();
3943 }
3944 
3945 // class TestInfo
3946 
3947 // Constructs a TestInfo object. It assumes ownership of the test factory
3948 // 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)3949 TestInfo::TestInfo(const std::string& a_test_case_name,
3950                    const std::string& a_name,
3951                    const char* a_type_param,
3952                    const char* a_value_param,
3953                    internal::CodeLocation a_code_location,
3954                    internal::TypeId fixture_class_id,
3955                    internal::TestFactoryBase* factory)
3956     : test_case_name_(a_test_case_name),
3957       name_(a_name),
3958       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3959       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3960       location_(a_code_location),
3961       fixture_class_id_(fixture_class_id),
3962       should_run_(false),
3963       is_disabled_(false),
3964       matches_filter_(false),
3965       factory_(factory),
3966       result_() {}
3967 
3968 // Destructs a TestInfo object.
~TestInfo()3969 TestInfo::~TestInfo() { delete factory_; }
3970 
3971 namespace internal {
3972 
3973 // Creates a new TestInfo object and registers it with Google Test;
3974 // returns the created object.
3975 //
3976 // Arguments:
3977 //
3978 //   test_case_name:   name of the test case
3979 //   name:             name of the test
3980 //   type_param:       the name of the test's type parameter, or NULL if
3981 //                     this is not a typed or a type-parameterized test.
3982 //   value_param:      text representation of the test's value parameter,
3983 //                     or NULL if this is not a value-parameterized test.
3984 //   code_location:    code location where the test is defined
3985 //   fixture_class_id: ID of the test fixture class
3986 //   set_up_tc:        pointer to the function that sets up the test case
3987 //   tear_down_tc:     pointer to the function that tears down the test case
3988 //   factory:          pointer to the factory that creates a test object.
3989 //                     The newly created TestInfo instance will assume
3990 //                     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)3991 TestInfo* MakeAndRegisterTestInfo(
3992     const char* test_case_name,
3993     const char* name,
3994     const char* type_param,
3995     const char* value_param,
3996     CodeLocation code_location,
3997     TypeId fixture_class_id,
3998     SetUpTestCaseFunc set_up_tc,
3999     TearDownTestCaseFunc tear_down_tc,
4000     TestFactoryBase* factory) {
4001   TestInfo* const test_info =
4002       new TestInfo(test_case_name, name, type_param, value_param,
4003                    code_location, fixture_class_id, factory);
4004   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4005   return test_info;
4006 }
4007 
4008 #if GTEST_HAS_PARAM_TEST
ReportInvalidTestCaseType(const char * test_case_name,CodeLocation code_location)4009 void ReportInvalidTestCaseType(const char* test_case_name,
4010                                CodeLocation code_location) {
4011   Message errors;
4012   errors
4013       << "Attempted redefinition of test case " << test_case_name << ".\n"
4014       << "All tests in the same test case must use the same test fixture\n"
4015       << "class.  However, in test case " << test_case_name << ", you tried\n"
4016       << "to define a test using a fixture class different from the one\n"
4017       << "used earlier. This can happen if the two fixture classes are\n"
4018       << "from different namespaces and have the same name. You should\n"
4019       << "probably rename one of the classes to put the tests into different\n"
4020       << "test cases.";
4021 
4022   fprintf(stderr, "%s %s",
4023           FormatFileLocation(code_location.file.c_str(),
4024                              code_location.line).c_str(),
4025           errors.GetString().c_str());
4026 }
4027 #endif  // GTEST_HAS_PARAM_TEST
4028 
4029 }  // namespace internal
4030 
4031 namespace {
4032 
4033 // A predicate that checks the test name of a TestInfo against a known
4034 // value.
4035 //
4036 // This is used for implementation of the TestCase class only.  We put
4037 // it in the anonymous namespace to prevent polluting the outer
4038 // namespace.
4039 //
4040 // TestNameIs is copyable.
4041 class TestNameIs {
4042  public:
4043   // Constructor.
4044   //
4045   // TestNameIs has NO default constructor.
TestNameIs(const char * name)4046   explicit TestNameIs(const char* name)
4047       : name_(name) {}
4048 
4049   // Returns true iff the test name of test_info matches name_.
operator ()(const TestInfo * test_info) const4050   bool operator()(const TestInfo * test_info) const {
4051     // Next 2 lines are to avoid ICPC warning #177 functions operator() never
4052     // used.
4053     bool res = false;
4054     res = &TestNameIs::operator();
4055     return test_info && test_info->name() == name_;
4056   }
4057 
4058  private:
4059   std::string name_;
4060 };
4061 
4062 }  // namespace
4063 
4064 namespace internal {
4065 
4066 // This method expands all parameterized tests registered with macros TEST_P
4067 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
4068 // This will be done just once during the program runtime.
RegisterParameterizedTests()4069 void UnitTestImpl::RegisterParameterizedTests() {
4070 #if GTEST_HAS_PARAM_TEST
4071   if (!parameterized_tests_registered_) {
4072     parameterized_test_registry_.RegisterTests();
4073     parameterized_tests_registered_ = true;
4074   }
4075 #endif
4076 }
4077 
4078 }  // namespace internal
4079 
4080 // Creates the test object, runs it, records its result, and then
4081 // deletes it.
Run()4082 void TestInfo::Run() {
4083   if (!should_run_) return;
4084 
4085   // Tells UnitTest where to store test result.
4086   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4087   impl->set_current_test_info(this);
4088 
4089   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4090 
4091   // Notifies the unit test event listeners that a test is about to start.
4092   repeater->OnTestStart(*this);
4093 
4094   const TimeInMillis start = internal::GetTimeInMillis();
4095 
4096   impl->os_stack_trace_getter()->UponLeavingGTest();
4097 
4098   // Creates the test object.
4099   Test* const test = internal::HandleExceptionsInMethodIfSupported(
4100       factory_, &internal::TestFactoryBase::CreateTest,
4101       "the test fixture's constructor");
4102 
4103   // Runs the test only if the test object was created and its
4104   // constructor didn't generate a fatal failure.
4105   if ((test != NULL) && !Test::HasFatalFailure()) {
4106     // This doesn't throw as all user code that can throw are wrapped into
4107     // exception handling code.
4108     test->Run();
4109   }
4110 
4111   // Deletes the test object.
4112   impl->os_stack_trace_getter()->UponLeavingGTest();
4113   internal::HandleExceptionsInMethodIfSupported(
4114       test, &Test::DeleteSelf_, "the test fixture's destructor");
4115 
4116   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4117 
4118   // Notifies the unit test event listener that a test has just finished.
4119   repeater->OnTestEnd(*this);
4120 
4121   // Tells UnitTest to stop associating assertion results to this
4122   // test.
4123   impl->set_current_test_info(NULL);
4124 }
4125 
4126 // class TestCase
4127 
4128 // Gets the number of successful tests in this test case.
successful_test_count() const4129 int TestCase::successful_test_count() const {
4130   return CountIf(test_info_list_, TestPassed);
4131 }
4132 
4133 // Gets the number of failed tests in this test case.
failed_test_count() const4134 int TestCase::failed_test_count() const {
4135   return CountIf(test_info_list_, TestFailed);
4136 }
4137 
4138 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const4139 int TestCase::reportable_disabled_test_count() const {
4140   return CountIf(test_info_list_, TestReportableDisabled);
4141 }
4142 
4143 // Gets the number of disabled tests in this test case.
disabled_test_count() const4144 int TestCase::disabled_test_count() const {
4145   return CountIf(test_info_list_, TestDisabled);
4146 }
4147 
4148 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const4149 int TestCase::reportable_test_count() const {
4150   return CountIf(test_info_list_, TestReportable);
4151 }
4152 
4153 // Get the number of tests in this test case that should run.
test_to_run_count() const4154 int TestCase::test_to_run_count() const {
4155   return CountIf(test_info_list_, ShouldRunTest);
4156 }
4157 
4158 // Gets the number of all tests.
total_test_count() const4159 int TestCase::total_test_count() const {
4160   return static_cast<int>(test_info_list_.size());
4161 }
4162 
4163 // Creates a TestCase with the given name.
4164 //
4165 // Arguments:
4166 //
4167 //   name:         name of the test case
4168 //   a_type_param: the name of the test case's type parameter, or NULL if
4169 //                 this is not a typed or a type-parameterized test case.
4170 //   set_up_tc:    pointer to the function that sets up the test case
4171 //   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)4172 TestCase::TestCase(const char* a_name, const char* a_type_param,
4173                    Test::SetUpTestCaseFunc set_up_tc,
4174                    Test::TearDownTestCaseFunc tear_down_tc)
4175     : name_(a_name),
4176       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
4177       set_up_tc_(set_up_tc),
4178       tear_down_tc_(tear_down_tc),
4179       should_run_(false),
4180       elapsed_time_(0) {
4181 }
4182 
4183 // Destructor of TestCase.
~TestCase()4184 TestCase::~TestCase() {
4185   // Deletes every Test in the collection.
4186   ForEach(test_info_list_, internal::Delete<TestInfo>);
4187 }
4188 
4189 // Returns the i-th test among all the tests. i can range from 0 to
4190 // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const4191 const TestInfo* TestCase::GetTestInfo(int i) const {
4192   const int index = GetElementOr(test_indices_, i, -1);
4193   return index < 0 ? NULL : test_info_list_[index];
4194 }
4195 
4196 // Returns the i-th test among all the tests. i can range from 0 to
4197 // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)4198 TestInfo* TestCase::GetMutableTestInfo(int i) {
4199   const int index = GetElementOr(test_indices_, i, -1);
4200   return index < 0 ? NULL : test_info_list_[index];
4201 }
4202 
4203 // Adds a test to this test case.  Will delete the test upon
4204 // destruction of the TestCase object.
AddTestInfo(TestInfo * test_info)4205 void TestCase::AddTestInfo(TestInfo * test_info) {
4206   test_info_list_.push_back(test_info);
4207   test_indices_.push_back(static_cast<int>(test_indices_.size()));
4208 }
4209 
4210 // Runs every test in this TestCase.
Run()4211 void TestCase::Run() {
4212   if (!should_run_) return;
4213 
4214   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4215   impl->set_current_test_case(this);
4216 
4217   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4218 
4219   repeater->OnTestCaseStart(*this);
4220   impl->os_stack_trace_getter()->UponLeavingGTest();
4221   internal::HandleExceptionsInMethodIfSupported(
4222       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
4223 
4224   const internal::TimeInMillis start = internal::GetTimeInMillis();
4225   for (int i = 0; i < total_test_count(); i++) {
4226     GetMutableTestInfo(i)->Run();
4227   }
4228   elapsed_time_ = internal::GetTimeInMillis() - start;
4229 
4230   impl->os_stack_trace_getter()->UponLeavingGTest();
4231   internal::HandleExceptionsInMethodIfSupported(
4232       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
4233 
4234   repeater->OnTestCaseEnd(*this);
4235   impl->set_current_test_case(NULL);
4236 }
4237 
4238 // Clears the results of all tests in this test case.
ClearResult()4239 void TestCase::ClearResult() {
4240   ad_hoc_test_result_.Clear();
4241   ForEach(test_info_list_, TestInfo::ClearTestResult);
4242 }
4243 
4244 // Shuffles the tests in this test case.
ShuffleTests(internal::Random * random)4245 void TestCase::ShuffleTests(internal::Random* random) {
4246   Shuffle(random, &test_indices_);
4247 }
4248 
4249 // Restores the test order to before the first shuffle.
UnshuffleTests()4250 void TestCase::UnshuffleTests() {
4251   for (size_t i = 0; i < test_indices_.size(); i++) {
4252     test_indices_[i] = static_cast<int>(i);
4253   }
4254 }
4255 
4256 // Formats a countable noun.  Depending on its quantity, either the
4257 // singular form or the plural form is used. e.g.
4258 //
4259 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4260 // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)4261 static std::string FormatCountableNoun(int count,
4262                                        const char * singular_form,
4263                                        const char * plural_form) {
4264   return internal::StreamableToString(count) + " " +
4265       (count == 1 ? singular_form : plural_form);
4266 }
4267 
4268 // Formats the count of tests.
FormatTestCount(int test_count)4269 static std::string FormatTestCount(int test_count) {
4270   return FormatCountableNoun(test_count, "test", "tests");
4271 }
4272 
4273 // Formats the count of test cases.
FormatTestCaseCount(int test_case_count)4274 static std::string FormatTestCaseCount(int test_case_count) {
4275   return FormatCountableNoun(test_case_count, "test case", "test cases");
4276 }
4277 
4278 // Converts a TestPartResult::Type enum to human-friendly string
4279 // representation.  Both kNonFatalFailure and kFatalFailure are translated
4280 // to "Failure", as the user usually doesn't care about the difference
4281 // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)4282 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4283   switch (type) {
4284     case TestPartResult::kSuccess:
4285       return "Success";
4286 
4287     case TestPartResult::kNonFatalFailure:
4288     case TestPartResult::kFatalFailure:
4289 #ifdef _MSC_VER
4290       return "error: ";
4291 #else
4292       return "Failure\n";
4293 #endif
4294     default:
4295       return "Unknown result type";
4296   }
4297 }
4298 
4299 namespace internal {
4300 
4301 // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)4302 static std::string PrintTestPartResultToString(
4303     const TestPartResult& test_part_result) {
4304   return (Message()
4305           << internal::FormatFileLocation(test_part_result.file_name(),
4306                                           test_part_result.line_number())
4307           << " " << TestPartResultTypeToString(test_part_result.type())
4308           << test_part_result.message()).GetString();
4309 }
4310 
4311 // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)4312 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4313   const std::string& result =
4314       PrintTestPartResultToString(test_part_result);
4315   printf("%s\n", result.c_str());
4316   fflush(stdout);
4317   // If the test program runs in Visual Studio or a debugger, the
4318   // following statements add the test part result message to the Output
4319   // window such that the user can double-click on it to jump to the
4320   // corresponding source code location; otherwise they do nothing.
4321 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4322   // We don't call OutputDebugString*() on Windows Mobile, as printing
4323   // to stdout is done by OutputDebugString() there already - we don't
4324   // want the same message printed twice.
4325   ::OutputDebugStringA(result.c_str());
4326   ::OutputDebugStringA("\n");
4327 #endif
4328 }
4329 
4330 // class PrettyUnitTestResultPrinter
4331 
4332 enum GTestColor {
4333   COLOR_DEFAULT,
4334   COLOR_RED,
4335   COLOR_GREEN,
4336   COLOR_YELLOW
4337 };
4338 
4339 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4340     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4341 
4342 // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)4343 WORD GetColorAttribute(GTestColor color) {
4344   switch (color) {
4345     case COLOR_RED:    return FOREGROUND_RED;
4346     case COLOR_GREEN:  return FOREGROUND_GREEN;
4347     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4348     default:           return 0;
4349   }
4350 }
4351 
4352 #else
4353 
4354 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
4355 // an invalid input.
GetAnsiColorCode(GTestColor color)4356 const char* GetAnsiColorCode(GTestColor color) {
4357   switch (color) {
4358     case COLOR_RED:     return "1";
4359     case COLOR_GREEN:   return "2";
4360     case COLOR_YELLOW:  return "3";
4361     default:            return NULL;
4362   };
4363 }
4364 
4365 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4366 
4367 // Returns true iff Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)4368 bool ShouldUseColor(bool stdout_is_tty) {
4369   const char* const gtest_color = GTEST_FLAG(color).c_str();
4370 
4371   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4372 #if GTEST_OS_WINDOWS
4373     // On Windows the TERM variable is usually not set, but the
4374     // console there does support colors.
4375     return stdout_is_tty;
4376 #else
4377     // On non-Windows platforms, we rely on the TERM variable.
4378     const char* const term = posix::GetEnv("TERM");
4379     const bool term_supports_color =
4380         String::CStringEquals(term, "xterm") ||
4381         String::CStringEquals(term, "xterm-color") ||
4382         String::CStringEquals(term, "xterm-256color") ||
4383         String::CStringEquals(term, "screen") ||
4384         String::CStringEquals(term, "screen-256color") ||
4385         String::CStringEquals(term, "tmux") ||
4386         String::CStringEquals(term, "tmux-256color") ||
4387         String::CStringEquals(term, "rxvt-unicode") ||
4388         String::CStringEquals(term, "rxvt-unicode-256color") ||
4389         String::CStringEquals(term, "linux") ||
4390         String::CStringEquals(term, "cygwin");
4391     return stdout_is_tty && term_supports_color;
4392 #endif  // GTEST_OS_WINDOWS
4393   }
4394 
4395   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4396       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4397       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4398       String::CStringEquals(gtest_color, "1");
4399   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
4400   // value is neither one of these nor "auto", we treat it as "no" to
4401   // be conservative.
4402 }
4403 
4404 // Helpers for printing colored strings to stdout. Note that on Windows, we
4405 // cannot simply emit special characters and have the terminal change colors.
4406 // This routine must actually emit the characters rather than return a string
4407 // that would be colored when printed, as can be done on Linux.
ColoredPrintf(GTestColor color,const char * fmt,...)4408 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4409   va_list args;
4410   va_start(args, fmt);
4411 
4412 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
4413     GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4414   const bool use_color = AlwaysFalse();
4415 #else
4416   static const bool in_color_mode =
4417       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4418   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4419 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4420   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4421 
4422   if (!use_color) {
4423     vprintf(fmt, args);
4424     va_end(args);
4425     return;
4426   }
4427 
4428 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4429     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4430   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4431 
4432   // Gets the current text color.
4433   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4434   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4435   const WORD old_color_attrs = buffer_info.wAttributes;
4436 
4437   // We need to flush the stream buffers into the console before each
4438   // SetConsoleTextAttribute call lest it affect the text that is already
4439   // printed but has not yet reached the console.
4440   fflush(stdout);
4441   SetConsoleTextAttribute(stdout_handle,
4442                           GetColorAttribute(color) | FOREGROUND_INTENSITY);
4443   vprintf(fmt, args);
4444 
4445   fflush(stdout);
4446   // Restores the text color.
4447   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4448 #else
4449   printf("\033[0;3%sm", GetAnsiColorCode(color));
4450   vprintf(fmt, args);
4451   printf("\033[m");  // Resets the terminal to default.
4452 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4453   va_end(args);
4454 }
4455 
4456 // Text printed in Google Test's text output and --gunit_list_tests
4457 // output to label the type parameter and value parameter for a test.
4458 static const char kTypeParamLabel[] = "TypeParam";
4459 static const char kValueParamLabel[] = "GetParam()";
4460 
PrintFullTestCommentIfPresent(const TestInfo & test_info)4461 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4462   const char* const type_param = test_info.type_param();
4463   const char* const value_param = test_info.value_param();
4464 
4465   if (type_param != NULL || value_param != NULL) {
4466     printf(", where ");
4467     if (type_param != NULL) {
4468       printf("%s = %s", kTypeParamLabel, type_param);
4469       if (value_param != NULL)
4470         printf(" and ");
4471     }
4472     if (value_param != NULL) {
4473       printf("%s = %s", kValueParamLabel, value_param);
4474     }
4475   }
4476 }
4477 
4478 // This class implements the TestEventListener interface.
4479 //
4480 // Class PrettyUnitTestResultPrinter is copyable.
4481 class PrettyUnitTestResultPrinter : public TestEventListener {
4482  public:
PrettyUnitTestResultPrinter()4483   PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_case,const char * test)4484   static void PrintTestName(const char * test_case, const char * test) {
4485     printf("%s.%s", test_case, test);
4486   }
4487 
4488   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)4489   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4490   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4491   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
OnEnvironmentsSetUpEnd(const UnitTest &)4492   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4493   virtual void OnTestCaseStart(const TestCase& test_case);
4494   virtual void OnTestStart(const TestInfo& test_info);
4495   virtual void OnTestPartResult(const TestPartResult& result);
4496   virtual void OnTestEnd(const TestInfo& test_info);
4497   virtual void OnTestCaseEnd(const TestCase& test_case);
4498   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
OnEnvironmentsTearDownEnd(const UnitTest &)4499   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4500   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
OnTestProgramEnd(const UnitTest &)4501   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4502 
4503  private:
4504   static void PrintFailedTests(const UnitTest& unit_test);
4505 };
4506 
4507   // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)4508 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4509     const UnitTest& unit_test, int iteration) {
4510   if (GTEST_FLAG(repeat) != 1)
4511     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4512 
4513   const char* const filter = GTEST_FLAG(filter).c_str();
4514 
4515   // Prints the filter if it's not *.  This reminds the user that some
4516   // tests may be skipped.
4517   if (!String::CStringEquals(filter, kUniversalFilter)) {
4518     ColoredPrintf(COLOR_YELLOW,
4519                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
4520   }
4521 
4522   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4523     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4524     ColoredPrintf(COLOR_YELLOW,
4525                   "Note: This is test shard %d of %s.\n",
4526                   static_cast<int>(shard_index) + 1,
4527                   internal::posix::GetEnv(kTestTotalShards));
4528   }
4529 
4530   if (GTEST_FLAG(shuffle)) {
4531     ColoredPrintf(COLOR_YELLOW,
4532                   "Note: Randomizing tests' orders with a seed of %d .\n",
4533                   unit_test.random_seed());
4534   }
4535 
4536   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4537   printf("Running %s from %s.\n",
4538          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4539          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4540   fflush(stdout);
4541 }
4542 
OnEnvironmentsSetUpStart(const UnitTest &)4543 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4544     const UnitTest& /*unit_test*/) {
4545   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4546   printf("Global test environment set-up.\n");
4547   fflush(stdout);
4548 }
4549 
OnTestCaseStart(const TestCase & test_case)4550 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4551   const std::string counts =
4552       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4553   ColoredPrintf(COLOR_GREEN, "[----------] ");
4554   printf("%s from %s", counts.c_str(), test_case.name());
4555   if (test_case.type_param() == NULL) {
4556     printf("\n");
4557   } else {
4558     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4559   }
4560   fflush(stdout);
4561 }
4562 
OnTestStart(const TestInfo & test_info)4563 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4564   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
4565   PrintTestName(test_info.test_case_name(), test_info.name());
4566   printf("\n");
4567   fflush(stdout);
4568 }
4569 
4570 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)4571 void PrettyUnitTestResultPrinter::OnTestPartResult(
4572     const TestPartResult& result) {
4573   // If the test part succeeded, we don't need to do anything.
4574   if (result.type() == TestPartResult::kSuccess)
4575     return;
4576 
4577   // Print failure message from the assertion (e.g. expected this and got that).
4578   PrintTestPartResult(result);
4579   fflush(stdout);
4580 }
4581 
OnTestEnd(const TestInfo & test_info)4582 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4583   if (test_info.result()->Passed()) {
4584     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
4585   } else {
4586     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4587   }
4588   PrintTestName(test_info.test_case_name(), test_info.name());
4589   if (test_info.result()->Failed())
4590     PrintFullTestCommentIfPresent(test_info);
4591 
4592   if (GTEST_FLAG(print_time)) {
4593     printf(" (%s ms)\n", internal::StreamableToString(
4594            test_info.result()->elapsed_time()).c_str());
4595   } else {
4596     printf("\n");
4597   }
4598   fflush(stdout);
4599 }
4600 
OnTestCaseEnd(const TestCase & test_case)4601 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4602   if (!GTEST_FLAG(print_time)) return;
4603 
4604   const std::string counts =
4605       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4606   ColoredPrintf(COLOR_GREEN, "[----------] ");
4607   printf("%s from %s (%s ms total)\n\n",
4608          counts.c_str(), test_case.name(),
4609          internal::StreamableToString(test_case.elapsed_time()).c_str());
4610   fflush(stdout);
4611 }
4612 
OnEnvironmentsTearDownStart(const UnitTest &)4613 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4614     const UnitTest& /*unit_test*/) {
4615   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4616   printf("Global test environment tear-down\n");
4617   fflush(stdout);
4618 }
4619 
4620 // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)4621 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4622   const int failed_test_count = unit_test.failed_test_count();
4623   if (failed_test_count == 0) {
4624     return;
4625   }
4626 
4627   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4628     const TestCase& test_case = *unit_test.GetTestCase(i);
4629     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4630       continue;
4631     }
4632     for (int j = 0; j < test_case.total_test_count(); ++j) {
4633       const TestInfo& test_info = *test_case.GetTestInfo(j);
4634       if (!test_info.should_run() || test_info.result()->Passed()) {
4635         continue;
4636       }
4637       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4638       printf("%s.%s", test_case.name(), test_info.name());
4639       PrintFullTestCommentIfPresent(test_info);
4640       printf("\n");
4641     }
4642   }
4643 }
4644 
OnTestIterationEnd(const UnitTest & unit_test,int)4645 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4646                                                      int /*iteration*/) {
4647   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4648   printf("%s from %s ran.",
4649          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4650          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4651   if (GTEST_FLAG(print_time)) {
4652     printf(" (%s ms total)",
4653            internal::StreamableToString(unit_test.elapsed_time()).c_str());
4654   }
4655   printf("\n");
4656   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
4657   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4658 
4659   int num_failures = unit_test.failed_test_count();
4660   if (!unit_test.Passed()) {
4661     const int failed_test_count = unit_test.failed_test_count();
4662     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
4663     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4664     PrintFailedTests(unit_test);
4665     printf("\n%2d FAILED %s\n", num_failures,
4666                         num_failures == 1 ? "TEST" : "TESTS");
4667   }
4668 
4669   int num_disabled = unit_test.reportable_disabled_test_count();
4670   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4671     if (!num_failures) {
4672       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
4673     }
4674     ColoredPrintf(COLOR_YELLOW,
4675                   "  YOU HAVE %d DISABLED %s\n\n",
4676                   num_disabled,
4677                   num_disabled == 1 ? "TEST" : "TESTS");
4678   }
4679   // Ensure that Google Test output is printed before, e.g., heapchecker output.
4680   fflush(stdout);
4681 }
4682 
4683 // End PrettyUnitTestResultPrinter
4684 
4685 // class TestEventRepeater
4686 //
4687 // This class forwards events to other event listeners.
4688 class TestEventRepeater : public TestEventListener {
4689  public:
TestEventRepeater()4690   TestEventRepeater() : forwarding_enabled_(true) {}
4691   virtual ~TestEventRepeater();
4692   void Append(TestEventListener *listener);
4693   TestEventListener* Release(TestEventListener* listener);
4694 
4695   // Controls whether events will be forwarded to listeners_. Set to false
4696   // in death test child processes.
forwarding_enabled() const4697   bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)4698   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4699 
4700   virtual void OnTestProgramStart(const UnitTest& unit_test);
4701   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4702   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4703   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4704   virtual void OnTestCaseStart(const TestCase& test_case);
4705   virtual void OnTestStart(const TestInfo& test_info);
4706   virtual void OnTestPartResult(const TestPartResult& result);
4707   virtual void OnTestEnd(const TestInfo& test_info);
4708   virtual void OnTestCaseEnd(const TestCase& test_case);
4709   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4710   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4711   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4712   virtual void OnTestProgramEnd(const UnitTest& unit_test);
4713 
4714  private:
4715   // Controls whether events will be forwarded to listeners_. Set to false
4716   // in death test child processes.
4717   bool forwarding_enabled_;
4718   // The list of listeners that receive events.
4719   std::vector<TestEventListener*> listeners_;
4720 
4721   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4722 };
4723 
~TestEventRepeater()4724 TestEventRepeater::~TestEventRepeater() {
4725   ForEach(listeners_, Delete<TestEventListener>);
4726 }
4727 
Append(TestEventListener * listener)4728 void TestEventRepeater::Append(TestEventListener *listener) {
4729   listeners_.push_back(listener);
4730 }
4731 
4732 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
Release(TestEventListener * listener)4733 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4734   for (size_t i = 0; i < listeners_.size(); ++i) {
4735     if (listeners_[i] == listener) {
4736       listeners_.erase(listeners_.begin() + i);
4737       return listener;
4738     }
4739   }
4740 
4741   return NULL;
4742 }
4743 
4744 // Since most methods are very similar, use macros to reduce boilerplate.
4745 // This defines a member that forwards the call to all listeners.
4746 #define GTEST_REPEATER_METHOD_(Name, Type) \
4747 void TestEventRepeater::Name(const Type& parameter) { \
4748   if (forwarding_enabled_) { \
4749     for (size_t i = 0; i < listeners_.size(); i++) { \
4750       listeners_[i]->Name(parameter); \
4751     } \
4752   } \
4753 }
4754 // This defines a member that forwards the call to all listeners in reverse
4755 // order.
4756 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4757 void TestEventRepeater::Name(const Type& parameter) { \
4758   if (forwarding_enabled_) { \
4759     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4760       listeners_[i]->Name(parameter); \
4761     } \
4762   } \
4763 }
4764 
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)4765 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4766 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4767 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4768 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4769 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4770 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4771 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4772 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4773 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4774 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4775 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4776 
4777 #undef GTEST_REPEATER_METHOD_
4778 #undef GTEST_REVERSE_REPEATER_METHOD_
4779 
4780 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4781                                              int iteration) {
4782   if (forwarding_enabled_) {
4783     for (size_t i = 0; i < listeners_.size(); i++) {
4784       listeners_[i]->OnTestIterationStart(unit_test, iteration);
4785     }
4786   }
4787 }
4788 
OnTestIterationEnd(const UnitTest & unit_test,int iteration)4789 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4790                                            int iteration) {
4791   if (forwarding_enabled_) {
4792     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4793       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4794     }
4795   }
4796 }
4797 
4798 // End TestEventRepeater
4799 
4800 // This class generates an XML output file.
4801 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4802  public:
4803   explicit XmlUnitTestResultPrinter(const char* output_file);
4804 
4805   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4806 
4807  private:
4808   // Is c a whitespace character that is normalized to a space character
4809   // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)4810   static bool IsNormalizableWhitespace(char c) {
4811     return c == 0x9 || c == 0xA || c == 0xD;
4812   }
4813 
4814   // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)4815   static bool IsValidXmlCharacter(char c) {
4816     return IsNormalizableWhitespace(c) || c >= 0x20;
4817   }
4818 
4819   // Returns an XML-escaped copy of the input string str.  If
4820   // is_attribute is true, the text is meant to appear as an attribute
4821   // value, and normalizable whitespace is preserved by replacing it
4822   // with character references.
4823   static std::string EscapeXml(const std::string& str, bool is_attribute);
4824 
4825   // Returns the given string with all characters invalid in XML removed.
4826   static std::string RemoveInvalidXmlCharacters(const std::string& str);
4827 
4828   // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)4829   static std::string EscapeXmlAttribute(const std::string& str) {
4830     return EscapeXml(str, true);
4831   }
4832 
4833   // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)4834   static std::string EscapeXmlText(const char* str) {
4835     return EscapeXml(str, false);
4836   }
4837 
4838   // Verifies that the given attribute belongs to the given element and
4839   // streams the attribute as XML.
4840   static void OutputXmlAttribute(std::ostream* stream,
4841                                  const std::string& element_name,
4842                                  const std::string& name,
4843                                  const std::string& value);
4844 
4845   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4846   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4847 
4848   // Streams an XML representation of a TestInfo object.
4849   static void OutputXmlTestInfo(::std::ostream* stream,
4850                                 const char* test_case_name,
4851                                 const TestInfo& test_info);
4852 
4853   // Prints an XML representation of a TestCase object
4854   static void PrintXmlTestCase(::std::ostream* stream,
4855                                const TestCase& test_case);
4856 
4857   // Prints an XML summary of unit_test to output stream out.
4858   static void PrintXmlUnitTest(::std::ostream* stream,
4859                                const UnitTest& unit_test);
4860 
4861   // Produces a string representing the test properties in a result as space
4862   // delimited XML attributes based on the property key="value" pairs.
4863   // When the std::string is not empty, it includes a space at the beginning,
4864   // to delimit this attribute from prior attributes.
4865   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4866 
4867   // The output file.
4868   const std::string output_file_;
4869 
4870   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4871 };
4872 
4873 // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)4874 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4875     : output_file_(output_file) {
4876   if (output_file_.c_str() == NULL || output_file_.empty()) {
4877     fprintf(stderr, "XML output file may not be null\n");
4878     fflush(stderr);
4879     exit(EXIT_FAILURE);
4880   }
4881 }
4882 
4883 // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)4884 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4885                                                   int /*iteration*/) {
4886   FILE* xmlout = NULL;
4887   FilePath output_file(output_file_);
4888   FilePath output_dir(output_file.RemoveFileName());
4889 
4890   if (output_dir.CreateDirectoriesRecursively()) {
4891     xmlout = posix::FOpen(output_file_.c_str(), "w");
4892   }
4893   if (xmlout == NULL) {
4894     // TODO(wan): report the reason of the failure.
4895     //
4896     // We don't do it for now as:
4897     //
4898     //   1. There is no urgent need for it.
4899     //   2. It's a bit involved to make the errno variable thread-safe on
4900     //      all three operating systems (Linux, Windows, and Mac OS).
4901     //   3. To interpret the meaning of errno in a thread-safe way,
4902     //      we need the strerror_r() function, which is not available on
4903     //      Windows.
4904     fprintf(stderr,
4905             "Unable to open file \"%s\"\n",
4906             output_file_.c_str());
4907     fflush(stderr);
4908     exit(EXIT_FAILURE);
4909   }
4910   std::stringstream stream;
4911   PrintXmlUnitTest(&stream, unit_test);
4912   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4913   fclose(xmlout);
4914 }
4915 
4916 // Returns an XML-escaped copy of the input string str.  If is_attribute
4917 // is true, the text is meant to appear as an attribute value, and
4918 // normalizable whitespace is preserved by replacing it with character
4919 // references.
4920 //
4921 // Invalid XML characters in str, if any, are stripped from the output.
4922 // It is expected that most, if not all, of the text processed by this
4923 // module will consist of ordinary English text.
4924 // If this module is ever modified to produce version 1.1 XML output,
4925 // most invalid characters can be retained using character references.
4926 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4927 // escaping scheme for invalid characters, rather than dropping them.
EscapeXml(const std::string & str,bool is_attribute)4928 std::string XmlUnitTestResultPrinter::EscapeXml(
4929     const std::string& str, bool is_attribute) {
4930   Message m;
4931 
4932   for (size_t i = 0; i < str.size(); ++i) {
4933     const char ch = str[i];
4934     switch (ch) {
4935       case '<':
4936         m << "&lt;";
4937         break;
4938       case '>':
4939         m << "&gt;";
4940         break;
4941       case '&':
4942         m << "&amp;";
4943         break;
4944       case '\'':
4945         if (is_attribute)
4946           m << "&apos;";
4947         else
4948           m << '\'';
4949         break;
4950       case '"':
4951         if (is_attribute)
4952           m << "&quot;";
4953         else
4954           m << '"';
4955         break;
4956       default:
4957         if (IsValidXmlCharacter(ch)) {
4958           if (is_attribute && IsNormalizableWhitespace(ch))
4959             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4960               << ";";
4961           else
4962             m << ch;
4963         }
4964         break;
4965     }
4966   }
4967 
4968   return m.GetString();
4969 }
4970 
4971 // Returns the given string with all characters invalid in XML removed.
4972 // Currently invalid characters are dropped from the string. An
4973 // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)4974 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4975     const std::string& str) {
4976   std::string output;
4977   output.reserve(str.size());
4978   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4979     if (IsValidXmlCharacter(*it))
4980       output.push_back(*it);
4981 
4982   return output;
4983 }
4984 
4985 // The following routines generate an XML representation of a UnitTest
4986 // object.
4987 //
4988 // This is how Google Test concepts map to the DTD:
4989 //
4990 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
4991 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
4992 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
4993 //       <failure message="...">...</failure>
4994 //       <failure message="...">...</failure>
4995 //       <failure message="...">...</failure>
4996 //                                     <-- individual assertion failures
4997 //     </testcase>
4998 //   </testsuite>
4999 // </testsuites>
5000 
5001 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)5002 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5003   ::std::stringstream ss;
5004   ss << (static_cast<double>(ms) * 1e-3);
5005   return ss.str();
5006 }
5007 
PortableLocaltime(time_t seconds,struct tm * out)5008 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5009 #if defined(_MSC_VER)
5010   return localtime_s(out, &seconds) == 0;
5011 #elif defined(__MINGW32__) || defined(__MINGW64__)
5012   // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5013   // Windows' localtime(), which has a thread-local tm buffer.
5014   struct tm* tm_ptr = localtime(&seconds);  // NOLINT
5015   if (tm_ptr == NULL)
5016     return false;
5017   *out = *tm_ptr;
5018   return true;
5019 #else
5020   return localtime_r(&seconds, out) != NULL;
5021 #endif
5022 }
5023 
5024 // Converts the given epoch time in milliseconds to a date string in the ISO
5025 // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)5026 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5027   struct tm time_struct;
5028   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5029     return "";
5030   // YYYY-MM-DDThh:mm:ss
5031   return StreamableToString(time_struct.tm_year + 1900) + "-" +
5032       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5033       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5034       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5035       String::FormatIntWidth2(time_struct.tm_min) + ":" +
5036       String::FormatIntWidth2(time_struct.tm_sec);
5037 }
5038 
5039 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)5040 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5041                                                      const char* data) {
5042   const char* segment = data;
5043   *stream << "<![CDATA[";
5044   for (;;) {
5045     const char* const next_segment = strstr(segment, "]]>");
5046     if (next_segment != NULL) {
5047       stream->write(
5048           segment, static_cast<std::streamsize>(next_segment - segment));
5049       *stream << "]]>]]&gt;<![CDATA[";
5050       segment = next_segment + strlen("]]>");
5051     } else {
5052       *stream << segment;
5053       break;
5054     }
5055   }
5056   *stream << "]]>";
5057 }
5058 
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)5059 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5060     std::ostream* stream,
5061     const std::string& element_name,
5062     const std::string& name,
5063     const std::string& value) {
5064   const std::vector<std::string>& allowed_names =
5065       GetReservedAttributesForElement(element_name);
5066 
5067   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5068                    allowed_names.end())
5069       << "Attribute " << name << " is not allowed for element <" << element_name
5070       << ">.";
5071 
5072   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5073 }
5074 
5075 // Prints an XML representation of a TestInfo object.
5076 // TODO(wan): There is also value in printing properties with the plain printer.
OutputXmlTestInfo(::std::ostream * stream,const char * test_case_name,const TestInfo & test_info)5077 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5078                                                  const char* test_case_name,
5079                                                  const TestInfo& test_info) {
5080   const TestResult& result = *test_info.result();
5081   const std::string kTestcase = "testcase";
5082 
5083   *stream << "    <testcase";
5084   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
5085 
5086   if (test_info.value_param() != NULL) {
5087     OutputXmlAttribute(stream, kTestcase, "value_param",
5088                        test_info.value_param());
5089   }
5090   if (test_info.type_param() != NULL) {
5091     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
5092   }
5093 
5094   OutputXmlAttribute(stream, kTestcase, "status",
5095                      test_info.should_run() ? "run" : "notrun");
5096   OutputXmlAttribute(stream, kTestcase, "time",
5097                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
5098   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
5099   *stream << TestPropertiesAsXmlAttributes(result);
5100 
5101   int failures = 0;
5102   for (int i = 0; i < result.total_part_count(); ++i) {
5103     const TestPartResult& part = result.GetTestPartResult(i);
5104     if (part.failed()) {
5105       if (++failures == 1) {
5106         *stream << ">\n";
5107       }
5108       const string location = internal::FormatCompilerIndependentFileLocation(
5109           part.file_name(), part.line_number());
5110       const string summary = location + "\n" + part.summary();
5111       *stream << "      <failure message=\""
5112               << EscapeXmlAttribute(summary.c_str())
5113               << "\" type=\"\">";
5114       const string detail = location + "\n" + part.message();
5115       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5116       *stream << "</failure>\n";
5117     }
5118   }
5119 
5120   if (failures == 0)
5121     *stream << " />\n";
5122   else
5123     *stream << "    </testcase>\n";
5124 }
5125 
5126 // Prints an XML representation of a TestCase object
PrintXmlTestCase(std::ostream * stream,const TestCase & test_case)5127 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
5128                                                 const TestCase& test_case) {
5129   const std::string kTestsuite = "testsuite";
5130   *stream << "  <" << kTestsuite;
5131   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
5132   OutputXmlAttribute(stream, kTestsuite, "tests",
5133                      StreamableToString(test_case.reportable_test_count()));
5134   OutputXmlAttribute(stream, kTestsuite, "failures",
5135                      StreamableToString(test_case.failed_test_count()));
5136   OutputXmlAttribute(
5137       stream, kTestsuite, "disabled",
5138       StreamableToString(test_case.reportable_disabled_test_count()));
5139   OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5140   OutputXmlAttribute(stream, kTestsuite, "time",
5141                      FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
5142   *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
5143           << ">\n";
5144 
5145   for (int i = 0; i < test_case.total_test_count(); ++i) {
5146     if (test_case.GetTestInfo(i)->is_reportable())
5147       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
5148   }
5149   *stream << "  </" << kTestsuite << ">\n";
5150 }
5151 
5152 // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)5153 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5154                                                 const UnitTest& unit_test) {
5155   const std::string kTestsuites = "testsuites";
5156 
5157   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5158   *stream << "<" << kTestsuites;
5159 
5160   OutputXmlAttribute(stream, kTestsuites, "tests",
5161                      StreamableToString(unit_test.reportable_test_count()));
5162   OutputXmlAttribute(stream, kTestsuites, "failures",
5163                      StreamableToString(unit_test.failed_test_count()));
5164   OutputXmlAttribute(
5165       stream, kTestsuites, "disabled",
5166       StreamableToString(unit_test.reportable_disabled_test_count()));
5167   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5168   OutputXmlAttribute(
5169       stream, kTestsuites, "timestamp",
5170       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5171   OutputXmlAttribute(stream, kTestsuites, "time",
5172                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5173 
5174   if (GTEST_FLAG(shuffle)) {
5175     OutputXmlAttribute(stream, kTestsuites, "random_seed",
5176                        StreamableToString(unit_test.random_seed()));
5177   }
5178 
5179   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5180 
5181   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5182   *stream << ">\n";
5183 
5184   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
5185     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
5186       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
5187   }
5188   *stream << "</" << kTestsuites << ">\n";
5189 }
5190 
5191 // Produces a string representing the test properties in a result as space
5192 // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)5193 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5194     const TestResult& result) {
5195   Message attributes;
5196   for (int i = 0; i < result.test_property_count(); ++i) {
5197     const TestProperty& property = result.GetTestProperty(i);
5198     attributes << " " << property.key() << "="
5199         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5200   }
5201   return attributes.GetString();
5202 }
5203 
5204 // End XmlUnitTestResultPrinter
5205 
5206 #if GTEST_CAN_STREAM_RESULTS_
5207 
5208 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5209 // replaces them by "%xx" where xx is their hexadecimal value. For
5210 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
5211 // in both time and space -- important as the input str may contain an
5212 // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)5213 string StreamingListener::UrlEncode(const char* str) {
5214   string result;
5215   result.reserve(strlen(str) + 1);
5216   for (char ch = *str; ch != '\0'; ch = *++str) {
5217     switch (ch) {
5218       case '%':
5219       case '=':
5220       case '&':
5221       case '\n':
5222         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5223         break;
5224       default:
5225         result.push_back(ch);
5226         break;
5227     }
5228   }
5229   return result;
5230 }
5231 
MakeConnection()5232 void StreamingListener::SocketWriter::MakeConnection() {
5233   GTEST_CHECK_(sockfd_ == -1)
5234       << "MakeConnection() can't be called when there is already a connection.";
5235 
5236   addrinfo hints;
5237   memset(&hints, 0, sizeof(hints));
5238   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
5239   hints.ai_socktype = SOCK_STREAM;
5240   addrinfo* servinfo = NULL;
5241 
5242   // Use the getaddrinfo() to get a linked list of IP addresses for
5243   // the given host name.
5244   const int error_num = getaddrinfo(
5245       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5246   if (error_num != 0) {
5247     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5248                         << gai_strerror(error_num);
5249   }
5250 
5251   // Loop through all the results and connect to the first we can.
5252   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
5253        cur_addr = cur_addr->ai_next) {
5254     sockfd_ = socket(
5255         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5256     if (sockfd_ != -1) {
5257       // Connect the client socket to the server socket.
5258       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5259         close(sockfd_);
5260         sockfd_ = -1;
5261       }
5262     }
5263   }
5264 
5265   freeaddrinfo(servinfo);  // all done with this structure
5266 
5267   if (sockfd_ == -1) {
5268     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5269                         << host_name_ << ":" << port_num_;
5270   }
5271 }
5272 
5273 // End of class Streaming Listener
5274 #endif  // GTEST_CAN_STREAM_RESULTS__
5275 
5276 // Class ScopedTrace
5277 
5278 // Pushes the given source file location and message onto a per-thread
5279 // trace stack maintained by Google Test.
ScopedTrace(const char * file,int line,const Message & message)5280 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
5281     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
5282   TraceInfo trace;
5283   trace.file = file;
5284   trace.line = line;
5285   trace.message = message.GetString();
5286 
5287   UnitTest::GetInstance()->PushGTestTrace(trace);
5288 }
5289 
5290 // Pops the info pushed by the c'tor.
~ScopedTrace()5291 ScopedTrace::~ScopedTrace()
5292     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
5293   UnitTest::GetInstance()->PopGTestTrace();
5294 }
5295 
5296 
5297 // class OsStackTraceGetter
5298 
5299 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5300     "... " GTEST_NAME_ " internal frames ...";
5301 
CurrentStackTrace(int,int)5302 string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,
5303                                              int /*skip_count*/) {
5304   return "";
5305 }
5306 
UponLeavingGTest()5307 void OsStackTraceGetter::UponLeavingGTest() {}
5308 
5309 // A helper class that creates the premature-exit file in its
5310 // constructor and deletes the file in its destructor.
5311 class ScopedPrematureExitFile {
5312  public:
ScopedPrematureExitFile(const char * premature_exit_filepath)5313   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5314       : premature_exit_filepath_(premature_exit_filepath) {
5315     // If a path to the premature-exit file is specified...
5316     if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
5317       // create the file with a single "0" character in it.  I/O
5318       // errors are ignored as there's nothing better we can do and we
5319       // don't want to fail the test because of this.
5320       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5321       fwrite("0", 1, 1, pfile);
5322       fclose(pfile);
5323     }
5324   }
5325 
~ScopedPrematureExitFile()5326   ~ScopedPrematureExitFile() {
5327     if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
5328       remove(premature_exit_filepath_);
5329     }
5330   }
5331 
5332  private:
5333   const char* const premature_exit_filepath_;
5334 
5335   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5336 };
5337 
5338 }  // namespace internal
5339 
5340 // class TestEventListeners
5341 
TestEventListeners()5342 TestEventListeners::TestEventListeners()
5343     : repeater_(new internal::TestEventRepeater()),
5344       default_result_printer_(NULL),
5345       default_xml_generator_(NULL) {
5346 }
5347 
~TestEventListeners()5348 TestEventListeners::~TestEventListeners() { delete repeater_; }
5349 
5350 // Returns the standard listener responsible for the default console
5351 // output.  Can be removed from the listeners list to shut down default
5352 // console output.  Note that removing this object from the listener list
5353 // with Release transfers its ownership to the user.
Append(TestEventListener * listener)5354 void TestEventListeners::Append(TestEventListener* listener) {
5355   repeater_->Append(listener);
5356 }
5357 
5358 // Removes the given event listener from the list and returns it.  It then
5359 // becomes the caller's responsibility to delete the listener. Returns
5360 // NULL if the listener is not found in the list.
Release(TestEventListener * listener)5361 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5362   if (listener == default_result_printer_)
5363     default_result_printer_ = NULL;
5364   else if (listener == default_xml_generator_)
5365     default_xml_generator_ = NULL;
5366   return repeater_->Release(listener);
5367 }
5368 
5369 // Returns repeater that broadcasts the TestEventListener events to all
5370 // subscribers.
repeater()5371 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5372 
5373 // Sets the default_result_printer attribute to the provided listener.
5374 // The listener is also added to the listener list and previous
5375 // default_result_printer is removed from it and deleted. The listener can
5376 // also be NULL in which case it will not be added to the list. Does
5377 // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)5378 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5379   if (default_result_printer_ != listener) {
5380     // It is an error to pass this method a listener that is already in the
5381     // list.
5382     delete Release(default_result_printer_);
5383     default_result_printer_ = listener;
5384     if (listener != NULL)
5385       Append(listener);
5386   }
5387 }
5388 
5389 // Sets the default_xml_generator attribute to the provided listener.  The
5390 // listener is also added to the listener list and previous
5391 // default_xml_generator is removed from it and deleted. The listener can
5392 // also be NULL in which case it will not be added to the list. Does
5393 // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)5394 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5395   if (default_xml_generator_ != listener) {
5396     // It is an error to pass this method a listener that is already in the
5397     // list.
5398     delete Release(default_xml_generator_);
5399     default_xml_generator_ = listener;
5400     if (listener != NULL)
5401       Append(listener);
5402   }
5403 }
5404 
5405 // Controls whether events will be forwarded by the repeater to the
5406 // listeners in the list.
EventForwardingEnabled() const5407 bool TestEventListeners::EventForwardingEnabled() const {
5408   return repeater_->forwarding_enabled();
5409 }
5410 
SuppressEventForwarding()5411 void TestEventListeners::SuppressEventForwarding() {
5412   repeater_->set_forwarding_enabled(false);
5413 }
5414 
5415 // class UnitTest
5416 
5417 // Gets the singleton UnitTest object.  The first time this method is
5418 // called, a UnitTest object is constructed and returned.  Consecutive
5419 // calls will return the same object.
5420 //
5421 // We don't protect this under mutex_ as a user is not supposed to
5422 // call this before main() starts, from which point on the return
5423 // value will never change.
GetInstance()5424 UnitTest* UnitTest::GetInstance() {
5425   // When compiled with MSVC 7.1 in optimized mode, destroying the
5426   // UnitTest object upon exiting the program messes up the exit code,
5427   // causing successful tests to appear failed.  We have to use a
5428   // different implementation in this case to bypass the compiler bug.
5429   // This implementation makes the compiler happy, at the cost of
5430   // leaking the UnitTest object.
5431 
5432   // CodeGear C++Builder insists on a public destructor for the
5433   // default implementation.  Use this implementation to keep good OO
5434   // design with private destructor.
5435 
5436 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5437   static UnitTest* const instance = new UnitTest;
5438   return instance;
5439 #else
5440   static UnitTest instance;
5441   return &instance;
5442 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5443 }
5444 
5445 // Gets the number of successful test cases.
successful_test_case_count() const5446 int UnitTest::successful_test_case_count() const {
5447   return impl()->successful_test_case_count();
5448 }
5449 
5450 // Gets the number of failed test cases.
failed_test_case_count() const5451 int UnitTest::failed_test_case_count() const {
5452   return impl()->failed_test_case_count();
5453 }
5454 
5455 // Gets the number of all test cases.
total_test_case_count() const5456 int UnitTest::total_test_case_count() const {
5457   return impl()->total_test_case_count();
5458 }
5459 
5460 // Gets the number of all test cases that contain at least one test
5461 // that should run.
test_case_to_run_count() const5462 int UnitTest::test_case_to_run_count() const {
5463   return impl()->test_case_to_run_count();
5464 }
5465 
5466 // Gets the number of successful tests.
successful_test_count() const5467 int UnitTest::successful_test_count() const {
5468   return impl()->successful_test_count();
5469 }
5470 
5471 // Gets the number of failed tests.
failed_test_count() const5472 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5473 
5474 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const5475 int UnitTest::reportable_disabled_test_count() const {
5476   return impl()->reportable_disabled_test_count();
5477 }
5478 
5479 // Gets the number of disabled tests.
disabled_test_count() const5480 int UnitTest::disabled_test_count() const {
5481   return impl()->disabled_test_count();
5482 }
5483 
5484 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const5485 int UnitTest::reportable_test_count() const {
5486   return impl()->reportable_test_count();
5487 }
5488 
5489 // Gets the number of all tests.
total_test_count() const5490 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5491 
5492 // Gets the number of tests that should run.
test_to_run_count() const5493 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5494 
5495 // Gets the time of the test program start, in ms from the start of the
5496 // UNIX epoch.
start_timestamp() const5497 internal::TimeInMillis UnitTest::start_timestamp() const {
5498     return impl()->start_timestamp();
5499 }
5500 
5501 // Gets the elapsed time, in milliseconds.
elapsed_time() const5502 internal::TimeInMillis UnitTest::elapsed_time() const {
5503   return impl()->elapsed_time();
5504 }
5505 
5506 // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const5507 bool UnitTest::Passed() const { return impl()->Passed(); }
5508 
5509 // Returns true iff the unit test failed (i.e. some test case failed
5510 // or something outside of all tests failed).
Failed() const5511 bool UnitTest::Failed() const { return impl()->Failed(); }
5512 
5513 // Gets the i-th test case among all the test cases. i can range from 0 to
5514 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const5515 const TestCase* UnitTest::GetTestCase(int i) const {
5516   return impl()->GetTestCase(i);
5517 }
5518 
5519 // Returns the TestResult containing information on test failures and
5520 // properties logged outside of individual test cases.
ad_hoc_test_result() const5521 const TestResult& UnitTest::ad_hoc_test_result() const {
5522   return *impl()->ad_hoc_test_result();
5523 }
5524 
5525 // Gets the i-th test case among all the test cases. i can range from 0 to
5526 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)5527 TestCase* UnitTest::GetMutableTestCase(int i) {
5528   return impl()->GetMutableTestCase(i);
5529 }
5530 
5531 // Returns the list of event listeners that can be used to track events
5532 // inside Google Test.
listeners()5533 TestEventListeners& UnitTest::listeners() {
5534   return *impl()->listeners();
5535 }
5536 
5537 // Registers and returns a global test environment.  When a test
5538 // program is run, all global test environments will be set-up in the
5539 // order they were registered.  After all tests in the program have
5540 // finished, all global test environments will be torn-down in the
5541 // *reverse* order they were registered.
5542 //
5543 // The UnitTest object takes ownership of the given environment.
5544 //
5545 // We don't protect this under mutex_, as we only support calling it
5546 // from the main thread.
AddEnvironment(Environment * env)5547 Environment* UnitTest::AddEnvironment(Environment* env) {
5548   if (env == NULL) {
5549     return NULL;
5550   }
5551 
5552   impl_->environments().push_back(env);
5553   return env;
5554 }
5555 
5556 // Adds a TestPartResult to the current TestResult object.  All Google Test
5557 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5558 // this to report their results.  The user code should use the
5559 // 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)5560 void UnitTest::AddTestPartResult(
5561     TestPartResult::Type result_type,
5562     const char* file_name,
5563     int line_number,
5564     const std::string& message,
5565     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
5566   Message msg;
5567   msg << message;
5568 
5569   internal::MutexLock lock(&mutex_);
5570   if (impl_->gtest_trace_stack().size() > 0) {
5571     msg << "\n" << GTEST_NAME_ << " trace:";
5572 
5573     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5574          i > 0; --i) {
5575       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5576       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5577           << " " << trace.message;
5578     }
5579   }
5580 
5581   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5582     msg << internal::kStackTraceMarker << os_stack_trace;
5583   }
5584 
5585   const TestPartResult result =
5586     TestPartResult(result_type, file_name, line_number,
5587                    msg.GetString().c_str());
5588   impl_->GetTestPartResultReporterForCurrentThread()->
5589       ReportTestPartResult(result);
5590 
5591   if (result_type != TestPartResult::kSuccess) {
5592     // gtest_break_on_failure takes precedence over
5593     // gtest_throw_on_failure.  This allows a user to set the latter
5594     // in the code (perhaps in order to use Google Test assertions
5595     // with another testing framework) and specify the former on the
5596     // command line for debugging.
5597     if (GTEST_FLAG(break_on_failure)) {
5598 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5599       // Using DebugBreak on Windows allows gtest to still break into a debugger
5600       // when a failure happens and both the --gtest_break_on_failure and
5601       // the --gtest_catch_exceptions flags are specified.
5602       DebugBreak();
5603 #else
5604       // Dereference NULL through a volatile pointer to prevent the compiler
5605       // from removing. We use this rather than abort() or __builtin_trap() for
5606       // portability: Symbian doesn't implement abort() well, and some debuggers
5607       // don't correctly trap abort().
5608       *static_cast<volatile int*>(NULL) = 1;
5609 #endif  // GTEST_OS_WINDOWS
5610     } else if (GTEST_FLAG(throw_on_failure)) {
5611 #if GTEST_HAS_EXCEPTIONS
5612       throw internal::GoogleTestFailureException(result);
5613 #else
5614       // We cannot call abort() as it generates a pop-up in debug mode
5615       // that cannot be suppressed in VC 7.1 or below.
5616       exit(1);
5617 #endif
5618     }
5619   }
5620 }
5621 
5622 // Adds a TestProperty to the current TestResult object when invoked from
5623 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5624 // from SetUpTestCase or TearDownTestCase, or to the global property set
5625 // when invoked elsewhere.  If the result already contains a property with
5626 // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)5627 void UnitTest::RecordProperty(const std::string& key,
5628                               const std::string& value) {
5629   impl_->RecordProperty(TestProperty(key, value));
5630 }
5631 
5632 // Runs all tests in this UnitTest object and prints the result.
5633 // Returns 0 if successful, or 1 otherwise.
5634 //
5635 // We don't protect this under mutex_, as we only support calling it
5636 // from the main thread.
Run()5637 int UnitTest::Run() {
5638   const bool in_death_test_child_process =
5639       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5640 
5641   // Google Test implements this protocol for catching that a test
5642   // program exits before returning control to Google Test:
5643   //
5644   //   1. Upon start, Google Test creates a file whose absolute path
5645   //      is specified by the environment variable
5646   //      TEST_PREMATURE_EXIT_FILE.
5647   //   2. When Google Test has finished its work, it deletes the file.
5648   //
5649   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5650   // running a Google-Test-based test program and check the existence
5651   // of the file at the end of the test execution to see if it has
5652   // exited prematurely.
5653 
5654   // If we are in the child process of a death test, don't
5655   // create/delete the premature exit file, as doing so is unnecessary
5656   // and will confuse the parent process.  Otherwise, create/delete
5657   // the file upon entering/leaving this function.  If the program
5658   // somehow exits before this function has a chance to return, the
5659   // premature-exit file will be left undeleted, causing a test runner
5660   // that understands the premature-exit-file protocol to report the
5661   // test as having failed.
5662   const internal::ScopedPrematureExitFile premature_exit_file(
5663       in_death_test_child_process ?
5664       NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5665 
5666   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
5667   // used for the duration of the program.
5668   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5669 
5670 #if GTEST_HAS_SEH
5671   // Either the user wants Google Test to catch exceptions thrown by the
5672   // tests or this is executing in the context of death test child
5673   // process. In either case the user does not want to see pop-up dialogs
5674   // about crashes - they are expected.
5675   if (impl()->catch_exceptions() || in_death_test_child_process) {
5676 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5677     // SetErrorMode doesn't exist on CE.
5678     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5679                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5680 # endif  // !GTEST_OS_WINDOWS_MOBILE
5681 
5682 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5683     // Death test children can be terminated with _abort().  On Windows,
5684     // _abort() can show a dialog with a warning message.  This forces the
5685     // abort message to go to stderr instead.
5686     _set_error_mode(_OUT_TO_STDERR);
5687 # endif
5688 
5689 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5690     // In the debug version, Visual Studio pops up a separate dialog
5691     // offering a choice to debug the aborted program. We need to suppress
5692     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5693     // executed. Google Test will notify the user of any unexpected
5694     // failure via stderr.
5695     //
5696     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5697     // Users of prior VC versions shall suffer the agony and pain of
5698     // clicking through the countless debug dialogs.
5699     // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5700     // debug mode when compiled with VC 7.1 or lower.
5701     if (!GTEST_FLAG(break_on_failure))
5702       _set_abort_behavior(
5703           0x0,                                    // Clear the following flags:
5704           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
5705 # endif
5706   }
5707 #endif  // GTEST_HAS_SEH
5708 
5709   return internal::HandleExceptionsInMethodIfSupported(
5710       impl(),
5711       &internal::UnitTestImpl::RunAllTests,
5712       "auxiliary test code (environments or event listeners)") ? 0 : 1;
5713 }
5714 
5715 // Returns the working directory when the first TEST() or TEST_F() was
5716 // executed.
original_working_dir() const5717 const char* UnitTest::original_working_dir() const {
5718   return impl_->original_working_dir_.c_str();
5719 }
5720 
5721 // Returns the TestCase object for the test that's currently running,
5722 // or NULL if no test is running.
current_test_case() const5723 const TestCase* UnitTest::current_test_case() const
5724     GTEST_LOCK_EXCLUDED_(mutex_) {
5725   internal::MutexLock lock(&mutex_);
5726   return impl_->current_test_case();
5727 }
5728 
5729 // Returns the TestInfo object for the test that's currently running,
5730 // or NULL if no test is running.
current_test_info() const5731 const TestInfo* UnitTest::current_test_info() const
5732     GTEST_LOCK_EXCLUDED_(mutex_) {
5733   internal::MutexLock lock(&mutex_);
5734   return impl_->current_test_info();
5735 }
5736 
5737 // Returns the random seed used at the start of the current test run.
random_seed() const5738 int UnitTest::random_seed() const { return impl_->random_seed(); }
5739 
5740 #if GTEST_HAS_PARAM_TEST
5741 // Returns ParameterizedTestCaseRegistry object used to keep track of
5742 // value-parameterized tests and instantiate and register them.
5743 internal::ParameterizedTestCaseRegistry&
parameterized_test_registry()5744     UnitTest::parameterized_test_registry()
5745         GTEST_LOCK_EXCLUDED_(mutex_) {
5746   return impl_->parameterized_test_registry();
5747 }
5748 #endif  // GTEST_HAS_PARAM_TEST
5749 
5750 // Creates an empty UnitTest.
UnitTest()5751 UnitTest::UnitTest() {
5752   impl_ = new internal::UnitTestImpl(this);
5753 }
5754 
5755 // Destructor of UnitTest.
~UnitTest()5756 UnitTest::~UnitTest() {
5757   delete impl_;
5758 }
5759 
5760 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5761 // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)5762 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5763     GTEST_LOCK_EXCLUDED_(mutex_) {
5764   internal::MutexLock lock(&mutex_);
5765   impl_->gtest_trace_stack().push_back(trace);
5766 }
5767 
5768 // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()5769 void UnitTest::PopGTestTrace()
5770     GTEST_LOCK_EXCLUDED_(mutex_) {
5771   internal::MutexLock lock(&mutex_);
5772   impl_->gtest_trace_stack().pop_back();
5773 }
5774 
5775 namespace internal {
5776 
UnitTestImpl(UnitTest * parent)5777 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5778     : parent_(parent),
5779       GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
5780       default_global_test_part_result_reporter_(this),
5781       default_per_thread_test_part_result_reporter_(this),
5782       GTEST_DISABLE_MSC_WARNINGS_POP_()
5783       global_test_part_result_repoter_(
5784           &default_global_test_part_result_reporter_),
5785       per_thread_test_part_result_reporter_(
5786           &default_per_thread_test_part_result_reporter_),
5787 #if GTEST_HAS_PARAM_TEST
5788       parameterized_test_registry_(),
5789       parameterized_tests_registered_(false),
5790 #endif  // GTEST_HAS_PARAM_TEST
5791       last_death_test_case_(-1),
5792       current_test_case_(NULL),
5793       current_test_info_(NULL),
5794       ad_hoc_test_result_(),
5795       os_stack_trace_getter_(NULL),
5796       post_flag_parse_init_performed_(false),
5797       random_seed_(0),  // Will be overridden by the flag before first use.
5798       random_(0),  // Will be reseeded before first use.
5799       start_timestamp_(0),
5800       elapsed_time_(0),
5801 #if GTEST_HAS_DEATH_TEST
5802       death_test_factory_(new DefaultDeathTestFactory),
5803 #endif
5804       // Will be overridden by the flag before first use.
5805       catch_exceptions_(false) {
5806   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5807 }
5808 
~UnitTestImpl()5809 UnitTestImpl::~UnitTestImpl() {
5810   // Deletes every TestCase.
5811   ForEach(test_cases_, internal::Delete<TestCase>);
5812 
5813   // Deletes every Environment.
5814   ForEach(environments_, internal::Delete<Environment>);
5815 
5816   delete os_stack_trace_getter_;
5817 }
5818 
5819 // Adds a TestProperty to the current TestResult object when invoked in a
5820 // context of a test, to current test case's ad_hoc_test_result when invoke
5821 // from SetUpTestCase/TearDownTestCase, or to the global property set
5822 // otherwise.  If the result already contains a property with the same key,
5823 // the value will be updated.
RecordProperty(const TestProperty & test_property)5824 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5825   std::string xml_element;
5826   TestResult* test_result;  // TestResult appropriate for property recording.
5827 
5828   if (current_test_info_ != NULL) {
5829     xml_element = "testcase";
5830     test_result = &(current_test_info_->result_);
5831   } else if (current_test_case_ != NULL) {
5832     xml_element = "testsuite";
5833     test_result = &(current_test_case_->ad_hoc_test_result_);
5834   } else {
5835     xml_element = "testsuites";
5836     test_result = &ad_hoc_test_result_;
5837   }
5838   test_result->RecordProperty(xml_element, test_property);
5839 }
5840 
5841 #if GTEST_HAS_DEATH_TEST
5842 // Disables event forwarding if the control is currently in a death test
5843 // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()5844 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5845   if (internal_run_death_test_flag_.get() != NULL)
5846     listeners()->SuppressEventForwarding();
5847 }
5848 #endif  // GTEST_HAS_DEATH_TEST
5849 
5850 // Initializes event listeners performing XML output as specified by
5851 // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()5852 void UnitTestImpl::ConfigureXmlOutput() {
5853   const std::string& output_format = UnitTestOptions::GetOutputFormat();
5854   if (output_format == "xml") {
5855     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5856         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5857   } else if (output_format != "") {
5858     printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5859            output_format.c_str());
5860     fflush(stdout);
5861   }
5862 }
5863 
5864 #if GTEST_CAN_STREAM_RESULTS_
5865 // Initializes event listeners for streaming test results in string form.
5866 // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()5867 void UnitTestImpl::ConfigureStreamingOutput() {
5868   const std::string& target = GTEST_FLAG(stream_result_to);
5869   if (!target.empty()) {
5870     const size_t pos = target.find(':');
5871     if (pos != std::string::npos) {
5872       listeners()->Append(new StreamingListener(target.substr(0, pos),
5873                                                 target.substr(pos+1)));
5874     } else {
5875       printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5876              target.c_str());
5877       fflush(stdout);
5878     }
5879   }
5880 }
5881 #endif  // GTEST_CAN_STREAM_RESULTS_
5882 
5883 // Performs initialization dependent upon flag values obtained in
5884 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
5885 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
5886 // this function is also called from RunAllTests.  Since this function can be
5887 // called more than once, it has to be idempotent.
PostFlagParsingInit()5888 void UnitTestImpl::PostFlagParsingInit() {
5889   // Ensures that this function does not execute more than once.
5890   if (!post_flag_parse_init_performed_) {
5891     post_flag_parse_init_performed_ = true;
5892 
5893 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5894     // Register to send notifications about key process state changes.
5895     listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5896 #endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5897 
5898 #if GTEST_HAS_DEATH_TEST
5899     InitDeathTestSubprocessControlInfo();
5900     SuppressTestEventsIfInSubprocess();
5901 #endif  // GTEST_HAS_DEATH_TEST
5902 
5903     // Registers parameterized tests. This makes parameterized tests
5904     // available to the UnitTest reflection API without running
5905     // RUN_ALL_TESTS.
5906     RegisterParameterizedTests();
5907 
5908     // Configures listeners for XML output. This makes it possible for users
5909     // to shut down the default XML output before invoking RUN_ALL_TESTS.
5910     ConfigureXmlOutput();
5911 
5912 #if GTEST_CAN_STREAM_RESULTS_
5913     // Configures listeners for streaming test results to the specified server.
5914     ConfigureStreamingOutput();
5915 #endif  // GTEST_CAN_STREAM_RESULTS_
5916   }
5917 }
5918 
5919 // A predicate that checks the name of a TestCase against a known
5920 // value.
5921 //
5922 // This is used for implementation of the UnitTest class only.  We put
5923 // it in the anonymous namespace to prevent polluting the outer
5924 // namespace.
5925 //
5926 // TestCaseNameIs is copyable.
5927 class TestCaseNameIs {
5928  public:
5929   // Constructor.
TestCaseNameIs(const std::string & name)5930   explicit TestCaseNameIs(const std::string& name)
5931       : name_(name) {}
5932 
5933   // Returns true iff the name of test_case matches name_.
operator ()(const TestCase * test_case) const5934   bool operator()(const TestCase* test_case) const {
5935     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5936   }
5937 
5938  private:
5939   std::string name_;
5940 };
5941 
5942 // Finds and returns a TestCase with the given name.  If one doesn't
5943 // exist, creates one and returns it.  It's the CALLER'S
5944 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5945 // TESTS ARE NOT SHUFFLED.
5946 //
5947 // Arguments:
5948 //
5949 //   test_case_name: name of the test case
5950 //   type_param:     the name of the test case's type parameter, or NULL if
5951 //                   this is not a typed or a type-parameterized test case.
5952 //   set_up_tc:      pointer to the function that sets up the test case
5953 //   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)5954 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5955                                     const char* type_param,
5956                                     Test::SetUpTestCaseFunc set_up_tc,
5957                                     Test::TearDownTestCaseFunc tear_down_tc) {
5958   // Can we find a TestCase with the given name?
5959   const std::vector<TestCase*>::const_iterator test_case =
5960       std::find_if(test_cases_.begin(), test_cases_.end(),
5961                    TestCaseNameIs(test_case_name));
5962 
5963   if (test_case != test_cases_.end())
5964     return *test_case;
5965 
5966   // No.  Let's create one.
5967   TestCase* const new_test_case =
5968       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5969 
5970   // Is this a death test case?
5971   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5972                                                kDeathTestCaseFilter)) {
5973     // Yes.  Inserts the test case after the last death test case
5974     // defined so far.  This only works when the test cases haven't
5975     // been shuffled.  Otherwise we may end up running a death test
5976     // after a non-death test.
5977     ++last_death_test_case_;
5978     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5979                        new_test_case);
5980   } else {
5981     // No.  Appends to the end of the list.
5982     test_cases_.push_back(new_test_case);
5983   }
5984 
5985   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5986   return new_test_case;
5987 }
5988 
5989 // Helpers for setting up / tearing down the given environment.  They
5990 // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)5991 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)5992 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5993 
5994 // Runs all tests in this UnitTest object, prints the result, and
5995 // returns true if all tests are successful.  If any exception is
5996 // thrown during a test, the test is considered to be failed, but the
5997 // rest of the tests will still be run.
5998 //
5999 // When parameterized tests are enabled, it expands and registers
6000 // parameterized tests first in RegisterParameterizedTests().
6001 // All other functions called from RunAllTests() may safely assume that
6002 // parameterized tests are ready to be counted and run.
RunAllTests()6003 bool UnitTestImpl::RunAllTests() {
6004   // Makes sure InitGoogleTest() was called.
6005   if (!GTestIsInitialized()) {
6006     printf("%s",
6007            "\nThis test program did NOT call ::testing::InitGoogleTest "
6008            "before calling RUN_ALL_TESTS().  Please fix it.\n");
6009     return false;
6010   }
6011 
6012   // Do not run any test if the --help flag was specified.
6013   if (g_help_flag)
6014     return true;
6015 
6016   // Repeats the call to the post-flag parsing initialization in case the
6017   // user didn't call InitGoogleTest.
6018   PostFlagParsingInit();
6019 
6020   // Even if sharding is not on, test runners may want to use the
6021   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6022   // protocol.
6023   internal::WriteToShardStatusFileIfNeeded();
6024 
6025   // True iff we are in a subprocess for running a thread-safe-style
6026   // death test.
6027   bool in_subprocess_for_death_test = false;
6028 
6029 #if GTEST_HAS_DEATH_TEST
6030   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
6031 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6032   if (in_subprocess_for_death_test) {
6033     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6034   }
6035 # endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6036 #endif  // GTEST_HAS_DEATH_TEST
6037 
6038   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6039                                         in_subprocess_for_death_test);
6040 
6041   // Compares the full test names with the filter to decide which
6042   // tests to run.
6043   const bool has_tests_to_run = FilterTests(should_shard
6044                                               ? HONOR_SHARDING_PROTOCOL
6045                                               : IGNORE_SHARDING_PROTOCOL) > 0;
6046 
6047   // Lists the tests and exits if the --gtest_list_tests flag was specified.
6048   if (GTEST_FLAG(list_tests)) {
6049     // This must be called *after* FilterTests() has been called.
6050     ListTestsMatchingFilter();
6051     return true;
6052   }
6053 
6054   random_seed_ = GTEST_FLAG(shuffle) ?
6055       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6056 
6057   // True iff at least one test has failed.
6058   bool failed = false;
6059 
6060   TestEventListener* repeater = listeners()->repeater();
6061 
6062   start_timestamp_ = GetTimeInMillis();
6063   repeater->OnTestProgramStart(*parent_);
6064 
6065   // How many times to repeat the tests?  We don't want to repeat them
6066   // when we are inside the subprocess of a death test.
6067   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6068   // Repeats forever if the repeat count is negative.
6069   const bool forever = repeat < 0;
6070   for (int i = 0; forever || i != repeat; i++) {
6071     // We want to preserve failures generated by ad-hoc test
6072     // assertions executed before RUN_ALL_TESTS().
6073     ClearNonAdHocTestResult();
6074 
6075     const TimeInMillis start = GetTimeInMillis();
6076 
6077     // Shuffles test cases and tests if requested.
6078     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6079       random()->Reseed(random_seed_);
6080       // This should be done before calling OnTestIterationStart(),
6081       // such that a test event listener can see the actual test order
6082       // in the event.
6083       ShuffleTests();
6084     }
6085 
6086     // Tells the unit test event listeners that the tests are about to start.
6087     repeater->OnTestIterationStart(*parent_, i);
6088 
6089     // Runs each test case if there is at least one test to run.
6090     if (has_tests_to_run) {
6091       // Sets up all environments beforehand.
6092       repeater->OnEnvironmentsSetUpStart(*parent_);
6093       ForEach(environments_, SetUpEnvironment);
6094       repeater->OnEnvironmentsSetUpEnd(*parent_);
6095 
6096       // Runs the tests only if there was no fatal failure during global
6097       // set-up.
6098       if (!Test::HasFatalFailure()) {
6099         for (int test_index = 0; test_index < total_test_case_count();
6100              test_index++) {
6101           GetMutableTestCase(test_index)->Run();
6102         }
6103       }
6104 
6105       // Tears down all environments in reverse order afterwards.
6106       repeater->OnEnvironmentsTearDownStart(*parent_);
6107       std::for_each(environments_.rbegin(), environments_.rend(),
6108                     TearDownEnvironment);
6109       repeater->OnEnvironmentsTearDownEnd(*parent_);
6110     }
6111 
6112     elapsed_time_ = GetTimeInMillis() - start;
6113 
6114     // Tells the unit test event listener that the tests have just finished.
6115     repeater->OnTestIterationEnd(*parent_, i);
6116 
6117     // Gets the result and clears it.
6118     if (!Passed()) {
6119       failed = true;
6120     }
6121 
6122     // Restores the original test order after the iteration.  This
6123     // allows the user to quickly repro a failure that happens in the
6124     // N-th iteration without repeating the first (N - 1) iterations.
6125     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6126     // case the user somehow changes the value of the flag somewhere
6127     // (it's always safe to unshuffle the tests).
6128     UnshuffleTests();
6129 
6130     if (GTEST_FLAG(shuffle)) {
6131       // Picks a new random seed for each iteration.
6132       random_seed_ = GetNextRandomSeed(random_seed_);
6133     }
6134   }
6135 
6136   repeater->OnTestProgramEnd(*parent_);
6137 
6138   return !failed;
6139 }
6140 
6141 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6142 // if the variable is present. If a file already exists at this location, this
6143 // function will write over it. If the variable is present, but the file cannot
6144 // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()6145 void WriteToShardStatusFileIfNeeded() {
6146   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6147   if (test_shard_file != NULL) {
6148     FILE* const file = posix::FOpen(test_shard_file, "w");
6149     if (file == NULL) {
6150       ColoredPrintf(COLOR_RED,
6151                     "Could not write to the test shard status file \"%s\" "
6152                     "specified by the %s environment variable.\n",
6153                     test_shard_file, kTestShardStatusFile);
6154       fflush(stdout);
6155       exit(EXIT_FAILURE);
6156     }
6157     fclose(file);
6158   }
6159 }
6160 
6161 // Checks whether sharding is enabled by examining the relevant
6162 // environment variable values. If the variables are present,
6163 // but inconsistent (i.e., shard_index >= total_shards), prints
6164 // an error and exits. If in_subprocess_for_death_test, sharding is
6165 // disabled because it must only be applied to the original test
6166 // 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)6167 bool ShouldShard(const char* total_shards_env,
6168                  const char* shard_index_env,
6169                  bool in_subprocess_for_death_test) {
6170   if (in_subprocess_for_death_test) {
6171     return false;
6172   }
6173 
6174   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6175   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6176 
6177   if (total_shards == -1 && shard_index == -1) {
6178     return false;
6179   } else if (total_shards == -1 && shard_index != -1) {
6180     const Message msg = Message()
6181       << "Invalid environment variables: you have "
6182       << kTestShardIndex << " = " << shard_index
6183       << ", but have left " << kTestTotalShards << " unset.\n";
6184     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6185     fflush(stdout);
6186     exit(EXIT_FAILURE);
6187   } else if (total_shards != -1 && shard_index == -1) {
6188     const Message msg = Message()
6189       << "Invalid environment variables: you have "
6190       << kTestTotalShards << " = " << total_shards
6191       << ", but have left " << kTestShardIndex << " unset.\n";
6192     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6193     fflush(stdout);
6194     exit(EXIT_FAILURE);
6195   } else if (shard_index < 0 || shard_index >= total_shards) {
6196     const Message msg = Message()
6197       << "Invalid environment variables: we require 0 <= "
6198       << kTestShardIndex << " < " << kTestTotalShards
6199       << ", but you have " << kTestShardIndex << "=" << shard_index
6200       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
6201     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6202     fflush(stdout);
6203     exit(EXIT_FAILURE);
6204   }
6205 
6206   return total_shards > 1;
6207 }
6208 
6209 // Parses the environment variable var as an Int32. If it is unset,
6210 // returns default_val. If it is not an Int32, prints an error
6211 // and aborts.
Int32FromEnvOrDie(const char * var,Int32 default_val)6212 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6213   const char* str_val = posix::GetEnv(var);
6214   if (str_val == NULL) {
6215     return default_val;
6216   }
6217 
6218   Int32 result;
6219   if (!ParseInt32(Message() << "The value of environment variable " << var,
6220                   str_val, &result)) {
6221     exit(EXIT_FAILURE);
6222   }
6223   return result;
6224 }
6225 
6226 // Given the total number of shards, the shard index, and the test id,
6227 // returns true iff the test should be run on this shard. The test id is
6228 // some arbitrary but unique non-negative integer assigned to each test
6229 // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)6230 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6231   return (test_id % total_shards) == shard_index;
6232 }
6233 
6234 // Compares the name of each test with the user-specified filter to
6235 // decide whether the test should be run, then records the result in
6236 // each TestCase and TestInfo object.
6237 // If shard_tests == true, further filters tests based on sharding
6238 // variables in the environment - see
6239 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
6240 // Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)6241 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6242   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6243       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6244   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6245       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6246 
6247   // num_runnable_tests are the number of tests that will
6248   // run across all shards (i.e., match filter and are not disabled).
6249   // num_selected_tests are the number of tests to be run on
6250   // this shard.
6251   int num_runnable_tests = 0;
6252   int num_selected_tests = 0;
6253   for (size_t i = 0; i < test_cases_.size(); i++) {
6254     TestCase* const test_case = test_cases_[i];
6255     const std::string &test_case_name = test_case->name();
6256     test_case->set_should_run(false);
6257 
6258     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6259       TestInfo* const test_info = test_case->test_info_list()[j];
6260       const std::string test_name(test_info->name());
6261       // A test is disabled if test case name or test name matches
6262       // kDisableTestFilter.
6263       const bool is_disabled =
6264           internal::UnitTestOptions::MatchesFilter(test_case_name,
6265                                                    kDisableTestFilter) ||
6266           internal::UnitTestOptions::MatchesFilter(test_name,
6267                                                    kDisableTestFilter);
6268       test_info->is_disabled_ = is_disabled;
6269 
6270       const bool matches_filter =
6271           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
6272                                                        test_name);
6273       test_info->matches_filter_ = matches_filter;
6274 
6275       const bool is_runnable =
6276           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6277           matches_filter;
6278 
6279       const bool is_selected = is_runnable &&
6280           (shard_tests == IGNORE_SHARDING_PROTOCOL ||
6281            ShouldRunTestOnShard(total_shards, shard_index,
6282                                 num_runnable_tests));
6283 
6284       num_runnable_tests += is_runnable;
6285       num_selected_tests += is_selected;
6286 
6287       test_info->should_run_ = is_selected;
6288       test_case->set_should_run(test_case->should_run() || is_selected);
6289     }
6290   }
6291   return num_selected_tests;
6292 }
6293 
6294 // Prints the given C-string on a single line by replacing all '\n'
6295 // characters with string "\\n".  If the output takes more than
6296 // max_length characters, only prints the first max_length characters
6297 // and "...".
PrintOnOneLine(const char * str,int max_length)6298 static void PrintOnOneLine(const char* str, int max_length) {
6299   if (str != NULL) {
6300     for (int i = 0; *str != '\0'; ++str) {
6301       if (i >= max_length) {
6302         printf("...");
6303         break;
6304       }
6305       if (*str == '\n') {
6306         printf("\\n");
6307         i += 2;
6308       } else {
6309         printf("%c", *str);
6310         ++i;
6311       }
6312     }
6313   }
6314 }
6315 
6316 // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()6317 void UnitTestImpl::ListTestsMatchingFilter() {
6318   // Print at most this many characters for each type/value parameter.
6319   const int kMaxParamLength = 250;
6320 
6321   for (size_t i = 0; i < test_cases_.size(); i++) {
6322     const TestCase* const test_case = test_cases_[i];
6323     bool printed_test_case_name = false;
6324 
6325     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6326       const TestInfo* const test_info =
6327           test_case->test_info_list()[j];
6328       if (test_info->matches_filter_) {
6329         if (!printed_test_case_name) {
6330           printed_test_case_name = true;
6331           printf("%s.", test_case->name());
6332           if (test_case->type_param() != NULL) {
6333             printf("  # %s = ", kTypeParamLabel);
6334             // We print the type parameter on a single line to make
6335             // the output easy to parse by a program.
6336             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6337           }
6338           printf("\n");
6339         }
6340         printf("  %s", test_info->name());
6341         if (test_info->value_param() != NULL) {
6342           printf("  # %s = ", kValueParamLabel);
6343           // We print the value parameter on a single line to make the
6344           // output easy to parse by a program.
6345           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6346         }
6347         printf("\n");
6348       }
6349     }
6350   }
6351   fflush(stdout);
6352 }
6353 
6354 // Sets the OS stack trace getter.
6355 //
6356 // Does nothing if the input and the current OS stack trace getter are
6357 // the same; otherwise, deletes the old getter and makes the input the
6358 // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)6359 void UnitTestImpl::set_os_stack_trace_getter(
6360     OsStackTraceGetterInterface* getter) {
6361   if (os_stack_trace_getter_ != getter) {
6362     delete os_stack_trace_getter_;
6363     os_stack_trace_getter_ = getter;
6364   }
6365 }
6366 
6367 // Returns the current OS stack trace getter if it is not NULL;
6368 // otherwise, creates an OsStackTraceGetter, makes it the current
6369 // getter, and returns it.
os_stack_trace_getter()6370 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6371   if (os_stack_trace_getter_ == NULL) {
6372 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6373     os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
6374 #else
6375     os_stack_trace_getter_ = new OsStackTraceGetter;
6376 #endif  // GTEST_OS_STACK_TRACE_GETTER_
6377   }
6378 
6379   return os_stack_trace_getter_;
6380 }
6381 
6382 // Returns the TestResult for the test that's currently running, or
6383 // the TestResult for the ad hoc test if no test is running.
current_test_result()6384 TestResult* UnitTestImpl::current_test_result() {
6385   return current_test_info_ ?
6386       &(current_test_info_->result_) : &ad_hoc_test_result_;
6387 }
6388 
6389 // Shuffles all test cases, and the tests within each test case,
6390 // making sure that death tests are still run first.
ShuffleTests()6391 void UnitTestImpl::ShuffleTests() {
6392   // Shuffles the death test cases.
6393   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6394 
6395   // Shuffles the non-death test cases.
6396   ShuffleRange(random(), last_death_test_case_ + 1,
6397                static_cast<int>(test_cases_.size()), &test_case_indices_);
6398 
6399   // Shuffles the tests inside each test case.
6400   for (size_t i = 0; i < test_cases_.size(); i++) {
6401     test_cases_[i]->ShuffleTests(random());
6402   }
6403 }
6404 
6405 // Restores the test cases and tests to their order before the first shuffle.
UnshuffleTests()6406 void UnitTestImpl::UnshuffleTests() {
6407   for (size_t i = 0; i < test_cases_.size(); i++) {
6408     // Unshuffles the tests in each test case.
6409     test_cases_[i]->UnshuffleTests();
6410     // Resets the index of each test case.
6411     test_case_indices_[i] = static_cast<int>(i);
6412   }
6413 }
6414 
6415 // Returns the current OS stack trace as an std::string.
6416 //
6417 // The maximum number of stack frames to be included is specified by
6418 // the gtest_stack_trace_depth flag.  The skip_count parameter
6419 // specifies the number of top frames to be skipped, which doesn't
6420 // count against the number of frames to be included.
6421 //
6422 // For example, if Foo() calls Bar(), which in turn calls
6423 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6424 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)6425 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
6426                                             int skip_count) {
6427   // We pass skip_count + 1 to skip this wrapper function in addition
6428   // to what the user really wants to skip.
6429   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6430 }
6431 
6432 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6433 // suppress unreachable code warnings.
6434 namespace {
6435 class ClassUniqueToAlwaysTrue {};
6436 }
6437 
IsTrue(bool condition)6438 bool IsTrue(bool condition) { return condition; }
6439 
AlwaysTrue()6440 bool AlwaysTrue() {
6441 #if GTEST_HAS_EXCEPTIONS
6442   // This condition is always false so AlwaysTrue() never actually throws,
6443   // but it makes the compiler think that it may throw.
6444   if (IsTrue(false))
6445     throw ClassUniqueToAlwaysTrue();
6446 #endif  // GTEST_HAS_EXCEPTIONS
6447   return true;
6448 }
6449 
6450 // If *pstr starts with the given prefix, modifies *pstr to be right
6451 // past the prefix and returns true; otherwise leaves *pstr unchanged
6452 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)6453 bool SkipPrefix(const char* prefix, const char** pstr) {
6454   const size_t prefix_len = strlen(prefix);
6455   if (strncmp(*pstr, prefix, prefix_len) == 0) {
6456     *pstr += prefix_len;
6457     return true;
6458   }
6459   return false;
6460 }
6461 
6462 // Parses a string as a command line flag.  The string should have
6463 // the format "--flag=value".  When def_optional is true, the "=value"
6464 // part can be omitted.
6465 //
6466 // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)6467 const char* ParseFlagValue(const char* str,
6468                            const char* flag,
6469                            bool def_optional) {
6470   // str and flag must not be NULL.
6471   if (str == NULL || flag == NULL) return NULL;
6472 
6473   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6474   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6475   const size_t flag_len = flag_str.length();
6476   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6477 
6478   // Skips the flag name.
6479   const char* flag_end = str + flag_len;
6480 
6481   // When def_optional is true, it's OK to not have a "=value" part.
6482   if (def_optional && (flag_end[0] == '\0')) {
6483     return flag_end;
6484   }
6485 
6486   // If def_optional is true and there are more characters after the
6487   // flag name, or if def_optional is false, there must be a '=' after
6488   // the flag name.
6489   if (flag_end[0] != '=') return NULL;
6490 
6491   // Returns the string after "=".
6492   return flag_end + 1;
6493 }
6494 
6495 // Parses a string for a bool flag, in the form of either
6496 // "--flag=value" or "--flag".
6497 //
6498 // In the former case, the value is taken as true as long as it does
6499 // not start with '0', 'f', or 'F'.
6500 //
6501 // In the latter case, the value is taken as true.
6502 //
6503 // On success, stores the value of the flag in *value, and returns
6504 // true.  On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)6505 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6506   // Gets the value of the flag as a string.
6507   const char* const value_str = ParseFlagValue(str, flag, true);
6508 
6509   // Aborts if the parsing failed.
6510   if (value_str == NULL) return false;
6511 
6512   // Converts the string value to a bool.
6513   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6514   return true;
6515 }
6516 
6517 // Parses a string for an Int32 flag, in the form of
6518 // "--flag=value".
6519 //
6520 // On success, stores the value of the flag in *value, and returns
6521 // true.  On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,Int32 * value)6522 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6523   // Gets the value of the flag as a string.
6524   const char* const value_str = ParseFlagValue(str, flag, false);
6525 
6526   // Aborts if the parsing failed.
6527   if (value_str == NULL) return false;
6528 
6529   // Sets *value to the value of the flag.
6530   return ParseInt32(Message() << "The value of flag --" << flag,
6531                     value_str, value);
6532 }
6533 
6534 // Parses a string for a string flag, in the form of
6535 // "--flag=value".
6536 //
6537 // On success, stores the value of the flag in *value, and returns
6538 // true.  On failure, returns false without changing *value.
ParseStringFlag(const char * str,const char * flag,std::string * value)6539 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6540   // Gets the value of the flag as a string.
6541   const char* const value_str = ParseFlagValue(str, flag, false);
6542 
6543   // Aborts if the parsing failed.
6544   if (value_str == NULL) return false;
6545 
6546   // Sets *value to the value of the flag.
6547   *value = value_str;
6548   return true;
6549 }
6550 
6551 // Determines whether a string has a prefix that Google Test uses for its
6552 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6553 // If Google Test detects that a command line flag has its prefix but is not
6554 // recognized, it will print its help message. Flags starting with
6555 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6556 // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)6557 static bool HasGoogleTestFlagPrefix(const char* str) {
6558   return (SkipPrefix("--", &str) ||
6559           SkipPrefix("-", &str) ||
6560           SkipPrefix("/", &str)) &&
6561          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6562          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6563           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6564 }
6565 
6566 // Prints a string containing code-encoded text.  The following escape
6567 // sequences can be used in the string to control the text color:
6568 //
6569 //   @@    prints a single '@' character.
6570 //   @R    changes the color to red.
6571 //   @G    changes the color to green.
6572 //   @Y    changes the color to yellow.
6573 //   @D    changes to the default terminal text color.
6574 //
6575 // TODO(wan@google.com): Write tests for this once we add stdout
6576 // capturing to Google Test.
PrintColorEncoded(const char * str)6577 static void PrintColorEncoded(const char* str) {
6578   GTestColor color = COLOR_DEFAULT;  // The current color.
6579 
6580   // Conceptually, we split the string into segments divided by escape
6581   // sequences.  Then we print one segment at a time.  At the end of
6582   // each iteration, the str pointer advances to the beginning of the
6583   // next segment.
6584   for (;;) {
6585     const char* p = strchr(str, '@');
6586     if (p == NULL) {
6587       ColoredPrintf(color, "%s", str);
6588       return;
6589     }
6590 
6591     ColoredPrintf(color, "%s", std::string(str, p).c_str());
6592 
6593     const char ch = p[1];
6594     str = p + 2;
6595     if (ch == '@') {
6596       ColoredPrintf(color, "@");
6597     } else if (ch == 'D') {
6598       color = COLOR_DEFAULT;
6599     } else if (ch == 'R') {
6600       color = COLOR_RED;
6601     } else if (ch == 'G') {
6602       color = COLOR_GREEN;
6603     } else if (ch == 'Y') {
6604       color = COLOR_YELLOW;
6605     } else {
6606       --str;
6607     }
6608   }
6609 }
6610 
6611 static const char kColorEncodedHelpMessage[] =
6612 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6613 "following command line flags to control its behavior:\n"
6614 "\n"
6615 "Test Selection:\n"
6616 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6617 "      List the names of all tests instead of running them. The name of\n"
6618 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
6619 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6620     "[@G-@YNEGATIVE_PATTERNS]@D\n"
6621 "      Run only the tests whose name matches one of the positive patterns but\n"
6622 "      none of the negative patterns. '?' matches any single character; '*'\n"
6623 "      matches any substring; ':' separates two patterns.\n"
6624 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6625 "      Run all disabled tests too.\n"
6626 "\n"
6627 "Test Execution:\n"
6628 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6629 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
6630 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6631 "      Randomize tests' orders on every iteration.\n"
6632 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6633 "      Random number seed to use for shuffling test orders (between 1 and\n"
6634 "      99999, or 0 to use a seed based on the current time).\n"
6635 "\n"
6636 "Test Output:\n"
6637 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6638 "      Enable/disable colored output. The default is @Gauto@D.\n"
6639 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6640 "      Don't print the elapsed time of each test.\n"
6641 "  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6642     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6643 "      Generate an XML report in the given directory or with the given file\n"
6644 "      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6645 #if GTEST_CAN_STREAM_RESULTS_
6646 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6647 "      Stream test results to the given server.\n"
6648 #endif  // GTEST_CAN_STREAM_RESULTS_
6649 "\n"
6650 "Assertion Behavior:\n"
6651 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6652 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6653 "      Set the default death test style.\n"
6654 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6655 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6656 "      Turn assertion failures into debugger break-points.\n"
6657 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6658 "      Turn assertion failures into C++ exceptions.\n"
6659 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6660 "      Do not report exceptions as test failures. Instead, allow them\n"
6661 "      to crash the program or throw a pop-up (on Windows).\n"
6662 "\n"
6663 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6664     "the corresponding\n"
6665 "environment variable of a flag (all letters in upper-case). For example, to\n"
6666 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6667     "color=no@D or set\n"
6668 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6669 "\n"
6670 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6671 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6672 "(not one in your own code or tests), please report it to\n"
6673 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6674 
ParseGoogleTestFlag(const char * const arg)6675 bool ParseGoogleTestFlag(const char* const arg) {
6676   return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6677                        &GTEST_FLAG(also_run_disabled_tests)) ||
6678       ParseBoolFlag(arg, kBreakOnFailureFlag,
6679                     &GTEST_FLAG(break_on_failure)) ||
6680       ParseBoolFlag(arg, kCatchExceptionsFlag,
6681                     &GTEST_FLAG(catch_exceptions)) ||
6682       ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6683       ParseStringFlag(arg, kDeathTestStyleFlag,
6684                       &GTEST_FLAG(death_test_style)) ||
6685       ParseBoolFlag(arg, kDeathTestUseFork,
6686                     &GTEST_FLAG(death_test_use_fork)) ||
6687       ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6688       ParseStringFlag(arg, kInternalRunDeathTestFlag,
6689                       &GTEST_FLAG(internal_run_death_test)) ||
6690       ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6691       ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
6692       ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6693       ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
6694       ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6695       ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6696       ParseInt32Flag(arg, kStackTraceDepthFlag,
6697                      &GTEST_FLAG(stack_trace_depth)) ||
6698       ParseStringFlag(arg, kStreamResultToFlag,
6699                       &GTEST_FLAG(stream_result_to)) ||
6700       ParseBoolFlag(arg, kThrowOnFailureFlag,
6701                     &GTEST_FLAG(throw_on_failure));
6702 }
6703 
6704 #if GTEST_USE_OWN_FLAGFILE_FLAG_
LoadFlagsFromFile(const std::string & path)6705 void LoadFlagsFromFile(const std::string& path) {
6706   FILE* flagfile = posix::FOpen(path.c_str(), "r");
6707   if (!flagfile) {
6708     fprintf(stderr,
6709             "Unable to open file \"%s\"\n",
6710             GTEST_FLAG(flagfile).c_str());
6711     fflush(stderr);
6712     exit(EXIT_FAILURE);
6713   }
6714   std::string contents(ReadEntireFile(flagfile));
6715   posix::FClose(flagfile);
6716   std::vector<std::string> lines;
6717   SplitString(contents, '\n', &lines);
6718   for (size_t i = 0; i < lines.size(); ++i) {
6719     if (lines[i].empty())
6720       continue;
6721     if (!ParseGoogleTestFlag(lines[i].c_str()))
6722       g_help_flag = true;
6723   }
6724 }
6725 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
6726 
6727 // Parses the command line for Google Test flags, without initializing
6728 // other parts of Google Test.  The type parameter CharType can be
6729 // instantiated to either char or wchar_t.
6730 template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)6731 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6732   for (int i = 1; i < *argc; i++) {
6733     const std::string arg_string = StreamableToString(argv[i]);
6734     const char* const arg = arg_string.c_str();
6735 
6736     using internal::ParseBoolFlag;
6737     using internal::ParseInt32Flag;
6738     using internal::ParseStringFlag;
6739 
6740     bool remove_flag = false;
6741     if (ParseGoogleTestFlag(arg)) {
6742       remove_flag = true;
6743 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6744     } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
6745       LoadFlagsFromFile(GTEST_FLAG(flagfile));
6746       remove_flag = true;
6747 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
6748     } else if (arg_string == "--help" || arg_string == "-h" ||
6749                arg_string == "-?" || arg_string == "/?" ||
6750                HasGoogleTestFlagPrefix(arg)) {
6751       // Both help flag and unrecognized Google Test flags (excluding
6752       // internal ones) trigger help display.
6753       g_help_flag = true;
6754     }
6755 
6756     if (remove_flag) {
6757       // Shift the remainder of the argv list left by one.  Note
6758       // that argv has (*argc + 1) elements, the last one always being
6759       // NULL.  The following loop moves the trailing NULL element as
6760       // well.
6761       for (int j = i; j != *argc; j++) {
6762         argv[j] = argv[j + 1];
6763       }
6764 
6765       // Decrements the argument count.
6766       (*argc)--;
6767 
6768       // We also need to decrement the iterator as we just removed
6769       // an element.
6770       i--;
6771     }
6772   }
6773 
6774   if (g_help_flag) {
6775     // We print the help here instead of in RUN_ALL_TESTS(), as the
6776     // latter may not be called at all if the user is using Google
6777     // Test with another testing framework.
6778     PrintColorEncoded(kColorEncodedHelpMessage);
6779   }
6780 }
6781 
6782 // Parses the command line for Google Test flags, without initializing
6783 // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)6784 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6785   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6786 }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)6787 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6788   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6789 }
6790 
6791 // The internal implementation of InitGoogleTest().
6792 //
6793 // The type parameter CharType can be instantiated to either char or
6794 // wchar_t.
6795 template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)6796 void InitGoogleTestImpl(int* argc, CharType** argv) {
6797   // We don't want to run the initialization code twice.
6798   if (GTestIsInitialized()) return;
6799 
6800   if (*argc <= 0) return;
6801 
6802   g_argvs.clear();
6803   for (int i = 0; i != *argc; i++) {
6804     g_argvs.push_back(StreamableToString(argv[i]));
6805   }
6806 
6807   ParseGoogleTestFlagsOnly(argc, argv);
6808   GetUnitTestImpl()->PostFlagParsingInit();
6809 }
6810 
6811 }  // namespace internal
6812 
6813 // Initializes Google Test.  This must be called before calling
6814 // RUN_ALL_TESTS().  In particular, it parses a command line for the
6815 // flags that Google Test recognizes.  Whenever a Google Test flag is
6816 // seen, it is removed from argv, and *argc is decremented.
6817 //
6818 // No value is returned.  Instead, the Google Test flag variables are
6819 // updated.
6820 //
6821 // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)6822 void InitGoogleTest(int* argc, char** argv) {
6823 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6824   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6825 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6826   internal::InitGoogleTestImpl(argc, argv);
6827 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6828 }
6829 
6830 // This overloaded version can be used in Windows programs compiled in
6831 // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)6832 void InitGoogleTest(int* argc, wchar_t** argv) {
6833 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6834   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6835 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6836   internal::InitGoogleTestImpl(argc, argv);
6837 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6838 }
6839 
6840 }  // namespace testing
6841 // Copyright 2005, Google Inc.
6842 // All rights reserved.
6843 //
6844 // Redistribution and use in source and binary forms, with or without
6845 // modification, are permitted provided that the following conditions are
6846 // met:
6847 //
6848 //     * Redistributions of source code must retain the above copyright
6849 // notice, this list of conditions and the following disclaimer.
6850 //     * Redistributions in binary form must reproduce the above
6851 // copyright notice, this list of conditions and the following disclaimer
6852 // in the documentation and/or other materials provided with the
6853 // distribution.
6854 //     * Neither the name of Google Inc. nor the names of its
6855 // contributors may be used to endorse or promote products derived from
6856 // this software without specific prior written permission.
6857 //
6858 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6859 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6860 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6861 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6862 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6863 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6864 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6865 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6866 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6867 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6868 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6869 //
6870 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6871 //
6872 // This file implements death tests.
6873 
6874 
6875 #if GTEST_HAS_DEATH_TEST
6876 
6877 # if GTEST_OS_MAC
6878 #  include <crt_externs.h>
6879 # endif  // GTEST_OS_MAC
6880 
6881 # include <errno.h>
6882 # include <fcntl.h>
6883 # include <limits.h>
6884 
6885 # if GTEST_OS_LINUX
6886 #  include <signal.h>
6887 # endif  // GTEST_OS_LINUX
6888 
6889 # include <stdarg.h>
6890 
6891 # if GTEST_OS_WINDOWS
6892 #  include <windows.h>
6893 # else
6894 #  include <sys/mman.h>
6895 #  include <sys/wait.h>
6896 # endif  // GTEST_OS_WINDOWS
6897 
6898 # if GTEST_OS_QNX
6899 #  include <spawn.h>
6900 # endif  // GTEST_OS_QNX
6901 
6902 #endif  // GTEST_HAS_DEATH_TEST
6903 
6904 
6905 // Indicates that this translation unit is part of Google Test's
6906 // implementation.  It must come before gtest-internal-inl.h is
6907 // included, or there will be a compiler error.  This trick exists to
6908 // prevent the accidental inclusion of gtest-internal-inl.h in the
6909 // user's code.
6910 #define GTEST_IMPLEMENTATION_ 1
6911 #undef GTEST_IMPLEMENTATION_
6912 
6913 namespace testing {
6914 
6915 // Constants.
6916 
6917 // The default death test style.
6918 static const char kDefaultDeathTestStyle[] = "fast";
6919 
6920 GTEST_DEFINE_string_(
6921     death_test_style,
6922     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6923     "Indicates how to run a death test in a forked child process: "
6924     "\"threadsafe\" (child process re-executes the test binary "
6925     "from the beginning, running only the specific death test) or "
6926     "\"fast\" (child process runs the death test immediately "
6927     "after forking).");
6928 
6929 GTEST_DEFINE_bool_(
6930     death_test_use_fork,
6931     internal::BoolFromGTestEnv("death_test_use_fork", false),
6932     "Instructs to use fork()/_exit() instead of clone() in death tests. "
6933     "Ignored and always uses fork() on POSIX systems where clone() is not "
6934     "implemented. Useful when running under valgrind or similar tools if "
6935     "those do not support clone(). Valgrind 3.3.1 will just fail if "
6936     "it sees an unsupported combination of clone() flags. "
6937     "It is not recommended to use this flag w/o valgrind though it will "
6938     "work in 99% of the cases. Once valgrind is fixed, this flag will "
6939     "most likely be removed.");
6940 
6941 namespace internal {
6942 GTEST_DEFINE_string_(
6943     internal_run_death_test, "",
6944     "Indicates the file, line number, temporal index of "
6945     "the single death test to run, and a file descriptor to "
6946     "which a success code may be sent, all separated by "
6947     "the '|' characters.  This flag is specified if and only if the current "
6948     "process is a sub-process launched for running a thread-safe "
6949     "death test.  FOR INTERNAL USE ONLY.");
6950 }  // namespace internal
6951 
6952 #if GTEST_HAS_DEATH_TEST
6953 
6954 namespace internal {
6955 
6956 // Valid only for fast death tests. Indicates the code is running in the
6957 // child process of a fast style death test.
6958 # if !GTEST_OS_WINDOWS
6959 static bool g_in_fast_death_test_child = false;
6960 # endif
6961 
6962 // Returns a Boolean value indicating whether the caller is currently
6963 // executing in the context of the death test child process.  Tools such as
6964 // Valgrind heap checkers may need this to modify their behavior in death
6965 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
6966 // implementation of death tests.  User code MUST NOT use it.
InDeathTestChild()6967 bool InDeathTestChild() {
6968 # if GTEST_OS_WINDOWS
6969 
6970   // On Windows, death tests are thread-safe regardless of the value of the
6971   // death_test_style flag.
6972   return !GTEST_FLAG(internal_run_death_test).empty();
6973 
6974 # else
6975 
6976   if (GTEST_FLAG(death_test_style) == "threadsafe")
6977     return !GTEST_FLAG(internal_run_death_test).empty();
6978   else
6979     return g_in_fast_death_test_child;
6980 #endif
6981 }
6982 
6983 }  // namespace internal
6984 
6985 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)6986 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6987 }
6988 
6989 // ExitedWithCode function-call operator.
operator ()(int exit_status) const6990 bool ExitedWithCode::operator()(int exit_status) const {
6991 # if GTEST_OS_WINDOWS
6992 
6993   return exit_status == exit_code_;
6994 
6995 # else
6996 
6997   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6998 
6999 # endif  // GTEST_OS_WINDOWS
7000 }
7001 
7002 # if !GTEST_OS_WINDOWS
7003 // KilledBySignal constructor.
KilledBySignal(int signum)7004 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
7005 }
7006 
7007 // KilledBySignal function-call operator.
operator ()(int exit_status) const7008 bool KilledBySignal::operator()(int exit_status) const {
7009 #  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7010   {
7011     bool result;
7012     if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7013       return result;
7014     }
7015   }
7016 #  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7017   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7018 }
7019 # endif  // !GTEST_OS_WINDOWS
7020 
7021 namespace internal {
7022 
7023 // Utilities needed for death tests.
7024 
7025 // Generates a textual description of a given exit code, in the format
7026 // specified by wait(2).
ExitSummary(int exit_code)7027 static std::string ExitSummary(int exit_code) {
7028   Message m;
7029 
7030 # if GTEST_OS_WINDOWS
7031 
7032   m << "Exited with exit status " << exit_code;
7033 
7034 # else
7035 
7036   if (WIFEXITED(exit_code)) {
7037     m << "Exited with exit status " << WEXITSTATUS(exit_code);
7038   } else if (WIFSIGNALED(exit_code)) {
7039     m << "Terminated by signal " << WTERMSIG(exit_code);
7040   }
7041 #  ifdef WCOREDUMP
7042   if (WCOREDUMP(exit_code)) {
7043     m << " (core dumped)";
7044   }
7045 #  endif
7046 # endif  // GTEST_OS_WINDOWS
7047 
7048   return m.GetString();
7049 }
7050 
7051 // Returns true if exit_status describes a process that was terminated
7052 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)7053 bool ExitedUnsuccessfully(int exit_status) {
7054   return !ExitedWithCode(0)(exit_status);
7055 }
7056 
7057 # if !GTEST_OS_WINDOWS
7058 // Generates a textual failure message when a death test finds more than
7059 // one thread running, or cannot determine the number of threads, prior
7060 // to executing the given statement.  It is the responsibility of the
7061 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)7062 static std::string DeathTestThreadWarning(size_t thread_count) {
7063   Message msg;
7064   msg << "Death tests use fork(), which is unsafe particularly"
7065       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
7066   if (thread_count == 0)
7067     msg << "couldn't detect the number of threads.";
7068   else
7069     msg << "detected " << thread_count << " threads.";
7070   return msg.GetString();
7071 }
7072 # endif  // !GTEST_OS_WINDOWS
7073 
7074 // Flag characters for reporting a death test that did not die.
7075 static const char kDeathTestLived = 'L';
7076 static const char kDeathTestReturned = 'R';
7077 static const char kDeathTestThrew = 'T';
7078 static const char kDeathTestInternalError = 'I';
7079 
7080 // An enumeration describing all of the possible ways that a death test can
7081 // conclude.  DIED means that the process died while executing the test
7082 // code; LIVED means that process lived beyond the end of the test code;
7083 // RETURNED means that the test statement attempted to execute a return
7084 // statement, which is not allowed; THREW means that the test statement
7085 // returned control by throwing an exception.  IN_PROGRESS means the test
7086 // has not yet concluded.
7087 // TODO(vladl@google.com): Unify names and possibly values for
7088 // AbortReason, DeathTestOutcome, and flag characters above.
7089 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7090 
7091 // Routine for aborting the program which is safe to call from an
7092 // exec-style death test child process, in which case the error
7093 // message is propagated back to the parent process.  Otherwise, the
7094 // message is simply printed to stderr.  In either case, the program
7095 // then exits with status 1.
DeathTestAbort(const std::string & message)7096 void DeathTestAbort(const std::string& message) {
7097   // On a POSIX system, this function may be called from a threadsafe-style
7098   // death test child process, which operates on a very small stack.  Use
7099   // the heap for any additional non-minuscule memory requirements.
7100   const InternalRunDeathTestFlag* const flag =
7101       GetUnitTestImpl()->internal_run_death_test_flag();
7102   if (flag != NULL) {
7103     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7104     fputc(kDeathTestInternalError, parent);
7105     fprintf(parent, "%s", message.c_str());
7106     fflush(parent);
7107     _exit(1);
7108   } else {
7109     fprintf(stderr, "%s", message.c_str());
7110     fflush(stderr);
7111     posix::Abort();
7112   }
7113 }
7114 
7115 // A replacement for CHECK that calls DeathTestAbort if the assertion
7116 // fails.
7117 # define GTEST_DEATH_TEST_CHECK_(expression) \
7118   do { \
7119     if (!::testing::internal::IsTrue(expression)) { \
7120       DeathTestAbort( \
7121           ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
7122           + ::testing::internal::StreamableToString(__LINE__) + ": " \
7123           + #expression); \
7124     } \
7125   } while (::testing::internal::AlwaysFalse())
7126 
7127 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7128 // evaluating any system call that fulfills two conditions: it must return
7129 // -1 on failure, and set errno to EINTR when it is interrupted and
7130 // should be tried again.  The macro expands to a loop that repeatedly
7131 // evaluates the expression as long as it evaluates to -1 and sets
7132 // errno to EINTR.  If the expression evaluates to -1 but errno is
7133 // something other than EINTR, DeathTestAbort is called.
7134 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7135   do { \
7136     int gtest_retval; \
7137     do { \
7138       gtest_retval = (expression); \
7139     } while (gtest_retval == -1 && errno == EINTR); \
7140     if (gtest_retval == -1) { \
7141       DeathTestAbort( \
7142           ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7143           + ::testing::internal::StreamableToString(__LINE__) + ": " \
7144           + #expression + " != -1"); \
7145     } \
7146   } while (::testing::internal::AlwaysFalse())
7147 
7148 // Returns the message describing the last system error in errno.
GetLastErrnoDescription()7149 std::string GetLastErrnoDescription() {
7150     return errno == 0 ? "" : posix::StrError(errno);
7151 }
7152 
7153 // This is called from a death test parent process to read a failure
7154 // message from the death test child process and log it with the FATAL
7155 // severity. On Windows, the message is read from a pipe handle. On other
7156 // platforms, it is read from a file descriptor.
FailFromInternalError(int fd)7157 static void FailFromInternalError(int fd) {
7158   Message error;
7159   char buffer[256];
7160   int num_read;
7161 
7162   do {
7163     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7164       buffer[num_read] = '\0';
7165       error << buffer;
7166     }
7167   } while (num_read == -1 && errno == EINTR);
7168 
7169   if (num_read == 0) {
7170     GTEST_LOG_(FATAL) << error.GetString();
7171   } else {
7172     const int last_error = errno;
7173     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7174                       << GetLastErrnoDescription() << " [" << last_error << "]";
7175   }
7176 }
7177 
7178 // Death test constructor.  Increments the running death test count
7179 // for the current test.
DeathTest()7180 DeathTest::DeathTest() {
7181   TestInfo* const info = GetUnitTestImpl()->current_test_info();
7182   if (info == NULL) {
7183     DeathTestAbort("Cannot run a death test outside of a TEST or "
7184                    "TEST_F construct");
7185   }
7186 }
7187 
7188 // Creates and returns a death test by dispatching to the current
7189 // death test factory.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)7190 bool DeathTest::Create(const char* statement, const RE* regex,
7191                        const char* file, int line, DeathTest** test) {
7192   return GetUnitTestImpl()->death_test_factory()->Create(
7193       statement, regex, file, line, test);
7194 }
7195 
LastMessage()7196 const char* DeathTest::LastMessage() {
7197   return last_death_test_message_.c_str();
7198 }
7199 
set_last_death_test_message(const std::string & message)7200 void DeathTest::set_last_death_test_message(const std::string& message) {
7201   last_death_test_message_ = message;
7202 }
7203 
7204 std::string DeathTest::last_death_test_message_;
7205 
7206 // Provides cross platform implementation for some death functionality.
7207 class DeathTestImpl : public DeathTest {
7208  protected:
DeathTestImpl(const char * a_statement,const RE * a_regex)7209   DeathTestImpl(const char* a_statement, const RE* a_regex)
7210       : statement_(a_statement),
7211         regex_(a_regex),
7212         spawned_(false),
7213         status_(-1),
7214         outcome_(IN_PROGRESS),
7215         read_fd_(-1),
7216         write_fd_(-1) {}
7217 
7218   // read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl()7219   ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7220 
7221   void Abort(AbortReason reason);
7222   virtual bool Passed(bool status_ok);
7223 
statement() const7224   const char* statement() const { return statement_; }
regex() const7225   const RE* regex() const { return regex_; }
spawned() const7226   bool spawned() const { return spawned_; }
set_spawned(bool is_spawned)7227   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
status() const7228   int status() const { return status_; }
set_status(int a_status)7229   void set_status(int a_status) { status_ = a_status; }
outcome() const7230   DeathTestOutcome outcome() const { return outcome_; }
set_outcome(DeathTestOutcome an_outcome)7231   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
read_fd() const7232   int read_fd() const { return read_fd_; }
set_read_fd(int fd)7233   void set_read_fd(int fd) { read_fd_ = fd; }
write_fd() const7234   int write_fd() const { return write_fd_; }
set_write_fd(int fd)7235   void set_write_fd(int fd) { write_fd_ = fd; }
7236 
7237   // Called in the parent process only. Reads the result code of the death
7238   // test child process via a pipe, interprets it to set the outcome_
7239   // member, and closes read_fd_.  Outputs diagnostics and terminates in
7240   // case of unexpected codes.
7241   void ReadAndInterpretStatusByte();
7242 
7243  private:
7244   // The textual content of the code this object is testing.  This class
7245   // doesn't own this string and should not attempt to delete it.
7246   const char* const statement_;
7247   // The regular expression which test output must match.  DeathTestImpl
7248   // doesn't own this object and should not attempt to delete it.
7249   const RE* const regex_;
7250   // True if the death test child process has been successfully spawned.
7251   bool spawned_;
7252   // The exit status of the child process.
7253   int status_;
7254   // How the death test concluded.
7255   DeathTestOutcome outcome_;
7256   // Descriptor to the read end of the pipe to the child process.  It is
7257   // always -1 in the child process.  The child keeps its write end of the
7258   // pipe in write_fd_.
7259   int read_fd_;
7260   // Descriptor to the child's write end of the pipe to the parent process.
7261   // It is always -1 in the parent process.  The parent keeps its end of the
7262   // pipe in read_fd_.
7263   int write_fd_;
7264 };
7265 
7266 // Called in the parent process only. Reads the result code of the death
7267 // test child process via a pipe, interprets it to set the outcome_
7268 // member, and closes read_fd_.  Outputs diagnostics and terminates in
7269 // case of unexpected codes.
ReadAndInterpretStatusByte()7270 void DeathTestImpl::ReadAndInterpretStatusByte() {
7271   char flag;
7272   int bytes_read;
7273 
7274   // The read() here blocks until data is available (signifying the
7275   // failure of the death test) or until the pipe is closed (signifying
7276   // its success), so it's okay to call this in the parent before
7277   // the child process has exited.
7278   do {
7279     bytes_read = posix::Read(read_fd(), &flag, 1);
7280   } while (bytes_read == -1 && errno == EINTR);
7281 
7282   if (bytes_read == 0) {
7283     set_outcome(DIED);
7284   } else if (bytes_read == 1) {
7285     switch (flag) {
7286       case kDeathTestReturned:
7287         set_outcome(RETURNED);
7288         break;
7289       case kDeathTestThrew:
7290         set_outcome(THREW);
7291         break;
7292       case kDeathTestLived:
7293         set_outcome(LIVED);
7294         break;
7295       case kDeathTestInternalError:
7296         FailFromInternalError(read_fd());  // Does not return.
7297         break;
7298       default:
7299         GTEST_LOG_(FATAL) << "Death test child process reported "
7300                           << "unexpected status byte ("
7301                           << static_cast<unsigned int>(flag) << ")";
7302     }
7303   } else {
7304     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
7305                       << GetLastErrnoDescription();
7306   }
7307   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
7308   set_read_fd(-1);
7309 }
7310 
7311 // Signals that the death test code which should have exited, didn't.
7312 // Should be called only in a death test child process.
7313 // Writes a status byte to the child's status file descriptor, then
7314 // calls _exit(1).
Abort(AbortReason reason)7315 void DeathTestImpl::Abort(AbortReason reason) {
7316   // The parent process considers the death test to be a failure if
7317   // it finds any data in our pipe.  So, here we write a single flag byte
7318   // to the pipe, then exit.
7319   const char status_ch =
7320       reason == TEST_DID_NOT_DIE ? kDeathTestLived :
7321       reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
7322 
7323   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
7324   // We are leaking the descriptor here because on some platforms (i.e.,
7325   // when built as Windows DLL), destructors of global objects will still
7326   // run after calling _exit(). On such systems, write_fd_ will be
7327   // indirectly closed from the destructor of UnitTestImpl, causing double
7328   // close if it is also closed here. On debug configurations, double close
7329   // may assert. As there are no in-process buffers to flush here, we are
7330   // relying on the OS to close the descriptor after the process terminates
7331   // when the destructors are not run.
7332   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
7333 }
7334 
7335 // Returns an indented copy of stderr output for a death test.
7336 // This makes distinguishing death test output lines from regular log lines
7337 // much easier.
FormatDeathTestOutput(const::std::string & output)7338 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
7339   ::std::string ret;
7340   for (size_t at = 0; ; ) {
7341     const size_t line_end = output.find('\n', at);
7342     ret += "[  DEATH   ] ";
7343     if (line_end == ::std::string::npos) {
7344       ret += output.substr(at);
7345       break;
7346     }
7347     ret += output.substr(at, line_end + 1 - at);
7348     at = line_end + 1;
7349   }
7350   return ret;
7351 }
7352 
7353 // Assesses the success or failure of a death test, using both private
7354 // members which have previously been set, and one argument:
7355 //
7356 // Private data members:
7357 //   outcome:  An enumeration describing how the death test
7358 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
7359 //             fails in the latter three cases.
7360 //   status:   The exit status of the child process. On *nix, it is in the
7361 //             in the format specified by wait(2). On Windows, this is the
7362 //             value supplied to the ExitProcess() API or a numeric code
7363 //             of the exception that terminated the program.
7364 //   regex:    A regular expression object to be applied to
7365 //             the test's captured standard error output; the death test
7366 //             fails if it does not match.
7367 //
7368 // Argument:
7369 //   status_ok: true if exit_status is acceptable in the context of
7370 //              this particular death test, which fails if it is false
7371 //
7372 // Returns true iff all of the above conditions are met.  Otherwise, the
7373 // first failing condition, in the order given above, is the one that is
7374 // reported. Also sets the last death test message string.
Passed(bool status_ok)7375 bool DeathTestImpl::Passed(bool status_ok) {
7376   if (!spawned())
7377     return false;
7378 
7379   const std::string error_message = GetCapturedStderr();
7380 
7381   bool success = false;
7382   Message buffer;
7383 
7384   buffer << "Death test: " << statement() << "\n";
7385   switch (outcome()) {
7386     case LIVED:
7387       buffer << "    Result: failed to die.\n"
7388              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7389       break;
7390     case THREW:
7391       buffer << "    Result: threw an exception.\n"
7392              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7393       break;
7394     case RETURNED:
7395       buffer << "    Result: illegal return in test statement.\n"
7396              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7397       break;
7398     case DIED:
7399       if (status_ok) {
7400         const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7401         if (matched) {
7402           success = true;
7403         } else {
7404           buffer << "    Result: died but not with expected error.\n"
7405                  << "  Expected: " << regex()->pattern() << "\n"
7406                  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7407         }
7408       } else {
7409         buffer << "    Result: died but not with expected exit code:\n"
7410                << "            " << ExitSummary(status()) << "\n"
7411                << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7412       }
7413       break;
7414     case IN_PROGRESS:
7415     default:
7416       GTEST_LOG_(FATAL)
7417           << "DeathTest::Passed somehow called before conclusion of test";
7418   }
7419 
7420   DeathTest::set_last_death_test_message(buffer.GetString());
7421   return success;
7422 }
7423 
7424 # if GTEST_OS_WINDOWS
7425 // WindowsDeathTest implements death tests on Windows. Due to the
7426 // specifics of starting new processes on Windows, death tests there are
7427 // always threadsafe, and Google Test considers the
7428 // --gtest_death_test_style=fast setting to be equivalent to
7429 // --gtest_death_test_style=threadsafe there.
7430 //
7431 // A few implementation notes:  Like the Linux version, the Windows
7432 // implementation uses pipes for child-to-parent communication. But due to
7433 // the specifics of pipes on Windows, some extra steps are required:
7434 //
7435 // 1. The parent creates a communication pipe and stores handles to both
7436 //    ends of it.
7437 // 2. The parent starts the child and provides it with the information
7438 //    necessary to acquire the handle to the write end of the pipe.
7439 // 3. The child acquires the write end of the pipe and signals the parent
7440 //    using a Windows event.
7441 // 4. Now the parent can release the write end of the pipe on its side. If
7442 //    this is done before step 3, the object's reference count goes down to
7443 //    0 and it is destroyed, preventing the child from acquiring it. The
7444 //    parent now has to release it, or read operations on the read end of
7445 //    the pipe will not return when the child terminates.
7446 // 5. The parent reads child's output through the pipe (outcome code and
7447 //    any possible error messages) from the pipe, and its stderr and then
7448 //    determines whether to fail the test.
7449 //
7450 // Note: to distinguish Win32 API calls from the local method and function
7451 // calls, the former are explicitly resolved in the global namespace.
7452 //
7453 class WindowsDeathTest : public DeathTestImpl {
7454  public:
WindowsDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)7455   WindowsDeathTest(const char* a_statement,
7456                    const RE* a_regex,
7457                    const char* file,
7458                    int line)
7459       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7460 
7461   // All of these virtual functions are inherited from DeathTest.
7462   virtual int Wait();
7463   virtual TestRole AssumeRole();
7464 
7465  private:
7466   // The name of the file in which the death test is located.
7467   const char* const file_;
7468   // The line number on which the death test is located.
7469   const int line_;
7470   // Handle to the write end of the pipe to the child process.
7471   AutoHandle write_handle_;
7472   // Child process handle.
7473   AutoHandle child_handle_;
7474   // Event the child process uses to signal the parent that it has
7475   // acquired the handle to the write end of the pipe. After seeing this
7476   // event the parent can release its own handles to make sure its
7477   // ReadFile() calls return when the child terminates.
7478   AutoHandle event_handle_;
7479 };
7480 
7481 // Waits for the child in a death test to exit, returning its exit
7482 // status, or 0 if no child process exists.  As a side effect, sets the
7483 // outcome data member.
Wait()7484 int WindowsDeathTest::Wait() {
7485   if (!spawned())
7486     return 0;
7487 
7488   // Wait until the child either signals that it has acquired the write end
7489   // of the pipe or it dies.
7490   const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7491   switch (::WaitForMultipleObjects(2,
7492                                    wait_handles,
7493                                    FALSE,  // Waits for any of the handles.
7494                                    INFINITE)) {
7495     case WAIT_OBJECT_0:
7496     case WAIT_OBJECT_0 + 1:
7497       break;
7498     default:
7499       GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
7500   }
7501 
7502   // The child has acquired the write end of the pipe or exited.
7503   // We release the handle on our side and continue.
7504   write_handle_.Reset();
7505   event_handle_.Reset();
7506 
7507   ReadAndInterpretStatusByte();
7508 
7509   // Waits for the child process to exit if it haven't already. This
7510   // returns immediately if the child has already exited, regardless of
7511   // whether previous calls to WaitForMultipleObjects synchronized on this
7512   // handle or not.
7513   GTEST_DEATH_TEST_CHECK_(
7514       WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7515                                              INFINITE));
7516   DWORD status_code;
7517   GTEST_DEATH_TEST_CHECK_(
7518       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7519   child_handle_.Reset();
7520   set_status(static_cast<int>(status_code));
7521   return status();
7522 }
7523 
7524 // The AssumeRole process for a Windows death test.  It creates a child
7525 // process with the same executable as the current process to run the
7526 // death test.  The child process is given the --gtest_filter and
7527 // --gtest_internal_run_death_test flags such that it knows to run the
7528 // current death test only.
AssumeRole()7529 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7530   const UnitTestImpl* const impl = GetUnitTestImpl();
7531   const InternalRunDeathTestFlag* const flag =
7532       impl->internal_run_death_test_flag();
7533   const TestInfo* const info = impl->current_test_info();
7534   const int death_test_index = info->result()->death_test_count();
7535 
7536   if (flag != NULL) {
7537     // ParseInternalRunDeathTestFlag() has performed all the necessary
7538     // processing.
7539     set_write_fd(flag->write_fd());
7540     return EXECUTE_TEST;
7541   }
7542 
7543   // WindowsDeathTest uses an anonymous pipe to communicate results of
7544   // a death test.
7545   SECURITY_ATTRIBUTES handles_are_inheritable = {
7546     sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7547   HANDLE read_handle, write_handle;
7548   GTEST_DEATH_TEST_CHECK_(
7549       ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7550                    0)  // Default buffer size.
7551       != FALSE);
7552   set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7553                                 O_RDONLY));
7554   write_handle_.Reset(write_handle);
7555   event_handle_.Reset(::CreateEvent(
7556       &handles_are_inheritable,
7557       TRUE,    // The event will automatically reset to non-signaled state.
7558       FALSE,   // The initial state is non-signalled.
7559       NULL));  // The even is unnamed.
7560   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7561   const std::string filter_flag =
7562       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
7563       info->test_case_name() + "." + info->name();
7564   const std::string internal_flag =
7565       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
7566       "=" + file_ + "|" + StreamableToString(line_) + "|" +
7567       StreamableToString(death_test_index) + "|" +
7568       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7569       // size_t has the same width as pointers on both 32-bit and 64-bit
7570       // Windows platforms.
7571       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7572       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
7573       "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7574 
7575   char executable_path[_MAX_PATH + 1];  // NOLINT
7576   GTEST_DEATH_TEST_CHECK_(
7577       _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7578                                             executable_path,
7579                                             _MAX_PATH));
7580 
7581   std::string command_line =
7582       std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
7583       internal_flag + "\"";
7584 
7585   DeathTest::set_last_death_test_message("");
7586 
7587   CaptureStderr();
7588   // Flush the log buffers since the log streams are shared with the child.
7589   FlushInfoLog();
7590 
7591   // The child process will share the standard handles with the parent.
7592   STARTUPINFOA startup_info;
7593   memset(&startup_info, 0, sizeof(STARTUPINFO));
7594   startup_info.dwFlags = STARTF_USESTDHANDLES;
7595   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7596   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7597   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7598 
7599   PROCESS_INFORMATION process_info;
7600   GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7601       executable_path,
7602       const_cast<char*>(command_line.c_str()),
7603       NULL,   // Retuned process handle is not inheritable.
7604       NULL,   // Retuned thread handle is not inheritable.
7605       TRUE,   // Child inherits all inheritable handles (for write_handle_).
7606       0x0,    // Default creation flags.
7607       NULL,   // Inherit the parent's environment.
7608       UnitTest::GetInstance()->original_working_dir(),
7609       &startup_info,
7610       &process_info) != FALSE);
7611   child_handle_.Reset(process_info.hProcess);
7612   ::CloseHandle(process_info.hThread);
7613   set_spawned(true);
7614   return OVERSEE_TEST;
7615 }
7616 # else  // We are not on Windows.
7617 
7618 // ForkingDeathTest provides implementations for most of the abstract
7619 // methods of the DeathTest interface.  Only the AssumeRole method is
7620 // left undefined.
7621 class ForkingDeathTest : public DeathTestImpl {
7622  public:
7623   ForkingDeathTest(const char* statement, const RE* regex);
7624 
7625   // All of these virtual functions are inherited from DeathTest.
7626   virtual int Wait();
7627 
7628  protected:
set_child_pid(pid_t child_pid)7629   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7630 
7631  private:
7632   // PID of child process during death test; 0 in the child process itself.
7633   pid_t child_pid_;
7634 };
7635 
7636 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * a_statement,const RE * a_regex)7637 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7638     : DeathTestImpl(a_statement, a_regex),
7639       child_pid_(-1) {}
7640 
7641 // Waits for the child in a death test to exit, returning its exit
7642 // status, or 0 if no child process exists.  As a side effect, sets the
7643 // outcome data member.
Wait()7644 int ForkingDeathTest::Wait() {
7645   if (!spawned())
7646     return 0;
7647 
7648   ReadAndInterpretStatusByte();
7649 
7650   int status_value;
7651   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7652   set_status(status_value);
7653   return status_value;
7654 }
7655 
7656 // A concrete death test class that forks, then immediately runs the test
7657 // in the child process.
7658 class NoExecDeathTest : public ForkingDeathTest {
7659  public:
NoExecDeathTest(const char * a_statement,const RE * a_regex)7660   NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7661       ForkingDeathTest(a_statement, a_regex) { }
7662   virtual TestRole AssumeRole();
7663 };
7664 
7665 // The AssumeRole process for a fork-and-run death test.  It implements a
7666 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()7667 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7668   const size_t thread_count = GetThreadCount();
7669   if (thread_count != 1) {
7670     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7671   }
7672 
7673   int pipe_fd[2];
7674   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7675 
7676   DeathTest::set_last_death_test_message("");
7677   CaptureStderr();
7678   // When we fork the process below, the log file buffers are copied, but the
7679   // file descriptors are shared.  We flush all log files here so that closing
7680   // the file descriptors in the child process doesn't throw off the
7681   // synchronization between descriptors and buffers in the parent process.
7682   // This is as close to the fork as possible to avoid a race condition in case
7683   // there are multiple threads running before the death test, and another
7684   // thread writes to the log file.
7685   FlushInfoLog();
7686 
7687   const pid_t child_pid = fork();
7688   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7689   set_child_pid(child_pid);
7690   if (child_pid == 0) {
7691     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7692     set_write_fd(pipe_fd[1]);
7693     // Redirects all logging to stderr in the child process to prevent
7694     // concurrent writes to the log files.  We capture stderr in the parent
7695     // process and append the child process' output to a log.
7696     LogToStderr();
7697     // Event forwarding to the listeners of event listener API mush be shut
7698     // down in death test subprocesses.
7699     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7700     g_in_fast_death_test_child = true;
7701     return EXECUTE_TEST;
7702   } else {
7703     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7704     set_read_fd(pipe_fd[0]);
7705     set_spawned(true);
7706     return OVERSEE_TEST;
7707   }
7708 }
7709 
7710 // A concrete death test class that forks and re-executes the main
7711 // program from the beginning, with command-line flags set that cause
7712 // only this specific death test to be run.
7713 class ExecDeathTest : public ForkingDeathTest {
7714  public:
ExecDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)7715   ExecDeathTest(const char* a_statement, const RE* a_regex,
7716                 const char* file, int line) :
7717       ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7718   virtual TestRole AssumeRole();
7719  private:
7720   static ::std::vector<testing::internal::string>
GetArgvsForDeathTestChildProcess()7721   GetArgvsForDeathTestChildProcess() {
7722     ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7723 #  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7724     ::std::vector<testing::internal::string> extra_args =
7725         GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
7726     args.insert(args.end(), extra_args.begin(), extra_args.end());
7727 #  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7728     return args;
7729   }
7730   // The name of the file in which the death test is located.
7731   const char* const file_;
7732   // The line number on which the death test is located.
7733   const int line_;
7734 };
7735 
7736 // Utility class for accumulating command-line arguments.
7737 class Arguments {
7738  public:
Arguments()7739   Arguments() {
7740     args_.push_back(NULL);
7741   }
7742 
~Arguments()7743   ~Arguments() {
7744     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7745          ++i) {
7746       free(*i);
7747     }
7748   }
AddArgument(const char * argument)7749   void AddArgument(const char* argument) {
7750     args_.insert(args_.end() - 1, posix::StrDup(argument));
7751   }
7752 
7753   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)7754   void AddArguments(const ::std::vector<Str>& arguments) {
7755     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7756          i != arguments.end();
7757          ++i) {
7758       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7759     }
7760   }
Argv()7761   char* const* Argv() {
7762     return &args_[0];
7763   }
7764 
7765  private:
7766   std::vector<char*> args_;
7767 };
7768 
7769 // A struct that encompasses the arguments to the child process of a
7770 // threadsafe-style death test process.
7771 struct ExecDeathTestArgs {
7772   char* const* argv;  // Command-line arguments for the child's call to exec
7773   int close_fd;       // File descriptor to close; the read end of a pipe
7774 };
7775 
7776 #  if GTEST_OS_MAC
GetEnviron()7777 inline char** GetEnviron() {
7778   // When Google Test is built as a framework on MacOS X, the environ variable
7779   // is unavailable. Apple's documentation (man environ) recommends using
7780   // _NSGetEnviron() instead.
7781   return *_NSGetEnviron();
7782 }
7783 #  else
7784 // Some POSIX platforms expect you to declare environ. extern "C" makes
7785 // it reside in the global namespace.
7786 extern "C" char** environ;
GetEnviron()7787 inline char** GetEnviron() { return environ; }
7788 #  endif  // GTEST_OS_MAC
7789 
7790 #  if !GTEST_OS_QNX
7791 // The main function for a threadsafe-style death test child process.
7792 // This function is called in a clone()-ed process and thus must avoid
7793 // any potentially unsafe operations like malloc or libc functions.
ExecDeathTestChildMain(void * child_arg)7794 static int ExecDeathTestChildMain(void* child_arg) {
7795   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7796   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7797 
7798   // We need to execute the test program in the same environment where
7799   // it was originally invoked.  Therefore we change to the original
7800   // working directory first.
7801   const char* const original_dir =
7802       UnitTest::GetInstance()->original_working_dir();
7803   // We can safely call chdir() as it's a direct system call.
7804   if (chdir(original_dir) != 0) {
7805     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7806                    GetLastErrnoDescription());
7807     return EXIT_FAILURE;
7808   }
7809 
7810   // We can safely call execve() as it's a direct system call.  We
7811   // cannot use execvp() as it's a libc function and thus potentially
7812   // unsafe.  Since execve() doesn't search the PATH, the user must
7813   // invoke the test program via a valid path that contains at least
7814   // one path separator.
7815   execve(args->argv[0], args->argv, GetEnviron());
7816   DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7817                  original_dir + " failed: " +
7818                  GetLastErrnoDescription());
7819   return EXIT_FAILURE;
7820 }
7821 #  endif  // !GTEST_OS_QNX
7822 
7823 // Two utility routines that together determine the direction the stack
7824 // grows.
7825 // This could be accomplished more elegantly by a single recursive
7826 // function, but we want to guard against the unlikely possibility of
7827 // a smart compiler optimizing the recursion away.
7828 //
7829 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7830 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7831 // correct answer.
7832 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
StackLowerThanAddress(const void * ptr,bool * result)7833 void StackLowerThanAddress(const void* ptr, bool* result) {
7834   int dummy;
7835   *result = (&dummy < ptr);
7836 }
7837 
7838 // Make sure AddressSanitizer does not tamper with the stack here.
7839 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
StackGrowsDown()7840 bool StackGrowsDown() {
7841   int dummy;
7842   bool result;
7843   StackLowerThanAddress(&dummy, &result);
7844   return result;
7845 }
7846 
7847 // Spawns a child process with the same executable as the current process in
7848 // a thread-safe manner and instructs it to run the death test.  The
7849 // implementation uses fork(2) + exec.  On systems where clone(2) is
7850 // available, it is used instead, being slightly more thread-safe.  On QNX,
7851 // fork supports only single-threaded environments, so this function uses
7852 // spawn(2) there instead.  The function dies with an error message if
7853 // anything goes wrong.
ExecDeathTestSpawnChild(char * const * argv,int close_fd)7854 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7855   ExecDeathTestArgs args = { argv, close_fd };
7856   pid_t child_pid = -1;
7857 
7858 #  if GTEST_OS_QNX
7859   // Obtains the current directory and sets it to be closed in the child
7860   // process.
7861   const int cwd_fd = open(".", O_RDONLY);
7862   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7863   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7864   // We need to execute the test program in the same environment where
7865   // it was originally invoked.  Therefore we change to the original
7866   // working directory first.
7867   const char* const original_dir =
7868       UnitTest::GetInstance()->original_working_dir();
7869   // We can safely call chdir() as it's a direct system call.
7870   if (chdir(original_dir) != 0) {
7871     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7872                    GetLastErrnoDescription());
7873     return EXIT_FAILURE;
7874   }
7875 
7876   int fd_flags;
7877   // Set close_fd to be closed after spawn.
7878   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7879   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7880                                         fd_flags | FD_CLOEXEC));
7881   struct inheritance inherit = {0};
7882   // spawn is a system call.
7883   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7884   // Restores the current working directory.
7885   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7886   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7887 
7888 #  else   // GTEST_OS_QNX
7889 #   if GTEST_OS_LINUX
7890   // When a SIGPROF signal is received while fork() or clone() are executing,
7891   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7892   // it after the call to fork()/clone() is complete.
7893   struct sigaction saved_sigprof_action;
7894   struct sigaction ignore_sigprof_action;
7895   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7896   sigemptyset(&ignore_sigprof_action.sa_mask);
7897   ignore_sigprof_action.sa_handler = SIG_IGN;
7898   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7899       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7900 #   endif  // GTEST_OS_LINUX
7901 
7902 #   if GTEST_HAS_CLONE
7903   const bool use_fork = GTEST_FLAG(death_test_use_fork);
7904 
7905   if (!use_fork) {
7906     static const bool stack_grows_down = StackGrowsDown();
7907     const size_t stack_size = getpagesize();
7908     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7909     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7910                              MAP_ANON | MAP_PRIVATE, -1, 0);
7911     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7912 
7913     // Maximum stack alignment in bytes:  For a downward-growing stack, this
7914     // amount is subtracted from size of the stack space to get an address
7915     // that is within the stack space and is aligned on all systems we care
7916     // about.  As far as I know there is no ABI with stack alignment greater
7917     // than 64.  We assume stack and stack_size already have alignment of
7918     // kMaxStackAlignment.
7919     const size_t kMaxStackAlignment = 64;
7920     void* const stack_top =
7921         static_cast<char*>(stack) +
7922             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7923     GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7924         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7925 
7926     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7927 
7928     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7929   }
7930 #   else
7931   const bool use_fork = true;
7932 #   endif  // GTEST_HAS_CLONE
7933 
7934   if (use_fork && (child_pid = fork()) == 0) {
7935       ExecDeathTestChildMain(&args);
7936       _exit(0);
7937   }
7938 #  endif  // GTEST_OS_QNX
7939 #  if GTEST_OS_LINUX
7940   GTEST_DEATH_TEST_CHECK_SYSCALL_(
7941       sigaction(SIGPROF, &saved_sigprof_action, NULL));
7942 #  endif  // GTEST_OS_LINUX
7943 
7944   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7945   return child_pid;
7946 }
7947 
7948 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
7949 // main program from the beginning, setting the --gtest_filter
7950 // and --gtest_internal_run_death_test flags to cause only the current
7951 // death test to be re-run.
AssumeRole()7952 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7953   const UnitTestImpl* const impl = GetUnitTestImpl();
7954   const InternalRunDeathTestFlag* const flag =
7955       impl->internal_run_death_test_flag();
7956   const TestInfo* const info = impl->current_test_info();
7957   const int death_test_index = info->result()->death_test_count();
7958 
7959   if (flag != NULL) {
7960     set_write_fd(flag->write_fd());
7961     return EXECUTE_TEST;
7962   }
7963 
7964   int pipe_fd[2];
7965   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7966   // Clear the close-on-exec flag on the write end of the pipe, lest
7967   // it be closed when the child process does an exec:
7968   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7969 
7970   const std::string filter_flag =
7971       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
7972       + info->test_case_name() + "." + info->name();
7973   const std::string internal_flag =
7974       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
7975       + file_ + "|" + StreamableToString(line_) + "|"
7976       + StreamableToString(death_test_index) + "|"
7977       + StreamableToString(pipe_fd[1]);
7978   Arguments args;
7979   args.AddArguments(GetArgvsForDeathTestChildProcess());
7980   args.AddArgument(filter_flag.c_str());
7981   args.AddArgument(internal_flag.c_str());
7982 
7983   DeathTest::set_last_death_test_message("");
7984 
7985   CaptureStderr();
7986   // See the comment in NoExecDeathTest::AssumeRole for why the next line
7987   // is necessary.
7988   FlushInfoLog();
7989 
7990   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7991   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7992   set_child_pid(child_pid);
7993   set_read_fd(pipe_fd[0]);
7994   set_spawned(true);
7995   return OVERSEE_TEST;
7996 }
7997 
7998 # endif  // !GTEST_OS_WINDOWS
7999 
8000 // Creates a concrete DeathTest-derived class that depends on the
8001 // --gtest_death_test_style flag, and sets the pointer pointed to
8002 // by the "test" argument to its address.  If the test should be
8003 // skipped, sets that pointer to NULL.  Returns true, unless the
8004 // flag is set to an invalid value.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)8005 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
8006                                      const char* file, int line,
8007                                      DeathTest** test) {
8008   UnitTestImpl* const impl = GetUnitTestImpl();
8009   const InternalRunDeathTestFlag* const flag =
8010       impl->internal_run_death_test_flag();
8011   const int death_test_index = impl->current_test_info()
8012       ->increment_death_test_count();
8013 
8014   if (flag != NULL) {
8015     if (death_test_index > flag->index()) {
8016       DeathTest::set_last_death_test_message(
8017           "Death test count (" + StreamableToString(death_test_index)
8018           + ") somehow exceeded expected maximum ("
8019           + StreamableToString(flag->index()) + ")");
8020       return false;
8021     }
8022 
8023     if (!(flag->file() == file && flag->line() == line &&
8024           flag->index() == death_test_index)) {
8025       *test = NULL;
8026       return true;
8027     }
8028   }
8029 
8030 # if GTEST_OS_WINDOWS
8031 
8032   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
8033       GTEST_FLAG(death_test_style) == "fast") {
8034     *test = new WindowsDeathTest(statement, regex, file, line);
8035   }
8036 
8037 # else
8038 
8039   if (GTEST_FLAG(death_test_style) == "threadsafe") {
8040     *test = new ExecDeathTest(statement, regex, file, line);
8041   } else if (GTEST_FLAG(death_test_style) == "fast") {
8042     *test = new NoExecDeathTest(statement, regex);
8043   }
8044 
8045 # endif  // GTEST_OS_WINDOWS
8046 
8047   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
8048     DeathTest::set_last_death_test_message(
8049         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
8050         + "\" encountered");
8051     return false;
8052   }
8053 
8054   return true;
8055 }
8056 
8057 # if GTEST_OS_WINDOWS
8058 // Recreates the pipe and event handles from the provided parameters,
8059 // signals the event, and returns a file descriptor wrapped around the pipe
8060 // 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)8061 int GetStatusFileDescriptor(unsigned int parent_process_id,
8062                             size_t write_handle_as_size_t,
8063                             size_t event_handle_as_size_t) {
8064   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
8065                                                    FALSE,  // Non-inheritable.
8066                                                    parent_process_id));
8067   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
8068     DeathTestAbort("Unable to open parent process " +
8069                    StreamableToString(parent_process_id));
8070   }
8071 
8072   // TODO(vladl@google.com): Replace the following check with a
8073   // compile-time assertion when available.
8074   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
8075 
8076   const HANDLE write_handle =
8077       reinterpret_cast<HANDLE>(write_handle_as_size_t);
8078   HANDLE dup_write_handle;
8079 
8080   // The newly initialized handle is accessible only in in the parent
8081   // process. To obtain one accessible within the child, we need to use
8082   // DuplicateHandle.
8083   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
8084                          ::GetCurrentProcess(), &dup_write_handle,
8085                          0x0,    // Requested privileges ignored since
8086                                  // DUPLICATE_SAME_ACCESS is used.
8087                          FALSE,  // Request non-inheritable handler.
8088                          DUPLICATE_SAME_ACCESS)) {
8089     DeathTestAbort("Unable to duplicate the pipe handle " +
8090                    StreamableToString(write_handle_as_size_t) +
8091                    " from the parent process " +
8092                    StreamableToString(parent_process_id));
8093   }
8094 
8095   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
8096   HANDLE dup_event_handle;
8097 
8098   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
8099                          ::GetCurrentProcess(), &dup_event_handle,
8100                          0x0,
8101                          FALSE,
8102                          DUPLICATE_SAME_ACCESS)) {
8103     DeathTestAbort("Unable to duplicate the event handle " +
8104                    StreamableToString(event_handle_as_size_t) +
8105                    " from the parent process " +
8106                    StreamableToString(parent_process_id));
8107   }
8108 
8109   const int write_fd =
8110       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
8111   if (write_fd == -1) {
8112     DeathTestAbort("Unable to convert pipe handle " +
8113                    StreamableToString(write_handle_as_size_t) +
8114                    " to a file descriptor");
8115   }
8116 
8117   // Signals the parent that the write end of the pipe has been acquired
8118   // so the parent can release its own write end.
8119   ::SetEvent(dup_event_handle);
8120 
8121   return write_fd;
8122 }
8123 # endif  // GTEST_OS_WINDOWS
8124 
8125 // Returns a newly created InternalRunDeathTestFlag object with fields
8126 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
8127 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()8128 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
8129   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
8130 
8131   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
8132   // can use it here.
8133   int line = -1;
8134   int index = -1;
8135   ::std::vector< ::std::string> fields;
8136   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
8137   int write_fd = -1;
8138 
8139 # if GTEST_OS_WINDOWS
8140 
8141   unsigned int parent_process_id = 0;
8142   size_t write_handle_as_size_t = 0;
8143   size_t event_handle_as_size_t = 0;
8144 
8145   if (fields.size() != 6
8146       || !ParseNaturalNumber(fields[1], &line)
8147       || !ParseNaturalNumber(fields[2], &index)
8148       || !ParseNaturalNumber(fields[3], &parent_process_id)
8149       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
8150       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
8151     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
8152                    GTEST_FLAG(internal_run_death_test));
8153   }
8154   write_fd = GetStatusFileDescriptor(parent_process_id,
8155                                      write_handle_as_size_t,
8156                                      event_handle_as_size_t);
8157 # else
8158 
8159   if (fields.size() != 4
8160       || !ParseNaturalNumber(fields[1], &line)
8161       || !ParseNaturalNumber(fields[2], &index)
8162       || !ParseNaturalNumber(fields[3], &write_fd)) {
8163     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
8164         + GTEST_FLAG(internal_run_death_test));
8165   }
8166 
8167 # endif  // GTEST_OS_WINDOWS
8168 
8169   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
8170 }
8171 
8172 }  // namespace internal
8173 
8174 #endif  // GTEST_HAS_DEATH_TEST
8175 
8176 }  // namespace testing
8177 // Copyright 2008, Google Inc.
8178 // All rights reserved.
8179 //
8180 // Redistribution and use in source and binary forms, with or without
8181 // modification, are permitted provided that the following conditions are
8182 // met:
8183 //
8184 //     * Redistributions of source code must retain the above copyright
8185 // notice, this list of conditions and the following disclaimer.
8186 //     * Redistributions in binary form must reproduce the above
8187 // copyright notice, this list of conditions and the following disclaimer
8188 // in the documentation and/or other materials provided with the
8189 // distribution.
8190 //     * Neither the name of Google Inc. nor the names of its
8191 // contributors may be used to endorse or promote products derived from
8192 // this software without specific prior written permission.
8193 //
8194 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8195 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8196 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8197 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8198 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8199 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8200 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8201 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8202 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8203 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8204 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8205 //
8206 // Authors: keith.ray@gmail.com (Keith Ray)
8207 
8208 
8209 #include <stdlib.h>
8210 
8211 #if GTEST_OS_WINDOWS_MOBILE
8212 # include <windows.h>
8213 #elif GTEST_OS_WINDOWS
8214 # include <direct.h>
8215 # include <io.h>
8216 #elif GTEST_OS_SYMBIAN
8217 // Symbian OpenC has PATH_MAX in sys/syslimits.h
8218 # include <sys/syslimits.h>
8219 #else
8220 # include <limits.h>
8221 # include <climits>  // Some Linux distributions define PATH_MAX here.
8222 #endif  // GTEST_OS_WINDOWS_MOBILE
8223 
8224 #if GTEST_OS_WINDOWS
8225 # define GTEST_PATH_MAX_ _MAX_PATH
8226 #elif defined(PATH_MAX)
8227 # define GTEST_PATH_MAX_ PATH_MAX
8228 #elif defined(_XOPEN_PATH_MAX)
8229 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
8230 #else
8231 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
8232 #endif  // GTEST_OS_WINDOWS
8233 
8234 
8235 namespace testing {
8236 namespace internal {
8237 
8238 #if GTEST_OS_WINDOWS
8239 // On Windows, '\\' is the standard path separator, but many tools and the
8240 // Windows API also accept '/' as an alternate path separator. Unless otherwise
8241 // noted, a file path can contain either kind of path separators, or a mixture
8242 // of them.
8243 const char kPathSeparator = '\\';
8244 const char kAlternatePathSeparator = '/';
8245 const char kAlternatePathSeparatorString[] = "/";
8246 # if GTEST_OS_WINDOWS_MOBILE
8247 // Windows CE doesn't have a current directory. You should not use
8248 // the current directory in tests on Windows CE, but this at least
8249 // provides a reasonable fallback.
8250 const char kCurrentDirectoryString[] = "\\";
8251 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
8252 const DWORD kInvalidFileAttributes = 0xffffffff;
8253 # else
8254 const char kCurrentDirectoryString[] = ".\\";
8255 # endif  // GTEST_OS_WINDOWS_MOBILE
8256 #else
8257 const char kPathSeparator = '/';
8258 const char kCurrentDirectoryString[] = "./";
8259 #endif  // GTEST_OS_WINDOWS
8260 
8261 // Returns whether the given character is a valid path separator.
IsPathSeparator(char c)8262 static bool IsPathSeparator(char c) {
8263 #if GTEST_HAS_ALT_PATH_SEP_
8264   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
8265 #else
8266   return c == kPathSeparator;
8267 #endif
8268 }
8269 
8270 // Returns the current working directory, or "" if unsuccessful.
GetCurrentDir()8271 FilePath FilePath::GetCurrentDir() {
8272 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
8273   // Windows CE doesn't have a current directory, so we just return
8274   // something reasonable.
8275   return FilePath(kCurrentDirectoryString);
8276 #elif GTEST_OS_WINDOWS
8277   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
8278   return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
8279 #else
8280   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
8281   char* result = getcwd(cwd, sizeof(cwd));
8282 # if GTEST_OS_NACL
8283   // getcwd will likely fail in NaCl due to the sandbox, so return something
8284   // reasonable. The user may have provided a shim implementation for getcwd,
8285   // however, so fallback only when failure is detected.
8286   return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
8287 # endif  // GTEST_OS_NACL
8288   return FilePath(result == NULL ? "" : cwd);
8289 #endif  // GTEST_OS_WINDOWS_MOBILE
8290 }
8291 
8292 // Returns a copy of the FilePath with the case-insensitive extension removed.
8293 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
8294 // FilePath("dir/file"). If a case-insensitive extension is not
8295 // found, returns a copy of the original FilePath.
RemoveExtension(const char * extension) const8296 FilePath FilePath::RemoveExtension(const char* extension) const {
8297   const std::string dot_extension = std::string(".") + extension;
8298   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
8299     return FilePath(pathname_.substr(
8300         0, pathname_.length() - dot_extension.length()));
8301   }
8302   return *this;
8303 }
8304 
8305 // Returns a pointer to the last occurence of a valid path separator in
8306 // the FilePath. On Windows, for example, both '/' and '\' are valid path
8307 // separators. Returns NULL if no path separator was found.
FindLastPathSeparator() const8308 const char* FilePath::FindLastPathSeparator() const {
8309   const char* const last_sep = strrchr(c_str(), kPathSeparator);
8310 #if GTEST_HAS_ALT_PATH_SEP_
8311   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
8312   // Comparing two pointers of which only one is NULL is undefined.
8313   if (last_alt_sep != NULL &&
8314       (last_sep == NULL || last_alt_sep > last_sep)) {
8315     return last_alt_sep;
8316   }
8317 #endif
8318   return last_sep;
8319 }
8320 
8321 // Returns a copy of the FilePath with the directory part removed.
8322 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
8323 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
8324 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
8325 // returns an empty FilePath ("").
8326 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveDirectoryName() const8327 FilePath FilePath::RemoveDirectoryName() const {
8328   const char* const last_sep = FindLastPathSeparator();
8329   return last_sep ? FilePath(last_sep + 1) : *this;
8330 }
8331 
8332 // RemoveFileName returns the directory path with the filename removed.
8333 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
8334 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
8335 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
8336 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
8337 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveFileName() const8338 FilePath FilePath::RemoveFileName() const {
8339   const char* const last_sep = FindLastPathSeparator();
8340   std::string dir;
8341   if (last_sep) {
8342     dir = std::string(c_str(), last_sep + 1 - c_str());
8343   } else {
8344     dir = kCurrentDirectoryString;
8345   }
8346   return FilePath(dir);
8347 }
8348 
8349 // Helper functions for naming files in a directory for xml output.
8350 
8351 // Given directory = "dir", base_name = "test", number = 0,
8352 // extension = "xml", returns "dir/test.xml". If number is greater
8353 // than zero (e.g., 12), returns "dir/test_12.xml".
8354 // On Windows platform, uses \ as the separator rather than /.
MakeFileName(const FilePath & directory,const FilePath & base_name,int number,const char * extension)8355 FilePath FilePath::MakeFileName(const FilePath& directory,
8356                                 const FilePath& base_name,
8357                                 int number,
8358                                 const char* extension) {
8359   std::string file;
8360   if (number == 0) {
8361     file = base_name.string() + "." + extension;
8362   } else {
8363     file = base_name.string() + "_" + StreamableToString(number)
8364         + "." + extension;
8365   }
8366   return ConcatPaths(directory, FilePath(file));
8367 }
8368 
8369 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
8370 // On Windows, uses \ as the separator rather than /.
ConcatPaths(const FilePath & directory,const FilePath & relative_path)8371 FilePath FilePath::ConcatPaths(const FilePath& directory,
8372                                const FilePath& relative_path) {
8373   if (directory.IsEmpty())
8374     return relative_path;
8375   const FilePath dir(directory.RemoveTrailingPathSeparator());
8376   return FilePath(dir.string() + kPathSeparator + relative_path.string());
8377 }
8378 
8379 // Returns true if pathname describes something findable in the file-system,
8380 // either a file, directory, or whatever.
FileOrDirectoryExists() const8381 bool FilePath::FileOrDirectoryExists() const {
8382 #if GTEST_OS_WINDOWS_MOBILE
8383   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
8384   const DWORD attributes = GetFileAttributes(unicode);
8385   delete [] unicode;
8386   return attributes != kInvalidFileAttributes;
8387 #else
8388   posix::StatStruct file_stat;
8389   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
8390 #endif  // GTEST_OS_WINDOWS_MOBILE
8391 }
8392 
8393 // Returns true if pathname describes a directory in the file-system
8394 // that exists.
DirectoryExists() const8395 bool FilePath::DirectoryExists() const {
8396   bool result = false;
8397 #if GTEST_OS_WINDOWS
8398   // Don't strip off trailing separator if path is a root directory on
8399   // Windows (like "C:\\").
8400   const FilePath& path(IsRootDirectory() ? *this :
8401                                            RemoveTrailingPathSeparator());
8402 #else
8403   const FilePath& path(*this);
8404 #endif
8405 
8406 #if GTEST_OS_WINDOWS_MOBILE
8407   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
8408   const DWORD attributes = GetFileAttributes(unicode);
8409   delete [] unicode;
8410   if ((attributes != kInvalidFileAttributes) &&
8411       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8412     result = true;
8413   }
8414 #else
8415   posix::StatStruct file_stat;
8416   result = posix::Stat(path.c_str(), &file_stat) == 0 &&
8417       posix::IsDir(file_stat);
8418 #endif  // GTEST_OS_WINDOWS_MOBILE
8419 
8420   return result;
8421 }
8422 
8423 // Returns true if pathname describes a root directory. (Windows has one
8424 // root directory per disk drive.)
IsRootDirectory() const8425 bool FilePath::IsRootDirectory() const {
8426 #if GTEST_OS_WINDOWS
8427   // TODO(wan@google.com): on Windows a network share like
8428   // \\server\share can be a root directory, although it cannot be the
8429   // current directory.  Handle this properly.
8430   return pathname_.length() == 3 && IsAbsolutePath();
8431 #else
8432   return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
8433 #endif
8434 }
8435 
8436 // Returns true if pathname describes an absolute path.
IsAbsolutePath() const8437 bool FilePath::IsAbsolutePath() const {
8438   const char* const name = pathname_.c_str();
8439 #if GTEST_OS_WINDOWS
8440   return pathname_.length() >= 3 &&
8441      ((name[0] >= 'a' && name[0] <= 'z') ||
8442       (name[0] >= 'A' && name[0] <= 'Z')) &&
8443      name[1] == ':' &&
8444      IsPathSeparator(name[2]);
8445 #else
8446   return IsPathSeparator(name[0]);
8447 #endif
8448 }
8449 
8450 // Returns a pathname for a file that does not currently exist. The pathname
8451 // will be directory/base_name.extension or
8452 // directory/base_name_<number>.extension if directory/base_name.extension
8453 // already exists. The number will be incremented until a pathname is found
8454 // that does not already exist.
8455 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8456 // There could be a race condition if two or more processes are calling this
8457 // function at the same time -- they could both pick the same filename.
GenerateUniqueFileName(const FilePath & directory,const FilePath & base_name,const char * extension)8458 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
8459                                           const FilePath& base_name,
8460                                           const char* extension) {
8461   FilePath full_pathname;
8462   int number = 0;
8463   do {
8464     full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
8465   } while (full_pathname.FileOrDirectoryExists());
8466   return full_pathname;
8467 }
8468 
8469 // Returns true if FilePath ends with a path separator, which indicates that
8470 // it is intended to represent a directory. Returns false otherwise.
8471 // This does NOT check that a directory (or file) actually exists.
IsDirectory() const8472 bool FilePath::IsDirectory() const {
8473   return !pathname_.empty() &&
8474          IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
8475 }
8476 
8477 // Create directories so that path exists. Returns true if successful or if
8478 // the directories already exist; returns false if unable to create directories
8479 // for any reason.
CreateDirectoriesRecursively() const8480 bool FilePath::CreateDirectoriesRecursively() const {
8481   if (!this->IsDirectory()) {
8482     return false;
8483   }
8484 
8485   if (pathname_.length() == 0 || this->DirectoryExists()) {
8486     return true;
8487   }
8488 
8489   const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8490   return parent.CreateDirectoriesRecursively() && this->CreateFolder();
8491 }
8492 
8493 // Create the directory so that path exists. Returns true if successful or
8494 // if the directory already exists; returns false if unable to create the
8495 // directory for any reason, including if the parent directory does not
8496 // exist. Not named "CreateDirectory" because that's a macro on Windows.
CreateFolder() const8497 bool FilePath::CreateFolder() const {
8498 #if GTEST_OS_WINDOWS_MOBILE
8499   FilePath removed_sep(this->RemoveTrailingPathSeparator());
8500   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8501   int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8502   delete [] unicode;
8503 #elif GTEST_OS_WINDOWS
8504   int result = _mkdir(pathname_.c_str());
8505 #else
8506   int result = mkdir(pathname_.c_str(), 0777);
8507 #endif  // GTEST_OS_WINDOWS_MOBILE
8508 
8509   if (result == -1) {
8510     return this->DirectoryExists();  // An error is OK if the directory exists.
8511   }
8512   return true;  // No error.
8513 }
8514 
8515 // If input name has a trailing separator character, remove it and return the
8516 // name, otherwise return the name string unmodified.
8517 // On Windows platform, uses \ as the separator, other platforms use /.
RemoveTrailingPathSeparator() const8518 FilePath FilePath::RemoveTrailingPathSeparator() const {
8519   return IsDirectory()
8520       ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8521       : *this;
8522 }
8523 
8524 // Removes any redundant separators that might be in the pathname.
8525 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8526 // redundancies that might be in a pathname involving "." or "..".
8527 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
Normalize()8528 void FilePath::Normalize() {
8529   if (pathname_.c_str() == NULL) {
8530     pathname_ = "";
8531     return;
8532   }
8533   const char* src = pathname_.c_str();
8534   char* const dest = new char[pathname_.length() + 1];
8535   char* dest_ptr = dest;
8536   memset(dest_ptr, 0, pathname_.length() + 1);
8537 
8538   while (*src != '\0') {
8539     *dest_ptr = *src;
8540     if (!IsPathSeparator(*src)) {
8541       src++;
8542     } else {
8543 #if GTEST_HAS_ALT_PATH_SEP_
8544       if (*dest_ptr == kAlternatePathSeparator) {
8545         *dest_ptr = kPathSeparator;
8546       }
8547 #endif
8548       while (IsPathSeparator(*src))
8549         src++;
8550     }
8551     dest_ptr++;
8552   }
8553   *dest_ptr = '\0';
8554   pathname_ = dest;
8555   delete[] dest;
8556 }
8557 
8558 }  // namespace internal
8559 }  // namespace testing
8560 // Copyright 2008, Google Inc.
8561 // All rights reserved.
8562 //
8563 // Redistribution and use in source and binary forms, with or without
8564 // modification, are permitted provided that the following conditions are
8565 // met:
8566 //
8567 //     * Redistributions of source code must retain the above copyright
8568 // notice, this list of conditions and the following disclaimer.
8569 //     * Redistributions in binary form must reproduce the above
8570 // copyright notice, this list of conditions and the following disclaimer
8571 // in the documentation and/or other materials provided with the
8572 // distribution.
8573 //     * Neither the name of Google Inc. nor the names of its
8574 // contributors may be used to endorse or promote products derived from
8575 // this software without specific prior written permission.
8576 //
8577 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8578 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8579 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8580 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8581 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8582 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8583 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8584 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8585 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8586 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8587 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8588 //
8589 // Author: wan@google.com (Zhanyong Wan)
8590 
8591 
8592 #include <limits.h>
8593 #include <stdlib.h>
8594 #include <stdio.h>
8595 #include <string.h>
8596 #include <fstream>
8597 
8598 #if GTEST_OS_WINDOWS
8599 # include <windows.h>
8600 # include <io.h>
8601 # include <sys/stat.h>
8602 # include <map>  // Used in ThreadLocal.
8603 #else
8604 # include <unistd.h>
8605 #endif  // GTEST_OS_WINDOWS
8606 
8607 #if GTEST_OS_MAC
8608 # include <mach/mach_init.h>
8609 # include <mach/task.h>
8610 # include <mach/vm_map.h>
8611 #endif  // GTEST_OS_MAC
8612 
8613 #if GTEST_OS_QNX
8614 # include <devctl.h>
8615 # include <fcntl.h>
8616 # include <sys/procfs.h>
8617 #endif  // GTEST_OS_QNX
8618 
8619 #if GTEST_OS_AIX
8620 # include <procinfo.h>
8621 # include <sys/types.h>
8622 #endif  // GTEST_OS_AIX
8623 
8624 
8625 // Indicates that this translation unit is part of Google Test's
8626 // implementation.  It must come before gtest-internal-inl.h is
8627 // included, or there will be a compiler error.  This trick exists to
8628 // prevent the accidental inclusion of gtest-internal-inl.h in the
8629 // user's code.
8630 #define GTEST_IMPLEMENTATION_ 1
8631 #undef GTEST_IMPLEMENTATION_
8632 
8633 namespace testing {
8634 namespace internal {
8635 
8636 #if defined(_MSC_VER) || defined(__BORLANDC__)
8637 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8638 const int kStdOutFileno = 1;
8639 const int kStdErrFileno = 2;
8640 #else
8641 const int kStdOutFileno = STDOUT_FILENO;
8642 const int kStdErrFileno = STDERR_FILENO;
8643 #endif  // _MSC_VER
8644 
8645 #if GTEST_OS_LINUX
8646 
8647 namespace {
8648 template <typename T>
ReadProcFileField(const string & filename,int field)8649 T ReadProcFileField(const string& filename, int field) {
8650   std::string dummy;
8651   std::ifstream file(filename.c_str());
8652   while (field-- > 0) {
8653     file >> dummy;
8654   }
8655   T output = 0;
8656   file >> output;
8657   return output;
8658 }
8659 }  // namespace
8660 
8661 // Returns the number of active threads, or 0 when there is an error.
GetThreadCount()8662 size_t GetThreadCount() {
8663   const string filename =
8664       (Message() << "/proc/" << getpid() << "/stat").GetString();
8665   return ReadProcFileField<int>(filename, 19);
8666 }
8667 
8668 #elif GTEST_OS_MAC
8669 
GetThreadCount()8670 size_t GetThreadCount() {
8671   const task_t task = mach_task_self();
8672   mach_msg_type_number_t thread_count;
8673   thread_act_array_t thread_list;
8674   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8675   if (status == KERN_SUCCESS) {
8676     // task_threads allocates resources in thread_list and we need to free them
8677     // to avoid leaks.
8678     vm_deallocate(task,
8679                   reinterpret_cast<vm_address_t>(thread_list),
8680                   sizeof(thread_t) * thread_count);
8681     return static_cast<size_t>(thread_count);
8682   } else {
8683     return 0;
8684   }
8685 }
8686 
8687 #elif GTEST_OS_QNX
8688 
8689 // Returns the number of threads running in the process, or 0 to indicate that
8690 // we cannot detect it.
GetThreadCount()8691 size_t GetThreadCount() {
8692   const int fd = open("/proc/self/as", O_RDONLY);
8693   if (fd < 0) {
8694     return 0;
8695   }
8696   procfs_info process_info;
8697   const int status =
8698       devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8699   close(fd);
8700   if (status == EOK) {
8701     return static_cast<size_t>(process_info.num_threads);
8702   } else {
8703     return 0;
8704   }
8705 }
8706 
8707 #elif GTEST_OS_AIX
8708 
GetThreadCount()8709 size_t GetThreadCount() {
8710   struct procentry64 entry;
8711   pid_t pid = getpid();
8712   int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
8713   if (status == 1) {
8714     return entry.pi_thcount;
8715   } else {
8716     return 0;
8717   }
8718 }
8719 
8720 #else
8721 
GetThreadCount()8722 size_t GetThreadCount() {
8723   // There's no portable way to detect the number of threads, so we just
8724   // return 0 to indicate that we cannot detect it.
8725   return 0;
8726 }
8727 
8728 #endif  // GTEST_OS_LINUX
8729 
8730 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
8731 
SleepMilliseconds(int n)8732 void SleepMilliseconds(int n) {
8733   ::Sleep(n);
8734 }
8735 
AutoHandle()8736 AutoHandle::AutoHandle()
8737     : handle_(INVALID_HANDLE_VALUE) {}
8738 
AutoHandle(Handle handle)8739 AutoHandle::AutoHandle(Handle handle)
8740     : handle_(handle) {}
8741 
~AutoHandle()8742 AutoHandle::~AutoHandle() {
8743   Reset();
8744 }
8745 
Get() const8746 AutoHandle::Handle AutoHandle::Get() const {
8747   return handle_;
8748 }
8749 
Reset()8750 void AutoHandle::Reset() {
8751   Reset(INVALID_HANDLE_VALUE);
8752 }
8753 
Reset(HANDLE handle)8754 void AutoHandle::Reset(HANDLE handle) {
8755   // Resetting with the same handle we already own is invalid.
8756   if (handle_ != handle) {
8757     if (IsCloseable()) {
8758       ::CloseHandle(handle_);
8759     }
8760     handle_ = handle;
8761   } else {
8762     GTEST_CHECK_(!IsCloseable())
8763         << "Resetting a valid handle to itself is likely a programmer error "
8764             "and thus not allowed.";
8765   }
8766 }
8767 
IsCloseable() const8768 bool AutoHandle::IsCloseable() const {
8769   // Different Windows APIs may use either of these values to represent an
8770   // invalid handle.
8771   return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
8772 }
8773 
Notification()8774 Notification::Notification()
8775     : event_(::CreateEvent(NULL,   // Default security attributes.
8776                            TRUE,   // Do not reset automatically.
8777                            FALSE,  // Initially unset.
8778                            NULL)) {  // Anonymous event.
8779   GTEST_CHECK_(event_.Get() != NULL);
8780 }
8781 
Notify()8782 void Notification::Notify() {
8783   GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
8784 }
8785 
WaitForNotification()8786 void Notification::WaitForNotification() {
8787   GTEST_CHECK_(
8788       ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
8789 }
8790 
Mutex()8791 Mutex::Mutex()
8792     : owner_thread_id_(0),
8793       type_(kDynamic),
8794       critical_section_init_phase_(0),
8795       critical_section_(new CRITICAL_SECTION) {
8796   ::InitializeCriticalSection(critical_section_);
8797 }
8798 
~Mutex()8799 Mutex::~Mutex() {
8800   // Static mutexes are leaked intentionally. It is not thread-safe to try
8801   // to clean them up.
8802   // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
8803   // nothing to clean it up but is available only on Vista and later.
8804   // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
8805   if (type_ == kDynamic) {
8806     ::DeleteCriticalSection(critical_section_);
8807     delete critical_section_;
8808     critical_section_ = NULL;
8809   }
8810 }
8811 
Lock()8812 void Mutex::Lock() {
8813   ThreadSafeLazyInit();
8814   ::EnterCriticalSection(critical_section_);
8815   owner_thread_id_ = ::GetCurrentThreadId();
8816 }
8817 
Unlock()8818 void Mutex::Unlock() {
8819   ThreadSafeLazyInit();
8820   // We don't protect writing to owner_thread_id_ here, as it's the
8821   // caller's responsibility to ensure that the current thread holds the
8822   // mutex when this is called.
8823   owner_thread_id_ = 0;
8824   ::LeaveCriticalSection(critical_section_);
8825 }
8826 
8827 // Does nothing if the current thread holds the mutex. Otherwise, crashes
8828 // with high probability.
AssertHeld()8829 void Mutex::AssertHeld() {
8830   ThreadSafeLazyInit();
8831   GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
8832       << "The current thread is not holding the mutex @" << this;
8833 }
8834 
8835 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
ThreadSafeLazyInit()8836 void Mutex::ThreadSafeLazyInit() {
8837   // Dynamic mutexes are initialized in the constructor.
8838   if (type_ == kStatic) {
8839     switch (
8840         ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
8841       case 0:
8842         // If critical_section_init_phase_ was 0 before the exchange, we
8843         // are the first to test it and need to perform the initialization.
8844         owner_thread_id_ = 0;
8845         critical_section_ = new CRITICAL_SECTION;
8846         ::InitializeCriticalSection(critical_section_);
8847         // Updates the critical_section_init_phase_ to 2 to signal
8848         // initialization complete.
8849         GTEST_CHECK_(::InterlockedCompareExchange(
8850                           &critical_section_init_phase_, 2L, 1L) ==
8851                       1L);
8852         break;
8853       case 1:
8854         // Somebody else is already initializing the mutex; spin until they
8855         // are done.
8856         while (::InterlockedCompareExchange(&critical_section_init_phase_,
8857                                             2L,
8858                                             2L) != 2L) {
8859           // Possibly yields the rest of the thread's time slice to other
8860           // threads.
8861           ::Sleep(0);
8862         }
8863         break;
8864 
8865       case 2:
8866         break;  // The mutex is already initialized and ready for use.
8867 
8868       default:
8869         GTEST_CHECK_(false)
8870             << "Unexpected value of critical_section_init_phase_ "
8871             << "while initializing a static mutex.";
8872     }
8873   }
8874 }
8875 
8876 namespace {
8877 
8878 class ThreadWithParamSupport : public ThreadWithParamBase {
8879  public:
CreateThread(Runnable * runnable,Notification * thread_can_start)8880   static HANDLE CreateThread(Runnable* runnable,
8881                              Notification* thread_can_start) {
8882     ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
8883     DWORD thread_id;
8884     // TODO(yukawa): Consider to use _beginthreadex instead.
8885     HANDLE thread_handle = ::CreateThread(
8886         NULL,    // Default security.
8887         0,       // Default stack size.
8888         &ThreadWithParamSupport::ThreadMain,
8889         param,   // Parameter to ThreadMainStatic
8890         0x0,     // Default creation flags.
8891         &thread_id);  // Need a valid pointer for the call to work under Win98.
8892     GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
8893                                         << ::GetLastError() << ".";
8894     if (thread_handle == NULL) {
8895       delete param;
8896     }
8897     return thread_handle;
8898   }
8899 
8900  private:
8901   struct ThreadMainParam {
ThreadMainParamtesting::internal::__anon383eb6e80911::ThreadWithParamSupport::ThreadMainParam8902     ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
8903         : runnable_(runnable),
8904           thread_can_start_(thread_can_start) {
8905     }
8906     scoped_ptr<Runnable> runnable_;
8907     // Does not own.
8908     Notification* thread_can_start_;
8909   };
8910 
ThreadMain(void * ptr)8911   static DWORD WINAPI ThreadMain(void* ptr) {
8912     // Transfers ownership.
8913     scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
8914     if (param->thread_can_start_ != NULL)
8915       param->thread_can_start_->WaitForNotification();
8916     param->runnable_->Run();
8917     return 0;
8918   }
8919 
8920   // Prohibit instantiation.
8921   ThreadWithParamSupport();
8922 
8923   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
8924 };
8925 
8926 }  // namespace
8927 
ThreadWithParamBase(Runnable * runnable,Notification * thread_can_start)8928 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
8929                                          Notification* thread_can_start)
8930       : thread_(ThreadWithParamSupport::CreateThread(runnable,
8931                                                      thread_can_start)) {
8932 }
8933 
~ThreadWithParamBase()8934 ThreadWithParamBase::~ThreadWithParamBase() {
8935   Join();
8936 }
8937 
Join()8938 void ThreadWithParamBase::Join() {
8939   GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
8940       << "Failed to join the thread with error " << ::GetLastError() << ".";
8941 }
8942 
8943 // Maps a thread to a set of ThreadIdToThreadLocals that have values
8944 // instantiated on that thread and notifies them when the thread exits.  A
8945 // ThreadLocal instance is expected to persist until all threads it has
8946 // values on have terminated.
8947 class ThreadLocalRegistryImpl {
8948  public:
8949   // Registers thread_local_instance as having value on the current thread.
8950   // Returns a value that can be used to identify the thread from other threads.
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)8951   static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
8952       const ThreadLocalBase* thread_local_instance) {
8953     DWORD current_thread = ::GetCurrentThreadId();
8954     MutexLock lock(&mutex_);
8955     ThreadIdToThreadLocals* const thread_to_thread_locals =
8956         GetThreadLocalsMapLocked();
8957     ThreadIdToThreadLocals::iterator thread_local_pos =
8958         thread_to_thread_locals->find(current_thread);
8959     if (thread_local_pos == thread_to_thread_locals->end()) {
8960       thread_local_pos = thread_to_thread_locals->insert(
8961           std::make_pair(current_thread, ThreadLocalValues())).first;
8962       StartWatcherThreadFor(current_thread);
8963     }
8964     ThreadLocalValues& thread_local_values = thread_local_pos->second;
8965     ThreadLocalValues::iterator value_pos =
8966         thread_local_values.find(thread_local_instance);
8967     if (value_pos == thread_local_values.end()) {
8968       value_pos =
8969           thread_local_values
8970               .insert(std::make_pair(
8971                   thread_local_instance,
8972                   linked_ptr<ThreadLocalValueHolderBase>(
8973                       thread_local_instance->NewValueForCurrentThread())))
8974               .first;
8975     }
8976     return value_pos->second.get();
8977   }
8978 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)8979   static void OnThreadLocalDestroyed(
8980       const ThreadLocalBase* thread_local_instance) {
8981     std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
8982     // Clean up the ThreadLocalValues data structure while holding the lock, but
8983     // defer the destruction of the ThreadLocalValueHolderBases.
8984     {
8985       MutexLock lock(&mutex_);
8986       ThreadIdToThreadLocals* const thread_to_thread_locals =
8987           GetThreadLocalsMapLocked();
8988       for (ThreadIdToThreadLocals::iterator it =
8989           thread_to_thread_locals->begin();
8990           it != thread_to_thread_locals->end();
8991           ++it) {
8992         ThreadLocalValues& thread_local_values = it->second;
8993         ThreadLocalValues::iterator value_pos =
8994             thread_local_values.find(thread_local_instance);
8995         if (value_pos != thread_local_values.end()) {
8996           value_holders.push_back(value_pos->second);
8997           thread_local_values.erase(value_pos);
8998           // This 'if' can only be successful at most once, so theoretically we
8999           // could break out of the loop here, but we don't bother doing so.
9000         }
9001       }
9002     }
9003     // Outside the lock, let the destructor for 'value_holders' deallocate the
9004     // ThreadLocalValueHolderBases.
9005   }
9006 
OnThreadExit(DWORD thread_id)9007   static void OnThreadExit(DWORD thread_id) {
9008     GTEST_CHECK_(thread_id != 0) << ::GetLastError();
9009     std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
9010     // Clean up the ThreadIdToThreadLocals data structure while holding the
9011     // lock, but defer the destruction of the ThreadLocalValueHolderBases.
9012     {
9013       MutexLock lock(&mutex_);
9014       ThreadIdToThreadLocals* const thread_to_thread_locals =
9015           GetThreadLocalsMapLocked();
9016       ThreadIdToThreadLocals::iterator thread_local_pos =
9017           thread_to_thread_locals->find(thread_id);
9018       if (thread_local_pos != thread_to_thread_locals->end()) {
9019         ThreadLocalValues& thread_local_values = thread_local_pos->second;
9020         for (ThreadLocalValues::iterator value_pos =
9021             thread_local_values.begin();
9022             value_pos != thread_local_values.end();
9023             ++value_pos) {
9024           value_holders.push_back(value_pos->second);
9025         }
9026         thread_to_thread_locals->erase(thread_local_pos);
9027       }
9028     }
9029     // Outside the lock, let the destructor for 'value_holders' deallocate the
9030     // ThreadLocalValueHolderBases.
9031   }
9032 
9033  private:
9034   // In a particular thread, maps a ThreadLocal object to its value.
9035   typedef std::map<const ThreadLocalBase*,
9036                    linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
9037   // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
9038   // thread's ID.
9039   typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
9040 
9041   // Holds the thread id and thread handle that we pass from
9042   // StartWatcherThreadFor to WatcherThreadFunc.
9043   typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
9044 
StartWatcherThreadFor(DWORD thread_id)9045   static void StartWatcherThreadFor(DWORD thread_id) {
9046     // The returned handle will be kept in thread_map and closed by
9047     // watcher_thread in WatcherThreadFunc.
9048     HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
9049                                  FALSE,
9050                                  thread_id);
9051     GTEST_CHECK_(thread != NULL);
9052     // We need to to pass a valid thread ID pointer into CreateThread for it
9053     // to work correctly under Win98.
9054     DWORD watcher_thread_id;
9055     HANDLE watcher_thread = ::CreateThread(
9056         NULL,   // Default security.
9057         0,      // Default stack size
9058         &ThreadLocalRegistryImpl::WatcherThreadFunc,
9059         reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
9060         CREATE_SUSPENDED,
9061         &watcher_thread_id);
9062     GTEST_CHECK_(watcher_thread != NULL);
9063     // Give the watcher thread the same priority as ours to avoid being
9064     // blocked by it.
9065     ::SetThreadPriority(watcher_thread,
9066                         ::GetThreadPriority(::GetCurrentThread()));
9067     ::ResumeThread(watcher_thread);
9068     ::CloseHandle(watcher_thread);
9069   }
9070 
9071   // Monitors exit from a given thread and notifies those
9072   // ThreadIdToThreadLocals about thread termination.
WatcherThreadFunc(LPVOID param)9073   static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
9074     const ThreadIdAndHandle* tah =
9075         reinterpret_cast<const ThreadIdAndHandle*>(param);
9076     GTEST_CHECK_(
9077         ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
9078     OnThreadExit(tah->first);
9079     ::CloseHandle(tah->second);
9080     delete tah;
9081     return 0;
9082   }
9083 
9084   // Returns map of thread local instances.
GetThreadLocalsMapLocked()9085   static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
9086     mutex_.AssertHeld();
9087     static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;
9088     return map;
9089   }
9090 
9091   // Protects access to GetThreadLocalsMapLocked() and its return value.
9092   static Mutex mutex_;
9093   // Protects access to GetThreadMapLocked() and its return value.
9094   static Mutex thread_map_mutex_;
9095 };
9096 
9097 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
9098 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
9099 
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)9100 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
9101       const ThreadLocalBase* thread_local_instance) {
9102   return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
9103       thread_local_instance);
9104 }
9105 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)9106 void ThreadLocalRegistry::OnThreadLocalDestroyed(
9107       const ThreadLocalBase* thread_local_instance) {
9108   ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
9109 }
9110 
9111 #endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9112 
9113 #if GTEST_USES_POSIX_RE
9114 
9115 // Implements RE.  Currently only needed for death tests.
9116 
~RE()9117 RE::~RE() {
9118   if (is_valid_) {
9119     // regfree'ing an invalid regex might crash because the content
9120     // of the regex is undefined. Since the regex's are essentially
9121     // the same, one cannot be valid (or invalid) without the other
9122     // being so too.
9123     regfree(&partial_regex_);
9124     regfree(&full_regex_);
9125   }
9126   free(const_cast<char*>(pattern_));
9127 }
9128 
9129 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)9130 bool RE::FullMatch(const char* str, const RE& re) {
9131   if (!re.is_valid_) return false;
9132 
9133   regmatch_t match;
9134   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
9135 }
9136 
9137 // Returns true iff regular expression re matches a substring of str
9138 // (including str itself).
PartialMatch(const char * str,const RE & re)9139 bool RE::PartialMatch(const char* str, const RE& re) {
9140   if (!re.is_valid_) return false;
9141 
9142   regmatch_t match;
9143   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
9144 }
9145 
9146 // Initializes an RE from its string representation.
Init(const char * regex)9147 void RE::Init(const char* regex) {
9148   pattern_ = posix::StrDup(regex);
9149 
9150   // Reserves enough bytes to hold the regular expression used for a
9151   // full match.
9152   const size_t full_regex_len = strlen(regex) + 10;
9153   char* const full_pattern = new char[full_regex_len];
9154 
9155   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
9156   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
9157   // We want to call regcomp(&partial_regex_, ...) even if the
9158   // previous expression returns false.  Otherwise partial_regex_ may
9159   // not be properly initialized can may cause trouble when it's
9160   // freed.
9161   //
9162   // Some implementation of POSIX regex (e.g. on at least some
9163   // versions of Cygwin) doesn't accept the empty string as a valid
9164   // regex.  We change it to an equivalent form "()" to be safe.
9165   if (is_valid_) {
9166     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
9167     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
9168   }
9169   EXPECT_TRUE(is_valid_)
9170       << "Regular expression \"" << regex
9171       << "\" is not a valid POSIX Extended regular expression.";
9172 
9173   delete[] full_pattern;
9174 }
9175 
9176 #elif GTEST_USES_SIMPLE_RE
9177 
9178 // Returns true iff ch appears anywhere in str (excluding the
9179 // terminating '\0' character).
IsInSet(char ch,const char * str)9180 bool IsInSet(char ch, const char* str) {
9181   return ch != '\0' && strchr(str, ch) != NULL;
9182 }
9183 
9184 // Returns true iff ch belongs to the given classification.  Unlike
9185 // similar functions in <ctype.h>, these aren't affected by the
9186 // current locale.
IsAsciiDigit(char ch)9187 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)9188 bool IsAsciiPunct(char ch) {
9189   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
9190 }
IsRepeat(char ch)9191 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)9192 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)9193 bool IsAsciiWordChar(char ch) {
9194   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
9195       ('0' <= ch && ch <= '9') || ch == '_';
9196 }
9197 
9198 // Returns true iff "\\c" is a supported escape sequence.
IsValidEscape(char c)9199 bool IsValidEscape(char c) {
9200   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
9201 }
9202 
9203 // Returns true iff the given atom (specified by escaped and pattern)
9204 // matches ch.  The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)9205 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
9206   if (escaped) {  // "\\p" where p is pattern_char.
9207     switch (pattern_char) {
9208       case 'd': return IsAsciiDigit(ch);
9209       case 'D': return !IsAsciiDigit(ch);
9210       case 'f': return ch == '\f';
9211       case 'n': return ch == '\n';
9212       case 'r': return ch == '\r';
9213       case 's': return IsAsciiWhiteSpace(ch);
9214       case 'S': return !IsAsciiWhiteSpace(ch);
9215       case 't': return ch == '\t';
9216       case 'v': return ch == '\v';
9217       case 'w': return IsAsciiWordChar(ch);
9218       case 'W': return !IsAsciiWordChar(ch);
9219     }
9220     return IsAsciiPunct(pattern_char) && pattern_char == ch;
9221   }
9222 
9223   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
9224 }
9225 
9226 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)9227 std::string FormatRegexSyntaxError(const char* regex, int index) {
9228   return (Message() << "Syntax error at index " << index
9229           << " in simple regular expression \"" << regex << "\": ").GetString();
9230 }
9231 
9232 // Generates non-fatal failures and returns false if regex is invalid;
9233 // otherwise returns true.
ValidateRegex(const char * regex)9234 bool ValidateRegex(const char* regex) {
9235   if (regex == NULL) {
9236     // TODO(wan@google.com): fix the source file location in the
9237     // assertion failures to match where the regex is used in user
9238     // code.
9239     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
9240     return false;
9241   }
9242 
9243   bool is_valid = true;
9244 
9245   // True iff ?, *, or + can follow the previous atom.
9246   bool prev_repeatable = false;
9247   for (int i = 0; regex[i]; i++) {
9248     if (regex[i] == '\\') {  // An escape sequence
9249       i++;
9250       if (regex[i] == '\0') {
9251         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9252                       << "'\\' cannot appear at the end.";
9253         return false;
9254       }
9255 
9256       if (!IsValidEscape(regex[i])) {
9257         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9258                       << "invalid escape sequence \"\\" << regex[i] << "\".";
9259         is_valid = false;
9260       }
9261       prev_repeatable = true;
9262     } else {  // Not an escape sequence.
9263       const char ch = regex[i];
9264 
9265       if (ch == '^' && i > 0) {
9266         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9267                       << "'^' can only appear at the beginning.";
9268         is_valid = false;
9269       } else if (ch == '$' && regex[i + 1] != '\0') {
9270         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9271                       << "'$' can only appear at the end.";
9272         is_valid = false;
9273       } else if (IsInSet(ch, "()[]{}|")) {
9274         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9275                       << "'" << ch << "' is unsupported.";
9276         is_valid = false;
9277       } else if (IsRepeat(ch) && !prev_repeatable) {
9278         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9279                       << "'" << ch << "' can only follow a repeatable token.";
9280         is_valid = false;
9281       }
9282 
9283       prev_repeatable = !IsInSet(ch, "^$?*+");
9284     }
9285   }
9286 
9287   return is_valid;
9288 }
9289 
9290 // Matches a repeated regex atom followed by a valid simple regular
9291 // expression.  The regex atom is defined as c if escaped is false,
9292 // or \c otherwise.  repeat is the repetition meta character (?, *,
9293 // or +).  The behavior is undefined if str contains too many
9294 // characters to be indexable by size_t, in which case the test will
9295 // probably time out anyway.  We are fine with this limitation as
9296 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)9297 bool MatchRepetitionAndRegexAtHead(
9298     bool escaped, char c, char repeat, const char* regex,
9299     const char* str) {
9300   const size_t min_count = (repeat == '+') ? 1 : 0;
9301   const size_t max_count = (repeat == '?') ? 1 :
9302       static_cast<size_t>(-1) - 1;
9303   // We cannot call numeric_limits::max() as it conflicts with the
9304   // max() macro on Windows.
9305 
9306   for (size_t i = 0; i <= max_count; ++i) {
9307     // We know that the atom matches each of the first i characters in str.
9308     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
9309       // We have enough matches at the head, and the tail matches too.
9310       // Since we only care about *whether* the pattern matches str
9311       // (as opposed to *how* it matches), there is no need to find a
9312       // greedy match.
9313       return true;
9314     }
9315     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
9316       return false;
9317   }
9318   return false;
9319 }
9320 
9321 // Returns true iff regex matches a prefix of str.  regex must be a
9322 // valid simple regular expression and not start with "^", or the
9323 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)9324 bool MatchRegexAtHead(const char* regex, const char* str) {
9325   if (*regex == '\0')  // An empty regex matches a prefix of anything.
9326     return true;
9327 
9328   // "$" only matches the end of a string.  Note that regex being
9329   // valid guarantees that there's nothing after "$" in it.
9330   if (*regex == '$')
9331     return *str == '\0';
9332 
9333   // Is the first thing in regex an escape sequence?
9334   const bool escaped = *regex == '\\';
9335   if (escaped)
9336     ++regex;
9337   if (IsRepeat(regex[1])) {
9338     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
9339     // here's an indirect recursion.  It terminates as the regex gets
9340     // shorter in each recursion.
9341     return MatchRepetitionAndRegexAtHead(
9342         escaped, regex[0], regex[1], regex + 2, str);
9343   } else {
9344     // regex isn't empty, isn't "$", and doesn't start with a
9345     // repetition.  We match the first atom of regex with the first
9346     // character of str and recurse.
9347     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
9348         MatchRegexAtHead(regex + 1, str + 1);
9349   }
9350 }
9351 
9352 // Returns true iff regex matches any substring of str.  regex must be
9353 // a valid simple regular expression, or the result is undefined.
9354 //
9355 // The algorithm is recursive, but the recursion depth doesn't exceed
9356 // the regex length, so we won't need to worry about running out of
9357 // stack space normally.  In rare cases the time complexity can be
9358 // exponential with respect to the regex length + the string length,
9359 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)9360 bool MatchRegexAnywhere(const char* regex, const char* str) {
9361   if (regex == NULL || str == NULL)
9362     return false;
9363 
9364   if (*regex == '^')
9365     return MatchRegexAtHead(regex + 1, str);
9366 
9367   // A successful match can be anywhere in str.
9368   do {
9369     if (MatchRegexAtHead(regex, str))
9370       return true;
9371   } while (*str++ != '\0');
9372   return false;
9373 }
9374 
9375 // Implements the RE class.
9376 
~RE()9377 RE::~RE() {
9378   free(const_cast<char*>(pattern_));
9379   free(const_cast<char*>(full_pattern_));
9380 }
9381 
9382 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)9383 bool RE::FullMatch(const char* str, const RE& re) {
9384   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
9385 }
9386 
9387 // Returns true iff regular expression re matches a substring of str
9388 // (including str itself).
PartialMatch(const char * str,const RE & re)9389 bool RE::PartialMatch(const char* str, const RE& re) {
9390   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
9391 }
9392 
9393 // Initializes an RE from its string representation.
Init(const char * regex)9394 void RE::Init(const char* regex) {
9395   pattern_ = full_pattern_ = NULL;
9396   if (regex != NULL) {
9397     pattern_ = posix::StrDup(regex);
9398   }
9399 
9400   is_valid_ = ValidateRegex(regex);
9401   if (!is_valid_) {
9402     // No need to calculate the full pattern when the regex is invalid.
9403     return;
9404   }
9405 
9406   const size_t len = strlen(regex);
9407   // Reserves enough bytes to hold the regular expression used for a
9408   // full match: we need space to prepend a '^', append a '$', and
9409   // terminate the string with '\0'.
9410   char* buffer = static_cast<char*>(malloc(len + 3));
9411   full_pattern_ = buffer;
9412 
9413   if (*regex != '^')
9414     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
9415 
9416   // We don't use snprintf or strncpy, as they trigger a warning when
9417   // compiled with VC++ 8.0.
9418   memcpy(buffer, regex, len);
9419   buffer += len;
9420 
9421   if (len == 0 || regex[len - 1] != '$')
9422     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
9423 
9424   *buffer = '\0';
9425 }
9426 
9427 #endif  // GTEST_USES_POSIX_RE
9428 
9429 const char kUnknownFile[] = "unknown file";
9430 
9431 // Formats a source file path and a line number as they would appear
9432 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)9433 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
9434   const std::string file_name(file == NULL ? kUnknownFile : file);
9435 
9436   if (line < 0) {
9437     return file_name + ":";
9438   }
9439 #ifdef _MSC_VER
9440   return file_name + "(" + StreamableToString(line) + "):";
9441 #else
9442   return file_name + ":" + StreamableToString(line) + ":";
9443 #endif  // _MSC_VER
9444 }
9445 
9446 // Formats a file location for compiler-independent XML output.
9447 // Although this function is not platform dependent, we put it next to
9448 // FormatFileLocation in order to contrast the two functions.
9449 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
9450 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)9451 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
9452     const char* file, int line) {
9453   const std::string file_name(file == NULL ? kUnknownFile : file);
9454 
9455   if (line < 0)
9456     return file_name;
9457   else
9458     return file_name + ":" + StreamableToString(line);
9459 }
9460 
GTestLog(GTestLogSeverity severity,const char * file,int line)9461 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
9462     : severity_(severity) {
9463   const char* const marker =
9464       severity == GTEST_INFO ?    "[  INFO ]" :
9465       severity == GTEST_WARNING ? "[WARNING]" :
9466       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
9467   GetStream() << ::std::endl << marker << " "
9468               << FormatFileLocation(file, line).c_str() << ": ";
9469 }
9470 
9471 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()9472 GTestLog::~GTestLog() {
9473   GetStream() << ::std::endl;
9474   if (severity_ == GTEST_FATAL) {
9475     fflush(stderr);
9476     posix::Abort();
9477   }
9478 }
9479 // Disable Microsoft deprecation warnings for POSIX functions called from
9480 // this class (creat, dup, dup2, and close)
9481 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
9482 
9483 #if GTEST_HAS_STREAM_REDIRECTION
9484 
9485 // Object that captures an output stream (stdout/stderr).
9486 class CapturedStream {
9487  public:
9488   // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)9489   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
9490 # if GTEST_OS_WINDOWS
9491     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
9492     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
9493 
9494     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
9495     const UINT success = ::GetTempFileNameA(temp_dir_path,
9496                                             "gtest_redir",
9497                                             0,  // Generate unique file name.
9498                                             temp_file_path);
9499     GTEST_CHECK_(success != 0)
9500         << "Unable to create a temporary file in " << temp_dir_path;
9501     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
9502     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
9503                                     << temp_file_path;
9504     filename_ = temp_file_path;
9505 # else
9506     // There's no guarantee that a test has write access to the current
9507     // directory, so we create the temporary file in the /tmp directory
9508     // instead. We use /tmp on most systems, and /sdcard on Android.
9509     // That's because Android doesn't have /tmp.
9510 #  if GTEST_OS_LINUX_ANDROID
9511     // Note: Android applications are expected to call the framework's
9512     // Context.getExternalStorageDirectory() method through JNI to get
9513     // the location of the world-writable SD Card directory. However,
9514     // this requires a Context handle, which cannot be retrieved
9515     // globally from native code. Doing so also precludes running the
9516     // code as part of a regular standalone executable, which doesn't
9517     // run in a Dalvik process (e.g. when running it through 'adb shell').
9518     //
9519     // The location /sdcard is directly accessible from native code
9520     // and is the only location (unofficially) supported by the Android
9521     // team. It's generally a symlink to the real SD Card mount point
9522     // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
9523     // other OEM-customized locations. Never rely on these, and always
9524     // use /sdcard.
9525     char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
9526 #  else
9527     char name_template[] = "/tmp/captured_stream.XXXXXX";
9528 #  endif  // GTEST_OS_LINUX_ANDROID
9529     const int captured_fd = mkstemp(name_template);
9530     filename_ = name_template;
9531 # endif  // GTEST_OS_WINDOWS
9532     fflush(NULL);
9533     dup2(captured_fd, fd_);
9534     close(captured_fd);
9535   }
9536 
~CapturedStream()9537   ~CapturedStream() {
9538     remove(filename_.c_str());
9539   }
9540 
GetCapturedString()9541   std::string GetCapturedString() {
9542     if (uncaptured_fd_ != -1) {
9543       // Restores the original stream.
9544       fflush(NULL);
9545       dup2(uncaptured_fd_, fd_);
9546       close(uncaptured_fd_);
9547       uncaptured_fd_ = -1;
9548     }
9549 
9550     FILE* const file = posix::FOpen(filename_.c_str(), "r");
9551     const std::string content = ReadEntireFile(file);
9552     posix::FClose(file);
9553     return content;
9554   }
9555 
9556  private:
9557   const int fd_;  // A stream to capture.
9558   int uncaptured_fd_;
9559   // Name of the temporary file holding the stderr output.
9560   ::std::string filename_;
9561 
9562   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
9563 };
9564 
9565 GTEST_DISABLE_MSC_WARNINGS_POP_()
9566 
9567 static CapturedStream* g_captured_stderr = NULL;
9568 static CapturedStream* g_captured_stdout = NULL;
9569 
9570 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)9571 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
9572   if (*stream != NULL) {
9573     GTEST_LOG_(FATAL) << "Only one " << stream_name
9574                       << " capturer can exist at a time.";
9575   }
9576   *stream = new CapturedStream(fd);
9577 }
9578 
9579 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)9580 std::string GetCapturedStream(CapturedStream** captured_stream) {
9581   const std::string content = (*captured_stream)->GetCapturedString();
9582 
9583   delete *captured_stream;
9584   *captured_stream = NULL;
9585 
9586   return content;
9587 }
9588 
9589 // Starts capturing stdout.
CaptureStdout()9590 void CaptureStdout() {
9591   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
9592 }
9593 
9594 // Starts capturing stderr.
CaptureStderr()9595 void CaptureStderr() {
9596   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
9597 }
9598 
9599 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()9600 std::string GetCapturedStdout() {
9601   return GetCapturedStream(&g_captured_stdout);
9602 }
9603 
9604 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()9605 std::string GetCapturedStderr() {
9606   return GetCapturedStream(&g_captured_stderr);
9607 }
9608 
9609 #endif  // GTEST_HAS_STREAM_REDIRECTION
9610 
TempDir()9611 std::string TempDir() {
9612 #if GTEST_OS_WINDOWS_MOBILE
9613   return "\\temp\\";
9614 #elif GTEST_OS_WINDOWS
9615   const char* temp_dir = posix::GetEnv("TEMP");
9616   if (temp_dir == NULL || temp_dir[0] == '\0')
9617     return "\\temp\\";
9618   else if (temp_dir[strlen(temp_dir) - 1] == '\\')
9619     return temp_dir;
9620   else
9621     return std::string(temp_dir) + "\\";
9622 #elif GTEST_OS_LINUX_ANDROID
9623   return "/sdcard/";
9624 #else
9625   return "/tmp/";
9626 #endif  // GTEST_OS_WINDOWS_MOBILE
9627 }
9628 
GetFileSize(FILE * file)9629 size_t GetFileSize(FILE* file) {
9630   fseek(file, 0, SEEK_END);
9631   return static_cast<size_t>(ftell(file));
9632 }
9633 
ReadEntireFile(FILE * file)9634 std::string ReadEntireFile(FILE* file) {
9635   const size_t file_size = GetFileSize(file);
9636   char* const buffer = new char[file_size];
9637 
9638   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
9639   size_t bytes_read = 0;       // # of bytes read so far
9640 
9641   fseek(file, 0, SEEK_SET);
9642 
9643   // Keeps reading the file until we cannot read further or the
9644   // pre-determined file size is reached.
9645   do {
9646     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
9647     bytes_read += bytes_last_read;
9648   } while (bytes_last_read > 0 && bytes_read < file_size);
9649 
9650   const std::string content(buffer, bytes_read);
9651   delete[] buffer;
9652 
9653   return content;
9654 }
9655 
9656 #if GTEST_HAS_DEATH_TEST
9657 
9658 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
9659                                         NULL;  // Owned.
9660 
SetInjectableArgvs(const::std::vector<testing::internal::string> * argvs)9661 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
9662   if (g_injected_test_argvs != argvs)
9663     delete g_injected_test_argvs;
9664   g_injected_test_argvs = argvs;
9665 }
9666 
GetInjectableArgvs()9667 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
9668   if (g_injected_test_argvs != NULL) {
9669     return *g_injected_test_argvs;
9670   }
9671   return GetArgvs();
9672 }
9673 #endif  // GTEST_HAS_DEATH_TEST
9674 
9675 #if GTEST_OS_WINDOWS_MOBILE
9676 namespace posix {
Abort()9677 void Abort() {
9678   DebugBreak();
9679   TerminateProcess(GetCurrentProcess(), 1);
9680 }
9681 }  // namespace posix
9682 #endif  // GTEST_OS_WINDOWS_MOBILE
9683 
9684 // Returns the name of the environment variable corresponding to the
9685 // given flag.  For example, FlagToEnvVar("foo") will return
9686 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)9687 static std::string FlagToEnvVar(const char* flag) {
9688   const std::string full_flag =
9689       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
9690 
9691   Message env_var;
9692   for (size_t i = 0; i != full_flag.length(); i++) {
9693     env_var << ToUpper(full_flag.c_str()[i]);
9694   }
9695 
9696   return env_var.GetString();
9697 }
9698 
9699 // Parses 'str' for a 32-bit signed integer.  If successful, writes
9700 // the result to *value and returns true; otherwise leaves *value
9701 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)9702 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
9703   // Parses the environment variable as a decimal integer.
9704   char* end = NULL;
9705   const long long_value = strtol(str, &end, 10);  // NOLINT
9706 
9707   // Has strtol() consumed all characters in the string?
9708   if (*end != '\0') {
9709     // No - an invalid character was encountered.
9710     Message msg;
9711     msg << "WARNING: " << src_text
9712         << " is expected to be a 32-bit integer, but actually"
9713         << " has value \"" << str << "\".\n";
9714     printf("%s", msg.GetString().c_str());
9715     fflush(stdout);
9716     return false;
9717   }
9718 
9719   // Is the parsed value in the range of an Int32?
9720   const Int32 result = static_cast<Int32>(long_value);
9721   if (long_value == LONG_MAX || long_value == LONG_MIN ||
9722       // The parsed value overflows as a long.  (strtol() returns
9723       // LONG_MAX or LONG_MIN when the input overflows.)
9724       result != long_value
9725       // The parsed value overflows as an Int32.
9726       ) {
9727     Message msg;
9728     msg << "WARNING: " << src_text
9729         << " is expected to be a 32-bit integer, but actually"
9730         << " has value " << str << ", which overflows.\n";
9731     printf("%s", msg.GetString().c_str());
9732     fflush(stdout);
9733     return false;
9734   }
9735 
9736   *value = result;
9737   return true;
9738 }
9739 
9740 // Reads and returns the Boolean environment variable corresponding to
9741 // the given flag; if it's not set, returns default_value.
9742 //
9743 // The value is considered true iff it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)9744 bool BoolFromGTestEnv(const char* flag, bool default_value) {
9745 #if defined(GTEST_GET_BOOL_FROM_ENV_)
9746   return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
9747 #endif  // defined(GTEST_GET_BOOL_FROM_ENV_)
9748   const std::string env_var = FlagToEnvVar(flag);
9749   const char* const string_value = posix::GetEnv(env_var.c_str());
9750   return string_value == NULL ?
9751       default_value : strcmp(string_value, "0") != 0;
9752 }
9753 
9754 // Reads and returns a 32-bit integer stored in the environment
9755 // variable corresponding to the given flag; if it isn't set or
9756 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)9757 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
9758 #if defined(GTEST_GET_INT32_FROM_ENV_)
9759   return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
9760 #endif  // defined(GTEST_GET_INT32_FROM_ENV_)
9761   const std::string env_var = FlagToEnvVar(flag);
9762   const char* const string_value = posix::GetEnv(env_var.c_str());
9763   if (string_value == NULL) {
9764     // The environment variable is not set.
9765     return default_value;
9766   }
9767 
9768   Int32 result = default_value;
9769   if (!ParseInt32(Message() << "Environment variable " << env_var,
9770                   string_value, &result)) {
9771     printf("The default value %s is used.\n",
9772            (Message() << default_value).GetString().c_str());
9773     fflush(stdout);
9774     return default_value;
9775   }
9776 
9777   return result;
9778 }
9779 
9780 // Reads and returns the string environment variable corresponding to
9781 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)9782 std::string StringFromGTestEnv(const char* flag, const char* default_value) {
9783 #if defined(GTEST_GET_STRING_FROM_ENV_)
9784   return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
9785 #endif  // defined(GTEST_GET_STRING_FROM_ENV_)
9786   const std::string env_var = FlagToEnvVar(flag);
9787   const char* value = posix::GetEnv(env_var.c_str());
9788   if (value != NULL) {
9789     return value;
9790   }
9791 
9792   // As a special case for the 'output' flag, if GTEST_OUTPUT is not
9793   // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
9794   // system.  The value of XML_OUTPUT_FILE is a filename without the
9795   // "xml:" prefix of GTEST_OUTPUT.
9796   //
9797   // The net priority order after flag processing is thus:
9798   //   --gtest_output command line flag
9799   //   GTEST_OUTPUT environment variable
9800   //   XML_OUTPUT_FILE environment variable
9801   //   'default_value'
9802   if (strcmp(flag, "output") == 0) {
9803     value = posix::GetEnv("XML_OUTPUT_FILE");
9804     if (value != NULL) {
9805       return std::string("xml:") + value;
9806     }
9807   }
9808   return default_value;
9809 }
9810 
9811 }  // namespace internal
9812 }  // namespace testing
9813 // Copyright 2007, Google Inc.
9814 // All rights reserved.
9815 //
9816 // Redistribution and use in source and binary forms, with or without
9817 // modification, are permitted provided that the following conditions are
9818 // met:
9819 //
9820 //     * Redistributions of source code must retain the above copyright
9821 // notice, this list of conditions and the following disclaimer.
9822 //     * Redistributions in binary form must reproduce the above
9823 // copyright notice, this list of conditions and the following disclaimer
9824 // in the documentation and/or other materials provided with the
9825 // distribution.
9826 //     * Neither the name of Google Inc. nor the names of its
9827 // contributors may be used to endorse or promote products derived from
9828 // this software without specific prior written permission.
9829 //
9830 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9831 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9832 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9833 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9834 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9835 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9836 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9837 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9838 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9839 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9840 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9841 //
9842 // Author: wan@google.com (Zhanyong Wan)
9843 
9844 // Google Test - The Google C++ Testing Framework
9845 //
9846 // This file implements a universal value printer that can print a
9847 // value of any type T:
9848 //
9849 //   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
9850 //
9851 // It uses the << operator when possible, and prints the bytes in the
9852 // object otherwise.  A user can override its behavior for a class
9853 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
9854 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
9855 // defines Foo.
9856 
9857 #include <ctype.h>
9858 #include <stdio.h>
9859 #include <cwchar>
9860 #include <ostream>  // NOLINT
9861 #include <string>
9862 
9863 namespace testing {
9864 
9865 namespace {
9866 
9867 using ::std::ostream;
9868 
9869 // Prints a segment of bytes in the given object.
9870 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
9871 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
9872 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintByteSegmentInObjectTo(const unsigned char * obj_bytes,size_t start,size_t count,ostream * os)9873 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
9874                                 size_t count, ostream* os) {
9875   char text[5] = "";
9876   for (size_t i = 0; i != count; i++) {
9877     const size_t j = start + i;
9878     if (i != 0) {
9879       // Organizes the bytes into groups of 2 for easy parsing by
9880       // human.
9881       if ((j % 2) == 0)
9882         *os << ' ';
9883       else
9884         *os << '-';
9885     }
9886     GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
9887     *os << text;
9888   }
9889 }
9890 
9891 // Prints the bytes in the given value to the given ostream.
PrintBytesInObjectToImpl(const unsigned char * obj_bytes,size_t count,ostream * os)9892 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
9893                               ostream* os) {
9894   // Tells the user how big the object is.
9895   *os << count << "-byte object <";
9896 
9897   const size_t kThreshold = 132;
9898   const size_t kChunkSize = 64;
9899   // If the object size is bigger than kThreshold, we'll have to omit
9900   // some details by printing only the first and the last kChunkSize
9901   // bytes.
9902   // TODO(wan): let the user control the threshold using a flag.
9903   if (count < kThreshold) {
9904     PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9905   } else {
9906     PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9907     *os << " ... ";
9908     // Rounds up to 2-byte boundary.
9909     const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9910     PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9911   }
9912   *os << ">";
9913 }
9914 
9915 }  // namespace
9916 
9917 namespace internal2 {
9918 
9919 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9920 // given object.  The delegation simplifies the implementation, which
9921 // uses the << operator and thus is easier done outside of the
9922 // ::testing::internal namespace, which contains a << operator that
9923 // sometimes conflicts with the one in STL.
PrintBytesInObjectTo(const unsigned char * obj_bytes,size_t count,ostream * os)9924 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
9925                           ostream* os) {
9926   PrintBytesInObjectToImpl(obj_bytes, count, os);
9927 }
9928 
9929 }  // namespace internal2
9930 
9931 namespace internal {
9932 
9933 // Depending on the value of a char (or wchar_t), we print it in one
9934 // of three formats:
9935 //   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9936 //   - as a hexidecimal escape sequence (e.g. '\x7F'), or
9937 //   - as a special escape sequence (e.g. '\r', '\n').
9938 enum CharFormat {
9939   kAsIs,
9940   kHexEscape,
9941   kSpecialEscape
9942 };
9943 
9944 // Returns true if c is a printable ASCII character.  We test the
9945 // value of c directly instead of calling isprint(), which is buggy on
9946 // Windows Mobile.
IsPrintableAscii(wchar_t c)9947 inline bool IsPrintableAscii(wchar_t c) {
9948   return 0x20 <= c && c <= 0x7E;
9949 }
9950 
9951 // Prints a wide or narrow char c as a character literal without the
9952 // quotes, escaping it when necessary; returns how c was formatted.
9953 // The template argument UnsignedChar is the unsigned version of Char,
9954 // which is the type of c.
9955 template <typename UnsignedChar, typename Char>
PrintAsCharLiteralTo(Char c,ostream * os)9956 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
9957   switch (static_cast<wchar_t>(c)) {
9958     case L'\0':
9959       *os << "\\0";
9960       break;
9961     case L'\'':
9962       *os << "\\'";
9963       break;
9964     case L'\\':
9965       *os << "\\\\";
9966       break;
9967     case L'\a':
9968       *os << "\\a";
9969       break;
9970     case L'\b':
9971       *os << "\\b";
9972       break;
9973     case L'\f':
9974       *os << "\\f";
9975       break;
9976     case L'\n':
9977       *os << "\\n";
9978       break;
9979     case L'\r':
9980       *os << "\\r";
9981       break;
9982     case L'\t':
9983       *os << "\\t";
9984       break;
9985     case L'\v':
9986       *os << "\\v";
9987       break;
9988     default:
9989       if (IsPrintableAscii(c)) {
9990         *os << static_cast<char>(c);
9991         return kAsIs;
9992       } else {
9993         *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9994         return kHexEscape;
9995       }
9996   }
9997   return kSpecialEscape;
9998 }
9999 
10000 // Prints a wchar_t c as if it's part of a string literal, escaping it when
10001 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(wchar_t c,ostream * os)10002 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
10003   switch (c) {
10004     case L'\'':
10005       *os << "'";
10006       return kAsIs;
10007     case L'"':
10008       *os << "\\\"";
10009       return kSpecialEscape;
10010     default:
10011       return PrintAsCharLiteralTo<wchar_t>(c, os);
10012   }
10013 }
10014 
10015 // Prints a char c as if it's part of a string literal, escaping it when
10016 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char c,ostream * os)10017 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
10018   return PrintAsStringLiteralTo(
10019       static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
10020 }
10021 
10022 // Prints a wide or narrow character c and its code.  '\0' is printed
10023 // as "'\\0'", other unprintable characters are also properly escaped
10024 // using the standard C++ escape sequence.  The template argument
10025 // UnsignedChar is the unsigned version of Char, which is the type of c.
10026 template <typename UnsignedChar, typename Char>
PrintCharAndCodeTo(Char c,ostream * os)10027 void PrintCharAndCodeTo(Char c, ostream* os) {
10028   // First, print c as a literal in the most readable form we can find.
10029   *os << ((sizeof(c) > 1) ? "L'" : "'");
10030   const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
10031   *os << "'";
10032 
10033   // To aid user debugging, we also print c's code in decimal, unless
10034   // it's 0 (in which case c was printed as '\\0', making the code
10035   // obvious).
10036   if (c == 0)
10037     return;
10038   *os << " (" << static_cast<int>(c);
10039 
10040   // For more convenience, we print c's code again in hexidecimal,
10041   // unless c was already printed in the form '\x##' or the code is in
10042   // [1, 9].
10043   if (format == kHexEscape || (1 <= c && c <= 9)) {
10044     // Do nothing.
10045   } else {
10046     *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
10047   }
10048   *os << ")";
10049 }
10050 
PrintTo(unsigned char c,::std::ostream * os)10051 void PrintTo(unsigned char c, ::std::ostream* os) {
10052   PrintCharAndCodeTo<unsigned char>(c, os);
10053 }
PrintTo(signed char c,::std::ostream * os)10054 void PrintTo(signed char c, ::std::ostream* os) {
10055   PrintCharAndCodeTo<unsigned char>(c, os);
10056 }
10057 
10058 // Prints a wchar_t as a symbol if it is printable or as its internal
10059 // code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
PrintTo(wchar_t wc,ostream * os)10060 void PrintTo(wchar_t wc, ostream* os) {
10061   PrintCharAndCodeTo<wchar_t>(wc, os);
10062 }
10063 
10064 // Prints the given array of characters to the ostream.  CharType must be either
10065 // char or wchar_t.
10066 // The array starts at begin, the length is len, it may include '\0' characters
10067 // and may not be NUL-terminated.
10068 template <typename CharType>
10069 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10070 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10071 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintCharsAsStringTo(const CharType * begin,size_t len,ostream * os)10072 static void PrintCharsAsStringTo(
10073     const CharType* begin, size_t len, ostream* os) {
10074   const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
10075   *os << kQuoteBegin;
10076   bool is_previous_hex = false;
10077   for (size_t index = 0; index < len; ++index) {
10078     const CharType cur = begin[index];
10079     if (is_previous_hex && IsXDigit(cur)) {
10080       // Previous character is of '\x..' form and this character can be
10081       // interpreted as another hexadecimal digit in its number. Break string to
10082       // disambiguate.
10083       *os << "\" " << kQuoteBegin;
10084     }
10085     is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
10086   }
10087   *os << "\"";
10088 }
10089 
10090 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
10091 // 'begin'.  CharType must be either char or wchar_t.
10092 template <typename CharType>
10093 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10094 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10095 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
UniversalPrintCharArray(const CharType * begin,size_t len,ostream * os)10096 static void UniversalPrintCharArray(
10097     const CharType* begin, size_t len, ostream* os) {
10098   // The code
10099   //   const char kFoo[] = "foo";
10100   // generates an array of 4, not 3, elements, with the last one being '\0'.
10101   //
10102   // Therefore when printing a char array, we don't print the last element if
10103   // it's '\0', such that the output matches the string literal as it's
10104   // written in the source code.
10105   if (len > 0 && begin[len - 1] == '\0') {
10106     PrintCharsAsStringTo(begin, len - 1, os);
10107     return;
10108   }
10109 
10110   // If, however, the last element in the array is not '\0', e.g.
10111   //    const char kFoo[] = { 'f', 'o', 'o' };
10112   // we must print the entire array.  We also print a message to indicate
10113   // that the array is not NUL-terminated.
10114   PrintCharsAsStringTo(begin, len, os);
10115   *os << " (no terminating NUL)";
10116 }
10117 
10118 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
UniversalPrintArray(const char * begin,size_t len,ostream * os)10119 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
10120   UniversalPrintCharArray(begin, len, os);
10121 }
10122 
10123 // Prints a (const) wchar_t array of 'len' elements, starting at address
10124 // 'begin'.
UniversalPrintArray(const wchar_t * begin,size_t len,ostream * os)10125 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
10126   UniversalPrintCharArray(begin, len, os);
10127 }
10128 
10129 // Prints the given C string to the ostream.
PrintTo(const char * s,ostream * os)10130 void PrintTo(const char* s, ostream* os) {
10131   if (s == NULL) {
10132     *os << "NULL";
10133   } else {
10134     *os << ImplicitCast_<const void*>(s) << " pointing to ";
10135     PrintCharsAsStringTo(s, strlen(s), os);
10136   }
10137 }
10138 
10139 // MSVC compiler can be configured to define whar_t as a typedef
10140 // of unsigned short. Defining an overload for const wchar_t* in that case
10141 // would cause pointers to unsigned shorts be printed as wide strings,
10142 // possibly accessing more memory than intended and causing invalid
10143 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
10144 // wchar_t is implemented as a native type.
10145 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
10146 // Prints the given wide C string to the ostream.
PrintTo(const wchar_t * s,ostream * os)10147 void PrintTo(const wchar_t* s, ostream* os) {
10148   if (s == NULL) {
10149     *os << "NULL";
10150   } else {
10151     *os << ImplicitCast_<const void*>(s) << " pointing to ";
10152     PrintCharsAsStringTo(s, std::wcslen(s), os);
10153   }
10154 }
10155 #endif  // wchar_t is native
10156 
10157 // Prints a ::string object.
10158 #if GTEST_HAS_GLOBAL_STRING
PrintStringTo(const::string & s,ostream * os)10159 void PrintStringTo(const ::string& s, ostream* os) {
10160   PrintCharsAsStringTo(s.data(), s.size(), os);
10161 }
10162 #endif  // GTEST_HAS_GLOBAL_STRING
10163 
PrintStringTo(const::std::string & s,ostream * os)10164 void PrintStringTo(const ::std::string& s, ostream* os) {
10165   PrintCharsAsStringTo(s.data(), s.size(), os);
10166 }
10167 
10168 // Prints a ::wstring object.
10169 #if GTEST_HAS_GLOBAL_WSTRING
PrintWideStringTo(const::wstring & s,ostream * os)10170 void PrintWideStringTo(const ::wstring& s, ostream* os) {
10171   PrintCharsAsStringTo(s.data(), s.size(), os);
10172 }
10173 #endif  // GTEST_HAS_GLOBAL_WSTRING
10174 
10175 #if GTEST_HAS_STD_WSTRING
PrintWideStringTo(const::std::wstring & s,ostream * os)10176 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
10177   PrintCharsAsStringTo(s.data(), s.size(), os);
10178 }
10179 #endif  // GTEST_HAS_STD_WSTRING
10180 
10181 }  // namespace internal
10182 
10183 }  // namespace testing
10184 // Copyright 2008, Google Inc.
10185 // All rights reserved.
10186 //
10187 // Redistribution and use in source and binary forms, with or without
10188 // modification, are permitted provided that the following conditions are
10189 // met:
10190 //
10191 //     * Redistributions of source code must retain the above copyright
10192 // notice, this list of conditions and the following disclaimer.
10193 //     * Redistributions in binary form must reproduce the above
10194 // copyright notice, this list of conditions and the following disclaimer
10195 // in the documentation and/or other materials provided with the
10196 // distribution.
10197 //     * Neither the name of Google Inc. nor the names of its
10198 // contributors may be used to endorse or promote products derived from
10199 // this software without specific prior written permission.
10200 //
10201 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10202 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10203 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10204 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10205 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10206 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10207 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10208 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10209 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10210 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10211 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10212 //
10213 // Author: mheule@google.com (Markus Heule)
10214 //
10215 // The Google C++ Testing Framework (Google Test)
10216 
10217 
10218 // Indicates that this translation unit is part of Google Test's
10219 // implementation.  It must come before gtest-internal-inl.h is
10220 // included, or there will be a compiler error.  This trick exists to
10221 // prevent the accidental inclusion of gtest-internal-inl.h in the
10222 // user's code.
10223 #define GTEST_IMPLEMENTATION_ 1
10224 #undef GTEST_IMPLEMENTATION_
10225 
10226 namespace testing {
10227 
10228 using internal::GetUnitTestImpl;
10229 
10230 // Gets the summary of the failure message by omitting the stack trace
10231 // in it.
ExtractSummary(const char * message)10232 std::string TestPartResult::ExtractSummary(const char* message) {
10233   const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
10234   return stack_trace == NULL ? message :
10235       std::string(message, stack_trace);
10236 }
10237 
10238 // Prints a TestPartResult object.
operator <<(std::ostream & os,const TestPartResult & result)10239 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
10240   return os
10241       << result.file_name() << ":" << result.line_number() << ": "
10242       << (result.type() == TestPartResult::kSuccess ? "Success" :
10243           result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
10244           "Non-fatal failure") << ":\n"
10245       << result.message() << std::endl;
10246 }
10247 
10248 // Appends a TestPartResult to the array.
Append(const TestPartResult & result)10249 void TestPartResultArray::Append(const TestPartResult& result) {
10250   array_.push_back(result);
10251 }
10252 
10253 // Returns the TestPartResult at the given index (0-based).
GetTestPartResult(int index) const10254 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
10255   if (index < 0 || index >= size()) {
10256     printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
10257     internal::posix::Abort();
10258   }
10259 
10260   return array_[index];
10261 }
10262 
10263 // Returns the number of TestPartResult objects in the array.
size() const10264 int TestPartResultArray::size() const {
10265   return static_cast<int>(array_.size());
10266 }
10267 
10268 namespace internal {
10269 
HasNewFatalFailureHelper()10270 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
10271     : has_new_fatal_failure_(false),
10272       original_reporter_(GetUnitTestImpl()->
10273                          GetTestPartResultReporterForCurrentThread()) {
10274   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
10275 }
10276 
~HasNewFatalFailureHelper()10277 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
10278   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
10279       original_reporter_);
10280 }
10281 
ReportTestPartResult(const TestPartResult & result)10282 void HasNewFatalFailureHelper::ReportTestPartResult(
10283     const TestPartResult& result) {
10284   if (result.fatally_failed())
10285     has_new_fatal_failure_ = true;
10286   original_reporter_->ReportTestPartResult(result);
10287 }
10288 
10289 }  // namespace internal
10290 
10291 }  // namespace testing
10292 // Copyright 2008 Google Inc.
10293 // All Rights Reserved.
10294 //
10295 // Redistribution and use in source and binary forms, with or without
10296 // modification, are permitted provided that the following conditions are
10297 // met:
10298 //
10299 //     * Redistributions of source code must retain the above copyright
10300 // notice, this list of conditions and the following disclaimer.
10301 //     * Redistributions in binary form must reproduce the above
10302 // copyright notice, this list of conditions and the following disclaimer
10303 // in the documentation and/or other materials provided with the
10304 // distribution.
10305 //     * Neither the name of Google Inc. nor the names of its
10306 // contributors may be used to endorse or promote products derived from
10307 // this software without specific prior written permission.
10308 //
10309 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10310 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10311 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10312 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10313 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10314 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10315 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10316 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10317 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10318 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10319 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10320 //
10321 // Author: wan@google.com (Zhanyong Wan)
10322 
10323 
10324 namespace testing {
10325 namespace internal {
10326 
10327 #if GTEST_HAS_TYPED_TEST_P
10328 
10329 // Skips to the first non-space char in str. Returns an empty string if str
10330 // contains only whitespace characters.
SkipSpaces(const char * str)10331 static const char* SkipSpaces(const char* str) {
10332   while (IsSpace(*str))
10333     str++;
10334   return str;
10335 }
10336 
SplitIntoTestNames(const char * src)10337 static std::vector<std::string> SplitIntoTestNames(const char* src) {
10338   std::vector<std::string> name_vec;
10339   src = SkipSpaces(src);
10340   for (; src != NULL; src = SkipComma(src)) {
10341     name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
10342   }
10343   return name_vec;
10344 }
10345 
10346 // Verifies that registered_tests match the test names in
10347 // registered_tests_; returns registered_tests if successful, or
10348 // aborts the program otherwise.
VerifyRegisteredTestNames(const char * file,int line,const char * registered_tests)10349 const char* TypedTestCasePState::VerifyRegisteredTestNames(
10350     const char* file, int line, const char* registered_tests) {
10351   typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
10352   registered_ = true;
10353 
10354   std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
10355 
10356   Message errors;
10357 
10358   std::set<std::string> tests;
10359   for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
10360        name_it != name_vec.end(); ++name_it) {
10361     const std::string& name = *name_it;
10362     if (tests.count(name) != 0) {
10363       errors << "Test " << name << " is listed more than once.\n";
10364       continue;
10365     }
10366 
10367     bool found = false;
10368     for (RegisteredTestIter it = registered_tests_.begin();
10369          it != registered_tests_.end();
10370          ++it) {
10371       if (name == it->first) {
10372         found = true;
10373         break;
10374       }
10375     }
10376 
10377     if (found) {
10378       tests.insert(name);
10379     } else {
10380       errors << "No test named " << name
10381              << " can be found in this test case.\n";
10382     }
10383   }
10384 
10385   for (RegisteredTestIter it = registered_tests_.begin();
10386        it != registered_tests_.end();
10387        ++it) {
10388     if (tests.count(it->first) == 0) {
10389       errors << "You forgot to list test " << it->first << ".\n";
10390     }
10391   }
10392 
10393   const std::string& errors_str = errors.GetString();
10394   if (errors_str != "") {
10395     fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
10396             errors_str.c_str());
10397     fflush(stderr);
10398     posix::Abort();
10399   }
10400 
10401   return registered_tests;
10402 }
10403 
10404 #endif  // GTEST_HAS_TYPED_TEST_P
10405 
10406 }  // namespace internal
10407 }  // namespace testing
10408