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 //   expected_expression: "foo"
2753 //   actual_expression:   "bar"
2754 //   expected_value:      "5"
2755 //   actual_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 * expected_expression,const char * actual_expression,const std::string & expected_value,const std::string & actual_value,bool ignoring_case)2760 AssertionResult EqFailure(const char* expected_expression,
2761                           const char* actual_expression,
2762                           const std::string& expected_value,
2763                           const std::string& actual_value,
2764                           bool ignoring_case) {
2765   Message msg;
2766   msg << "Value of: " << actual_expression;
2767   if (actual_value != actual_expression) {
2768     msg << "\n  Actual: " << actual_value;
2769   }
2770 
2771   msg << "\nExpected: " << expected_expression;
2772   if (ignoring_case) {
2773     msg << " (ignoring case)";
2774   }
2775   if (expected_value != expected_expression) {
2776     msg << "\nWhich is: " << expected_value;
2777   }
2778 
2779   if (!expected_value.empty() && !actual_value.empty()) {
2780     const std::vector<std::string> expected_lines =
2781         SplitEscapedString(expected_value);
2782     const std::vector<std::string> actual_lines =
2783         SplitEscapedString(actual_value);
2784     if (expected_lines.size() > 1 || actual_lines.size() > 1) {
2785       msg << "\nWith diff:\n"
2786           << edit_distance::CreateUnifiedDiff(expected_lines, actual_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 * expected_expression,const char * actual_expression,BiggestInt expected,BiggestInt actual)2885 AssertionResult CmpHelperEQ(const char* expected_expression,
2886                             const char* actual_expression,
2887                             BiggestInt expected,
2888                             BiggestInt actual) {
2889   if (expected == actual) {
2890     return AssertionSuccess();
2891   }
2892 
2893   return EqFailure(expected_expression,
2894                    actual_expression,
2895                    FormatForComparisonFailureMessage(expected, actual),
2896                    FormatForComparisonFailureMessage(actual, expected),
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 * expected_expression,const char * actual_expression,const char * expected,const char * actual)2935 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2936                                const char* actual_expression,
2937                                const char* expected,
2938                                const char* actual) {
2939   if (String::CStringEquals(expected, actual)) {
2940     return AssertionSuccess();
2941   }
2942 
2943   return EqFailure(expected_expression,
2944                    actual_expression,
2945                    PrintToString(expected),
2946                    PrintToString(actual),
2947                    false);
2948 }
2949 
2950 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * expected_expression,const char * actual_expression,const char * expected,const char * actual)2951 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2952                                    const char* actual_expression,
2953                                    const char* expected,
2954                                    const char* actual) {
2955   if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2956     return AssertionSuccess();
2957   }
2958 
2959   return EqFailure(expected_expression,
2960                    actual_expression,
2961                    PrintToString(expected),
2962                    PrintToString(actual),
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 * expected_expression,const char * actual_expression,const wchar_t * expected,const wchar_t * actual)3317 AssertionResult CmpHelperSTREQ(const char* expected_expression,
3318                                const char* actual_expression,
3319                                const wchar_t* expected,
3320                                const wchar_t* actual) {
3321   if (String::WideCStringEquals(expected, actual)) {
3322     return AssertionSuccess();
3323   }
3324 
3325   return EqFailure(expected_expression,
3326                    actual_expression,
3327                    PrintToString(expected),
3328                    PrintToString(actual),
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     return test_info && test_info->name() == name_;
4052   }
4053 
4054  private:
4055   std::string name_;
4056 };
4057 
4058 }  // namespace
4059 
4060 namespace internal {
4061 
4062 // This method expands all parameterized tests registered with macros TEST_P
4063 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
4064 // This will be done just once during the program runtime.
RegisterParameterizedTests()4065 void UnitTestImpl::RegisterParameterizedTests() {
4066 #if GTEST_HAS_PARAM_TEST
4067   if (!parameterized_tests_registered_) {
4068     parameterized_test_registry_.RegisterTests();
4069     parameterized_tests_registered_ = true;
4070   }
4071 #endif
4072 }
4073 
4074 }  // namespace internal
4075 
4076 // Creates the test object, runs it, records its result, and then
4077 // deletes it.
Run()4078 void TestInfo::Run() {
4079   if (!should_run_) return;
4080 
4081   // Tells UnitTest where to store test result.
4082   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4083   impl->set_current_test_info(this);
4084 
4085   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4086 
4087   // Notifies the unit test event listeners that a test is about to start.
4088   repeater->OnTestStart(*this);
4089 
4090   const TimeInMillis start = internal::GetTimeInMillis();
4091 
4092   impl->os_stack_trace_getter()->UponLeavingGTest();
4093 
4094   // Creates the test object.
4095   Test* const test = internal::HandleExceptionsInMethodIfSupported(
4096       factory_, &internal::TestFactoryBase::CreateTest,
4097       "the test fixture's constructor");
4098 
4099   // Runs the test only if the test object was created and its
4100   // constructor didn't generate a fatal failure.
4101   if ((test != NULL) && !Test::HasFatalFailure()) {
4102     // This doesn't throw as all user code that can throw are wrapped into
4103     // exception handling code.
4104     test->Run();
4105   }
4106 
4107   // Deletes the test object.
4108   impl->os_stack_trace_getter()->UponLeavingGTest();
4109   internal::HandleExceptionsInMethodIfSupported(
4110       test, &Test::DeleteSelf_, "the test fixture's destructor");
4111 
4112   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4113 
4114   // Notifies the unit test event listener that a test has just finished.
4115   repeater->OnTestEnd(*this);
4116 
4117   // Tells UnitTest to stop associating assertion results to this
4118   // test.
4119   impl->set_current_test_info(NULL);
4120 }
4121 
4122 // class TestCase
4123 
4124 // Gets the number of successful tests in this test case.
successful_test_count() const4125 int TestCase::successful_test_count() const {
4126   return CountIf(test_info_list_, TestPassed);
4127 }
4128 
4129 // Gets the number of failed tests in this test case.
failed_test_count() const4130 int TestCase::failed_test_count() const {
4131   return CountIf(test_info_list_, TestFailed);
4132 }
4133 
4134 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const4135 int TestCase::reportable_disabled_test_count() const {
4136   return CountIf(test_info_list_, TestReportableDisabled);
4137 }
4138 
4139 // Gets the number of disabled tests in this test case.
disabled_test_count() const4140 int TestCase::disabled_test_count() const {
4141   return CountIf(test_info_list_, TestDisabled);
4142 }
4143 
4144 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const4145 int TestCase::reportable_test_count() const {
4146   return CountIf(test_info_list_, TestReportable);
4147 }
4148 
4149 // Get the number of tests in this test case that should run.
test_to_run_count() const4150 int TestCase::test_to_run_count() const {
4151   return CountIf(test_info_list_, ShouldRunTest);
4152 }
4153 
4154 // Gets the number of all tests.
total_test_count() const4155 int TestCase::total_test_count() const {
4156   return static_cast<int>(test_info_list_.size());
4157 }
4158 
4159 // Creates a TestCase with the given name.
4160 //
4161 // Arguments:
4162 //
4163 //   name:         name of the test case
4164 //   a_type_param: the name of the test case's type parameter, or NULL if
4165 //                 this is not a typed or a type-parameterized test case.
4166 //   set_up_tc:    pointer to the function that sets up the test case
4167 //   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)4168 TestCase::TestCase(const char* a_name, const char* a_type_param,
4169                    Test::SetUpTestCaseFunc set_up_tc,
4170                    Test::TearDownTestCaseFunc tear_down_tc)
4171     : name_(a_name),
4172       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
4173       set_up_tc_(set_up_tc),
4174       tear_down_tc_(tear_down_tc),
4175       should_run_(false),
4176       elapsed_time_(0) {
4177 }
4178 
4179 // Destructor of TestCase.
~TestCase()4180 TestCase::~TestCase() {
4181   // Deletes every Test in the collection.
4182   ForEach(test_info_list_, internal::Delete<TestInfo>);
4183 }
4184 
4185 // Returns the i-th test among all the tests. i can range from 0 to
4186 // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const4187 const TestInfo* TestCase::GetTestInfo(int i) const {
4188   const int index = GetElementOr(test_indices_, i, -1);
4189   return index < 0 ? NULL : test_info_list_[index];
4190 }
4191 
4192 // Returns the i-th test among all the tests. i can range from 0 to
4193 // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)4194 TestInfo* TestCase::GetMutableTestInfo(int i) {
4195   const int index = GetElementOr(test_indices_, i, -1);
4196   return index < 0 ? NULL : test_info_list_[index];
4197 }
4198 
4199 // Adds a test to this test case.  Will delete the test upon
4200 // destruction of the TestCase object.
AddTestInfo(TestInfo * test_info)4201 void TestCase::AddTestInfo(TestInfo * test_info) {
4202   test_info_list_.push_back(test_info);
4203   test_indices_.push_back(static_cast<int>(test_indices_.size()));
4204 }
4205 
4206 // Runs every test in this TestCase.
Run()4207 void TestCase::Run() {
4208   if (!should_run_) return;
4209 
4210   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4211   impl->set_current_test_case(this);
4212 
4213   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4214 
4215   repeater->OnTestCaseStart(*this);
4216   impl->os_stack_trace_getter()->UponLeavingGTest();
4217   internal::HandleExceptionsInMethodIfSupported(
4218       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
4219 
4220   const internal::TimeInMillis start = internal::GetTimeInMillis();
4221   for (int i = 0; i < total_test_count(); i++) {
4222     GetMutableTestInfo(i)->Run();
4223   }
4224   elapsed_time_ = internal::GetTimeInMillis() - start;
4225 
4226   impl->os_stack_trace_getter()->UponLeavingGTest();
4227   internal::HandleExceptionsInMethodIfSupported(
4228       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
4229 
4230   repeater->OnTestCaseEnd(*this);
4231   impl->set_current_test_case(NULL);
4232 }
4233 
4234 // Clears the results of all tests in this test case.
ClearResult()4235 void TestCase::ClearResult() {
4236   ad_hoc_test_result_.Clear();
4237   ForEach(test_info_list_, TestInfo::ClearTestResult);
4238 }
4239 
4240 // Shuffles the tests in this test case.
ShuffleTests(internal::Random * random)4241 void TestCase::ShuffleTests(internal::Random* random) {
4242   Shuffle(random, &test_indices_);
4243 }
4244 
4245 // Restores the test order to before the first shuffle.
UnshuffleTests()4246 void TestCase::UnshuffleTests() {
4247   for (size_t i = 0; i < test_indices_.size(); i++) {
4248     test_indices_[i] = static_cast<int>(i);
4249   }
4250 }
4251 
4252 // Formats a countable noun.  Depending on its quantity, either the
4253 // singular form or the plural form is used. e.g.
4254 //
4255 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4256 // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)4257 static std::string FormatCountableNoun(int count,
4258                                        const char * singular_form,
4259                                        const char * plural_form) {
4260   return internal::StreamableToString(count) + " " +
4261       (count == 1 ? singular_form : plural_form);
4262 }
4263 
4264 // Formats the count of tests.
FormatTestCount(int test_count)4265 static std::string FormatTestCount(int test_count) {
4266   return FormatCountableNoun(test_count, "test", "tests");
4267 }
4268 
4269 // Formats the count of test cases.
FormatTestCaseCount(int test_case_count)4270 static std::string FormatTestCaseCount(int test_case_count) {
4271   return FormatCountableNoun(test_case_count, "test case", "test cases");
4272 }
4273 
4274 // Converts a TestPartResult::Type enum to human-friendly string
4275 // representation.  Both kNonFatalFailure and kFatalFailure are translated
4276 // to "Failure", as the user usually doesn't care about the difference
4277 // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)4278 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4279   switch (type) {
4280     case TestPartResult::kSuccess:
4281       return "Success";
4282 
4283     case TestPartResult::kNonFatalFailure:
4284     case TestPartResult::kFatalFailure:
4285 #ifdef _MSC_VER
4286       return "error: ";
4287 #else
4288       return "Failure\n";
4289 #endif
4290     default:
4291       return "Unknown result type";
4292   }
4293 }
4294 
4295 namespace internal {
4296 
4297 // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)4298 static std::string PrintTestPartResultToString(
4299     const TestPartResult& test_part_result) {
4300   return (Message()
4301           << internal::FormatFileLocation(test_part_result.file_name(),
4302                                           test_part_result.line_number())
4303           << " " << TestPartResultTypeToString(test_part_result.type())
4304           << test_part_result.message()).GetString();
4305 }
4306 
4307 // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)4308 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4309   const std::string& result =
4310       PrintTestPartResultToString(test_part_result);
4311   printf("%s\n", result.c_str());
4312   fflush(stdout);
4313   // If the test program runs in Visual Studio or a debugger, the
4314   // following statements add the test part result message to the Output
4315   // window such that the user can double-click on it to jump to the
4316   // corresponding source code location; otherwise they do nothing.
4317 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4318   // We don't call OutputDebugString*() on Windows Mobile, as printing
4319   // to stdout is done by OutputDebugString() there already - we don't
4320   // want the same message printed twice.
4321   ::OutputDebugStringA(result.c_str());
4322   ::OutputDebugStringA("\n");
4323 #endif
4324 }
4325 
4326 // class PrettyUnitTestResultPrinter
4327 
4328 enum GTestColor {
4329   COLOR_DEFAULT,
4330   COLOR_RED,
4331   COLOR_GREEN,
4332   COLOR_YELLOW
4333 };
4334 
4335 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4336     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4337 
4338 // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)4339 WORD GetColorAttribute(GTestColor color) {
4340   switch (color) {
4341     case COLOR_RED:    return FOREGROUND_RED;
4342     case COLOR_GREEN:  return FOREGROUND_GREEN;
4343     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4344     default:           return 0;
4345   }
4346 }
4347 
4348 #else
4349 
4350 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
4351 // an invalid input.
GetAnsiColorCode(GTestColor color)4352 const char* GetAnsiColorCode(GTestColor color) {
4353   switch (color) {
4354     case COLOR_RED:     return "1";
4355     case COLOR_GREEN:   return "2";
4356     case COLOR_YELLOW:  return "3";
4357     default:            return NULL;
4358   };
4359 }
4360 
4361 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4362 
4363 // Returns true iff Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)4364 bool ShouldUseColor(bool stdout_is_tty) {
4365   const char* const gtest_color = GTEST_FLAG(color).c_str();
4366 
4367   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4368 #if GTEST_OS_WINDOWS
4369     // On Windows the TERM variable is usually not set, but the
4370     // console there does support colors.
4371     return stdout_is_tty;
4372 #else
4373     // On non-Windows platforms, we rely on the TERM variable.
4374     const char* const term = posix::GetEnv("TERM");
4375     const bool term_supports_color =
4376         String::CStringEquals(term, "xterm") ||
4377         String::CStringEquals(term, "xterm-color") ||
4378         String::CStringEquals(term, "xterm-256color") ||
4379         String::CStringEquals(term, "screen") ||
4380         String::CStringEquals(term, "screen-256color") ||
4381         String::CStringEquals(term, "rxvt-unicode") ||
4382         String::CStringEquals(term, "rxvt-unicode-256color") ||
4383         String::CStringEquals(term, "linux") ||
4384         String::CStringEquals(term, "cygwin");
4385     return stdout_is_tty && term_supports_color;
4386 #endif  // GTEST_OS_WINDOWS
4387   }
4388 
4389   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4390       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4391       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4392       String::CStringEquals(gtest_color, "1");
4393   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
4394   // value is neither one of these nor "auto", we treat it as "no" to
4395   // be conservative.
4396 }
4397 
4398 // Helpers for printing colored strings to stdout. Note that on Windows, we
4399 // cannot simply emit special characters and have the terminal change colors.
4400 // This routine must actually emit the characters rather than return a string
4401 // that would be colored when printed, as can be done on Linux.
ColoredPrintf(GTestColor color,const char * fmt,...)4402 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4403   va_list args;
4404   va_start(args, fmt);
4405 
4406 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
4407     GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4408   const bool use_color = AlwaysFalse();
4409 #else
4410   static const bool in_color_mode =
4411       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4412   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4413 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4414   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4415 
4416   if (!use_color) {
4417     vprintf(fmt, args);
4418     va_end(args);
4419     return;
4420   }
4421 
4422 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4423     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4424   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4425 
4426   // Gets the current text color.
4427   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4428   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4429   const WORD old_color_attrs = buffer_info.wAttributes;
4430 
4431   // We need to flush the stream buffers into the console before each
4432   // SetConsoleTextAttribute call lest it affect the text that is already
4433   // printed but has not yet reached the console.
4434   fflush(stdout);
4435   SetConsoleTextAttribute(stdout_handle,
4436                           GetColorAttribute(color) | FOREGROUND_INTENSITY);
4437   vprintf(fmt, args);
4438 
4439   fflush(stdout);
4440   // Restores the text color.
4441   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4442 #else
4443   printf("\033[0;3%sm", GetAnsiColorCode(color));
4444   vprintf(fmt, args);
4445   printf("\033[m");  // Resets the terminal to default.
4446 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4447   va_end(args);
4448 }
4449 
4450 // Text printed in Google Test's text output and --gunit_list_tests
4451 // output to label the type parameter and value parameter for a test.
4452 static const char kTypeParamLabel[] = "TypeParam";
4453 static const char kValueParamLabel[] = "GetParam()";
4454 
PrintFullTestCommentIfPresent(const TestInfo & test_info)4455 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4456   const char* const type_param = test_info.type_param();
4457   const char* const value_param = test_info.value_param();
4458 
4459   if (type_param != NULL || value_param != NULL) {
4460     printf(", where ");
4461     if (type_param != NULL) {
4462       printf("%s = %s", kTypeParamLabel, type_param);
4463       if (value_param != NULL)
4464         printf(" and ");
4465     }
4466     if (value_param != NULL) {
4467       printf("%s = %s", kValueParamLabel, value_param);
4468     }
4469   }
4470 }
4471 
4472 // This class implements the TestEventListener interface.
4473 //
4474 // Class PrettyUnitTestResultPrinter is copyable.
4475 class PrettyUnitTestResultPrinter : public TestEventListener {
4476  public:
PrettyUnitTestResultPrinter()4477   PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_case,const char * test)4478   static void PrintTestName(const char * test_case, const char * test) {
4479     printf("%s.%s", test_case, test);
4480   }
4481 
4482   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)4483   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4484   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4485   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
OnEnvironmentsSetUpEnd(const UnitTest &)4486   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4487   virtual void OnTestCaseStart(const TestCase& test_case);
4488   virtual void OnTestStart(const TestInfo& test_info);
4489   virtual void OnTestPartResult(const TestPartResult& result);
4490   virtual void OnTestEnd(const TestInfo& test_info);
4491   virtual void OnTestCaseEnd(const TestCase& test_case);
4492   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
OnEnvironmentsTearDownEnd(const UnitTest &)4493   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4494   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
OnTestProgramEnd(const UnitTest &)4495   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4496 
4497  private:
4498   static void PrintFailedTests(const UnitTest& unit_test);
4499 };
4500 
4501   // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)4502 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4503     const UnitTest& unit_test, int iteration) {
4504   if (GTEST_FLAG(repeat) != 1)
4505     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4506 
4507   const char* const filter = GTEST_FLAG(filter).c_str();
4508 
4509   // Prints the filter if it's not *.  This reminds the user that some
4510   // tests may be skipped.
4511   if (!String::CStringEquals(filter, kUniversalFilter)) {
4512     ColoredPrintf(COLOR_YELLOW,
4513                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
4514   }
4515 
4516   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4517     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4518     ColoredPrintf(COLOR_YELLOW,
4519                   "Note: This is test shard %d of %s.\n",
4520                   static_cast<int>(shard_index) + 1,
4521                   internal::posix::GetEnv(kTestTotalShards));
4522   }
4523 
4524   if (GTEST_FLAG(shuffle)) {
4525     ColoredPrintf(COLOR_YELLOW,
4526                   "Note: Randomizing tests' orders with a seed of %d .\n",
4527                   unit_test.random_seed());
4528   }
4529 
4530   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4531   printf("Running %s from %s.\n",
4532          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4533          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4534   fflush(stdout);
4535 }
4536 
OnEnvironmentsSetUpStart(const UnitTest &)4537 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4538     const UnitTest& /*unit_test*/) {
4539   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4540   printf("Global test environment set-up.\n");
4541   fflush(stdout);
4542 }
4543 
OnTestCaseStart(const TestCase & test_case)4544 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4545   const std::string counts =
4546       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4547   ColoredPrintf(COLOR_GREEN, "[----------] ");
4548   printf("%s from %s", counts.c_str(), test_case.name());
4549   if (test_case.type_param() == NULL) {
4550     printf("\n");
4551   } else {
4552     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4553   }
4554   fflush(stdout);
4555 }
4556 
OnTestStart(const TestInfo & test_info)4557 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4558   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
4559   PrintTestName(test_info.test_case_name(), test_info.name());
4560   printf("\n");
4561   fflush(stdout);
4562 }
4563 
4564 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)4565 void PrettyUnitTestResultPrinter::OnTestPartResult(
4566     const TestPartResult& result) {
4567   // If the test part succeeded, we don't need to do anything.
4568   if (result.type() == TestPartResult::kSuccess)
4569     return;
4570 
4571   // Print failure message from the assertion (e.g. expected this and got that).
4572   PrintTestPartResult(result);
4573   fflush(stdout);
4574 }
4575 
OnTestEnd(const TestInfo & test_info)4576 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4577   if (test_info.result()->Passed()) {
4578     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
4579   } else {
4580     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4581   }
4582   PrintTestName(test_info.test_case_name(), test_info.name());
4583   if (test_info.result()->Failed())
4584     PrintFullTestCommentIfPresent(test_info);
4585 
4586   if (GTEST_FLAG(print_time)) {
4587     printf(" (%s ms)\n", internal::StreamableToString(
4588            test_info.result()->elapsed_time()).c_str());
4589   } else {
4590     printf("\n");
4591   }
4592   fflush(stdout);
4593 }
4594 
OnTestCaseEnd(const TestCase & test_case)4595 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4596   if (!GTEST_FLAG(print_time)) return;
4597 
4598   const std::string counts =
4599       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4600   ColoredPrintf(COLOR_GREEN, "[----------] ");
4601   printf("%s from %s (%s ms total)\n\n",
4602          counts.c_str(), test_case.name(),
4603          internal::StreamableToString(test_case.elapsed_time()).c_str());
4604   fflush(stdout);
4605 }
4606 
OnEnvironmentsTearDownStart(const UnitTest &)4607 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4608     const UnitTest& /*unit_test*/) {
4609   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4610   printf("Global test environment tear-down\n");
4611   fflush(stdout);
4612 }
4613 
4614 // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)4615 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4616   const int failed_test_count = unit_test.failed_test_count();
4617   if (failed_test_count == 0) {
4618     return;
4619   }
4620 
4621   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4622     const TestCase& test_case = *unit_test.GetTestCase(i);
4623     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4624       continue;
4625     }
4626     for (int j = 0; j < test_case.total_test_count(); ++j) {
4627       const TestInfo& test_info = *test_case.GetTestInfo(j);
4628       if (!test_info.should_run() || test_info.result()->Passed()) {
4629         continue;
4630       }
4631       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4632       printf("%s.%s", test_case.name(), test_info.name());
4633       PrintFullTestCommentIfPresent(test_info);
4634       printf("\n");
4635     }
4636   }
4637 }
4638 
OnTestIterationEnd(const UnitTest & unit_test,int)4639 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4640                                                      int /*iteration*/) {
4641   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4642   printf("%s from %s ran.",
4643          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4644          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4645   if (GTEST_FLAG(print_time)) {
4646     printf(" (%s ms total)",
4647            internal::StreamableToString(unit_test.elapsed_time()).c_str());
4648   }
4649   printf("\n");
4650   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
4651   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4652 
4653   int num_failures = unit_test.failed_test_count();
4654   if (!unit_test.Passed()) {
4655     const int failed_test_count = unit_test.failed_test_count();
4656     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
4657     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4658     PrintFailedTests(unit_test);
4659     printf("\n%2d FAILED %s\n", num_failures,
4660                         num_failures == 1 ? "TEST" : "TESTS");
4661   }
4662 
4663   int num_disabled = unit_test.reportable_disabled_test_count();
4664   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4665     if (!num_failures) {
4666       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
4667     }
4668     ColoredPrintf(COLOR_YELLOW,
4669                   "  YOU HAVE %d DISABLED %s\n\n",
4670                   num_disabled,
4671                   num_disabled == 1 ? "TEST" : "TESTS");
4672   }
4673   // Ensure that Google Test output is printed before, e.g., heapchecker output.
4674   fflush(stdout);
4675 }
4676 
4677 // End PrettyUnitTestResultPrinter
4678 
4679 // class TestEventRepeater
4680 //
4681 // This class forwards events to other event listeners.
4682 class TestEventRepeater : public TestEventListener {
4683  public:
TestEventRepeater()4684   TestEventRepeater() : forwarding_enabled_(true) {}
4685   virtual ~TestEventRepeater();
4686   void Append(TestEventListener *listener);
4687   TestEventListener* Release(TestEventListener* listener);
4688 
4689   // Controls whether events will be forwarded to listeners_. Set to false
4690   // in death test child processes.
forwarding_enabled() const4691   bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)4692   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4693 
4694   virtual void OnTestProgramStart(const UnitTest& unit_test);
4695   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4696   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4697   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4698   virtual void OnTestCaseStart(const TestCase& test_case);
4699   virtual void OnTestStart(const TestInfo& test_info);
4700   virtual void OnTestPartResult(const TestPartResult& result);
4701   virtual void OnTestEnd(const TestInfo& test_info);
4702   virtual void OnTestCaseEnd(const TestCase& test_case);
4703   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4704   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4705   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4706   virtual void OnTestProgramEnd(const UnitTest& unit_test);
4707 
4708  private:
4709   // Controls whether events will be forwarded to listeners_. Set to false
4710   // in death test child processes.
4711   bool forwarding_enabled_;
4712   // The list of listeners that receive events.
4713   std::vector<TestEventListener*> listeners_;
4714 
4715   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4716 };
4717 
~TestEventRepeater()4718 TestEventRepeater::~TestEventRepeater() {
4719   ForEach(listeners_, Delete<TestEventListener>);
4720 }
4721 
Append(TestEventListener * listener)4722 void TestEventRepeater::Append(TestEventListener *listener) {
4723   listeners_.push_back(listener);
4724 }
4725 
4726 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
Release(TestEventListener * listener)4727 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4728   for (size_t i = 0; i < listeners_.size(); ++i) {
4729     if (listeners_[i] == listener) {
4730       listeners_.erase(listeners_.begin() + i);
4731       return listener;
4732     }
4733   }
4734 
4735   return NULL;
4736 }
4737 
4738 // Since most methods are very similar, use macros to reduce boilerplate.
4739 // This defines a member that forwards the call to all listeners.
4740 #define GTEST_REPEATER_METHOD_(Name, Type) \
4741 void TestEventRepeater::Name(const Type& parameter) { \
4742   if (forwarding_enabled_) { \
4743     for (size_t i = 0; i < listeners_.size(); i++) { \
4744       listeners_[i]->Name(parameter); \
4745     } \
4746   } \
4747 }
4748 // This defines a member that forwards the call to all listeners in reverse
4749 // order.
4750 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4751 void TestEventRepeater::Name(const Type& parameter) { \
4752   if (forwarding_enabled_) { \
4753     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4754       listeners_[i]->Name(parameter); \
4755     } \
4756   } \
4757 }
4758 
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)4759 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4760 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4761 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4762 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4763 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4764 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4765 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4766 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4767 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4768 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4769 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4770 
4771 #undef GTEST_REPEATER_METHOD_
4772 #undef GTEST_REVERSE_REPEATER_METHOD_
4773 
4774 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4775                                              int iteration) {
4776   if (forwarding_enabled_) {
4777     for (size_t i = 0; i < listeners_.size(); i++) {
4778       listeners_[i]->OnTestIterationStart(unit_test, iteration);
4779     }
4780   }
4781 }
4782 
OnTestIterationEnd(const UnitTest & unit_test,int iteration)4783 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4784                                            int iteration) {
4785   if (forwarding_enabled_) {
4786     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4787       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4788     }
4789   }
4790 }
4791 
4792 // End TestEventRepeater
4793 
4794 // This class generates an XML output file.
4795 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4796  public:
4797   explicit XmlUnitTestResultPrinter(const char* output_file);
4798 
4799   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4800 
4801  private:
4802   // Is c a whitespace character that is normalized to a space character
4803   // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)4804   static bool IsNormalizableWhitespace(char c) {
4805     return c == 0x9 || c == 0xA || c == 0xD;
4806   }
4807 
4808   // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)4809   static bool IsValidXmlCharacter(char c) {
4810     return IsNormalizableWhitespace(c) || c >= 0x20;
4811   }
4812 
4813   // Returns an XML-escaped copy of the input string str.  If
4814   // is_attribute is true, the text is meant to appear as an attribute
4815   // value, and normalizable whitespace is preserved by replacing it
4816   // with character references.
4817   static std::string EscapeXml(const std::string& str, bool is_attribute);
4818 
4819   // Returns the given string with all characters invalid in XML removed.
4820   static std::string RemoveInvalidXmlCharacters(const std::string& str);
4821 
4822   // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)4823   static std::string EscapeXmlAttribute(const std::string& str) {
4824     return EscapeXml(str, true);
4825   }
4826 
4827   // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)4828   static std::string EscapeXmlText(const char* str) {
4829     return EscapeXml(str, false);
4830   }
4831 
4832   // Verifies that the given attribute belongs to the given element and
4833   // streams the attribute as XML.
4834   static void OutputXmlAttribute(std::ostream* stream,
4835                                  const std::string& element_name,
4836                                  const std::string& name,
4837                                  const std::string& value);
4838 
4839   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4840   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4841 
4842   // Streams an XML representation of a TestInfo object.
4843   static void OutputXmlTestInfo(::std::ostream* stream,
4844                                 const char* test_case_name,
4845                                 const TestInfo& test_info);
4846 
4847   // Prints an XML representation of a TestCase object
4848   static void PrintXmlTestCase(::std::ostream* stream,
4849                                const TestCase& test_case);
4850 
4851   // Prints an XML summary of unit_test to output stream out.
4852   static void PrintXmlUnitTest(::std::ostream* stream,
4853                                const UnitTest& unit_test);
4854 
4855   // Produces a string representing the test properties in a result as space
4856   // delimited XML attributes based on the property key="value" pairs.
4857   // When the std::string is not empty, it includes a space at the beginning,
4858   // to delimit this attribute from prior attributes.
4859   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4860 
4861   // The output file.
4862   const std::string output_file_;
4863 
4864   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4865 };
4866 
4867 // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)4868 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4869     : output_file_(output_file) {
4870   if (output_file_.c_str() == NULL || output_file_.empty()) {
4871     fprintf(stderr, "XML output file may not be null\n");
4872     fflush(stderr);
4873     exit(EXIT_FAILURE);
4874   }
4875 }
4876 
4877 // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)4878 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4879                                                   int /*iteration*/) {
4880   FILE* xmlout = NULL;
4881   FilePath output_file(output_file_);
4882   FilePath output_dir(output_file.RemoveFileName());
4883 
4884   if (output_dir.CreateDirectoriesRecursively()) {
4885     xmlout = posix::FOpen(output_file_.c_str(), "w");
4886   }
4887   if (xmlout == NULL) {
4888     // TODO(wan): report the reason of the failure.
4889     //
4890     // We don't do it for now as:
4891     //
4892     //   1. There is no urgent need for it.
4893     //   2. It's a bit involved to make the errno variable thread-safe on
4894     //      all three operating systems (Linux, Windows, and Mac OS).
4895     //   3. To interpret the meaning of errno in a thread-safe way,
4896     //      we need the strerror_r() function, which is not available on
4897     //      Windows.
4898     fprintf(stderr,
4899             "Unable to open file \"%s\"\n",
4900             output_file_.c_str());
4901     fflush(stderr);
4902     exit(EXIT_FAILURE);
4903   }
4904   std::stringstream stream;
4905   PrintXmlUnitTest(&stream, unit_test);
4906   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4907   fclose(xmlout);
4908 }
4909 
4910 // Returns an XML-escaped copy of the input string str.  If is_attribute
4911 // is true, the text is meant to appear as an attribute value, and
4912 // normalizable whitespace is preserved by replacing it with character
4913 // references.
4914 //
4915 // Invalid XML characters in str, if any, are stripped from the output.
4916 // It is expected that most, if not all, of the text processed by this
4917 // module will consist of ordinary English text.
4918 // If this module is ever modified to produce version 1.1 XML output,
4919 // most invalid characters can be retained using character references.
4920 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4921 // escaping scheme for invalid characters, rather than dropping them.
EscapeXml(const std::string & str,bool is_attribute)4922 std::string XmlUnitTestResultPrinter::EscapeXml(
4923     const std::string& str, bool is_attribute) {
4924   Message m;
4925 
4926   for (size_t i = 0; i < str.size(); ++i) {
4927     const char ch = str[i];
4928     switch (ch) {
4929       case '<':
4930         m << "&lt;";
4931         break;
4932       case '>':
4933         m << "&gt;";
4934         break;
4935       case '&':
4936         m << "&amp;";
4937         break;
4938       case '\'':
4939         if (is_attribute)
4940           m << "&apos;";
4941         else
4942           m << '\'';
4943         break;
4944       case '"':
4945         if (is_attribute)
4946           m << "&quot;";
4947         else
4948           m << '"';
4949         break;
4950       default:
4951         if (IsValidXmlCharacter(ch)) {
4952           if (is_attribute && IsNormalizableWhitespace(ch))
4953             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4954               << ";";
4955           else
4956             m << ch;
4957         }
4958         break;
4959     }
4960   }
4961 
4962   return m.GetString();
4963 }
4964 
4965 // Returns the given string with all characters invalid in XML removed.
4966 // Currently invalid characters are dropped from the string. An
4967 // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)4968 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4969     const std::string& str) {
4970   std::string output;
4971   output.reserve(str.size());
4972   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4973     if (IsValidXmlCharacter(*it))
4974       output.push_back(*it);
4975 
4976   return output;
4977 }
4978 
4979 // The following routines generate an XML representation of a UnitTest
4980 // object.
4981 //
4982 // This is how Google Test concepts map to the DTD:
4983 //
4984 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
4985 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
4986 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
4987 //       <failure message="...">...</failure>
4988 //       <failure message="...">...</failure>
4989 //       <failure message="...">...</failure>
4990 //                                     <-- individual assertion failures
4991 //     </testcase>
4992 //   </testsuite>
4993 // </testsuites>
4994 
4995 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)4996 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4997   ::std::stringstream ss;
4998   ss << (static_cast<double>(ms) * 1e-3);
4999   return ss.str();
5000 }
5001 
PortableLocaltime(time_t seconds,struct tm * out)5002 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5003 #if defined(_MSC_VER)
5004   return localtime_s(out, &seconds) == 0;
5005 #elif defined(__MINGW32__) || defined(__MINGW64__)
5006   // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5007   // Windows' localtime(), which has a thread-local tm buffer.
5008   struct tm* tm_ptr = localtime(&seconds);  // NOLINT
5009   if (tm_ptr == NULL)
5010     return false;
5011   *out = *tm_ptr;
5012   return true;
5013 #else
5014   return localtime_r(&seconds, out) != NULL;
5015 #endif
5016 }
5017 
5018 // Converts the given epoch time in milliseconds to a date string in the ISO
5019 // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)5020 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5021   struct tm time_struct;
5022   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5023     return "";
5024   // YYYY-MM-DDThh:mm:ss
5025   return StreamableToString(time_struct.tm_year + 1900) + "-" +
5026       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5027       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5028       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5029       String::FormatIntWidth2(time_struct.tm_min) + ":" +
5030       String::FormatIntWidth2(time_struct.tm_sec);
5031 }
5032 
5033 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)5034 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5035                                                      const char* data) {
5036   const char* segment = data;
5037   *stream << "<![CDATA[";
5038   for (;;) {
5039     const char* const next_segment = strstr(segment, "]]>");
5040     if (next_segment != NULL) {
5041       stream->write(
5042           segment, static_cast<std::streamsize>(next_segment - segment));
5043       *stream << "]]>]]&gt;<![CDATA[";
5044       segment = next_segment + strlen("]]>");
5045     } else {
5046       *stream << segment;
5047       break;
5048     }
5049   }
5050   *stream << "]]>";
5051 }
5052 
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)5053 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5054     std::ostream* stream,
5055     const std::string& element_name,
5056     const std::string& name,
5057     const std::string& value) {
5058   const std::vector<std::string>& allowed_names =
5059       GetReservedAttributesForElement(element_name);
5060 
5061   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5062                    allowed_names.end())
5063       << "Attribute " << name << " is not allowed for element <" << element_name
5064       << ">.";
5065 
5066   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5067 }
5068 
5069 // Prints an XML representation of a TestInfo object.
5070 // 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)5071 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5072                                                  const char* test_case_name,
5073                                                  const TestInfo& test_info) {
5074   const TestResult& result = *test_info.result();
5075   const std::string kTestcase = "testcase";
5076 
5077   *stream << "    <testcase";
5078   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
5079 
5080   if (test_info.value_param() != NULL) {
5081     OutputXmlAttribute(stream, kTestcase, "value_param",
5082                        test_info.value_param());
5083   }
5084   if (test_info.type_param() != NULL) {
5085     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
5086   }
5087 
5088   OutputXmlAttribute(stream, kTestcase, "status",
5089                      test_info.should_run() ? "run" : "notrun");
5090   OutputXmlAttribute(stream, kTestcase, "time",
5091                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
5092   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
5093   *stream << TestPropertiesAsXmlAttributes(result);
5094 
5095   int failures = 0;
5096   for (int i = 0; i < result.total_part_count(); ++i) {
5097     const TestPartResult& part = result.GetTestPartResult(i);
5098     if (part.failed()) {
5099       if (++failures == 1) {
5100         *stream << ">\n";
5101       }
5102       const string location = internal::FormatCompilerIndependentFileLocation(
5103           part.file_name(), part.line_number());
5104       const string summary = location + "\n" + part.summary();
5105       *stream << "      <failure message=\""
5106               << EscapeXmlAttribute(summary.c_str())
5107               << "\" type=\"\">";
5108       const string detail = location + "\n" + part.message();
5109       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5110       *stream << "</failure>\n";
5111     }
5112   }
5113 
5114   if (failures == 0)
5115     *stream << " />\n";
5116   else
5117     *stream << "    </testcase>\n";
5118 }
5119 
5120 // Prints an XML representation of a TestCase object
PrintXmlTestCase(std::ostream * stream,const TestCase & test_case)5121 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
5122                                                 const TestCase& test_case) {
5123   const std::string kTestsuite = "testsuite";
5124   *stream << "  <" << kTestsuite;
5125   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
5126   OutputXmlAttribute(stream, kTestsuite, "tests",
5127                      StreamableToString(test_case.reportable_test_count()));
5128   OutputXmlAttribute(stream, kTestsuite, "failures",
5129                      StreamableToString(test_case.failed_test_count()));
5130   OutputXmlAttribute(
5131       stream, kTestsuite, "disabled",
5132       StreamableToString(test_case.reportable_disabled_test_count()));
5133   OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5134   OutputXmlAttribute(stream, kTestsuite, "time",
5135                      FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
5136   *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
5137           << ">\n";
5138 
5139   for (int i = 0; i < test_case.total_test_count(); ++i) {
5140     if (test_case.GetTestInfo(i)->is_reportable())
5141       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
5142   }
5143   *stream << "  </" << kTestsuite << ">\n";
5144 }
5145 
5146 // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)5147 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5148                                                 const UnitTest& unit_test) {
5149   const std::string kTestsuites = "testsuites";
5150 
5151   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5152   *stream << "<" << kTestsuites;
5153 
5154   OutputXmlAttribute(stream, kTestsuites, "tests",
5155                      StreamableToString(unit_test.reportable_test_count()));
5156   OutputXmlAttribute(stream, kTestsuites, "failures",
5157                      StreamableToString(unit_test.failed_test_count()));
5158   OutputXmlAttribute(
5159       stream, kTestsuites, "disabled",
5160       StreamableToString(unit_test.reportable_disabled_test_count()));
5161   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5162   OutputXmlAttribute(
5163       stream, kTestsuites, "timestamp",
5164       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5165   OutputXmlAttribute(stream, kTestsuites, "time",
5166                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5167 
5168   if (GTEST_FLAG(shuffle)) {
5169     OutputXmlAttribute(stream, kTestsuites, "random_seed",
5170                        StreamableToString(unit_test.random_seed()));
5171   }
5172 
5173   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5174 
5175   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5176   *stream << ">\n";
5177 
5178   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
5179     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
5180       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
5181   }
5182   *stream << "</" << kTestsuites << ">\n";
5183 }
5184 
5185 // Produces a string representing the test properties in a result as space
5186 // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)5187 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5188     const TestResult& result) {
5189   Message attributes;
5190   for (int i = 0; i < result.test_property_count(); ++i) {
5191     const TestProperty& property = result.GetTestProperty(i);
5192     attributes << " " << property.key() << "="
5193         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5194   }
5195   return attributes.GetString();
5196 }
5197 
5198 // End XmlUnitTestResultPrinter
5199 
5200 #if GTEST_CAN_STREAM_RESULTS_
5201 
5202 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5203 // replaces them by "%xx" where xx is their hexadecimal value. For
5204 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
5205 // in both time and space -- important as the input str may contain an
5206 // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)5207 string StreamingListener::UrlEncode(const char* str) {
5208   string result;
5209   result.reserve(strlen(str) + 1);
5210   for (char ch = *str; ch != '\0'; ch = *++str) {
5211     switch (ch) {
5212       case '%':
5213       case '=':
5214       case '&':
5215       case '\n':
5216         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5217         break;
5218       default:
5219         result.push_back(ch);
5220         break;
5221     }
5222   }
5223   return result;
5224 }
5225 
MakeConnection()5226 void StreamingListener::SocketWriter::MakeConnection() {
5227   GTEST_CHECK_(sockfd_ == -1)
5228       << "MakeConnection() can't be called when there is already a connection.";
5229 
5230   addrinfo hints;
5231   memset(&hints, 0, sizeof(hints));
5232   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
5233   hints.ai_socktype = SOCK_STREAM;
5234   addrinfo* servinfo = NULL;
5235 
5236   // Use the getaddrinfo() to get a linked list of IP addresses for
5237   // the given host name.
5238   const int error_num = getaddrinfo(
5239       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5240   if (error_num != 0) {
5241     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5242                         << gai_strerror(error_num);
5243   }
5244 
5245   // Loop through all the results and connect to the first we can.
5246   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
5247        cur_addr = cur_addr->ai_next) {
5248     sockfd_ = socket(
5249         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5250     if (sockfd_ != -1) {
5251       // Connect the client socket to the server socket.
5252       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5253         close(sockfd_);
5254         sockfd_ = -1;
5255       }
5256     }
5257   }
5258 
5259   freeaddrinfo(servinfo);  // all done with this structure
5260 
5261   if (sockfd_ == -1) {
5262     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5263                         << host_name_ << ":" << port_num_;
5264   }
5265 }
5266 
5267 // End of class Streaming Listener
5268 #endif  // GTEST_CAN_STREAM_RESULTS__
5269 
5270 // Class ScopedTrace
5271 
5272 // Pushes the given source file location and message onto a per-thread
5273 // trace stack maintained by Google Test.
ScopedTrace(const char * file,int line,const Message & message)5274 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
5275     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
5276   TraceInfo trace;
5277   trace.file = file;
5278   trace.line = line;
5279   trace.message = message.GetString();
5280 
5281   UnitTest::GetInstance()->PushGTestTrace(trace);
5282 }
5283 
5284 // Pops the info pushed by the c'tor.
~ScopedTrace()5285 ScopedTrace::~ScopedTrace()
5286     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
5287   UnitTest::GetInstance()->PopGTestTrace();
5288 }
5289 
5290 
5291 // class OsStackTraceGetter
5292 
5293 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5294     "... " GTEST_NAME_ " internal frames ...";
5295 
CurrentStackTrace(int,int)5296 string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,
5297                                              int /*skip_count*/) {
5298   return "";
5299 }
5300 
UponLeavingGTest()5301 void OsStackTraceGetter::UponLeavingGTest() {}
5302 
5303 // A helper class that creates the premature-exit file in its
5304 // constructor and deletes the file in its destructor.
5305 class ScopedPrematureExitFile {
5306  public:
ScopedPrematureExitFile(const char * premature_exit_filepath)5307   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5308       : premature_exit_filepath_(premature_exit_filepath) {
5309     // If a path to the premature-exit file is specified...
5310     if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
5311       // create the file with a single "0" character in it.  I/O
5312       // errors are ignored as there's nothing better we can do and we
5313       // don't want to fail the test because of this.
5314       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5315       fwrite("0", 1, 1, pfile);
5316       fclose(pfile);
5317     }
5318   }
5319 
~ScopedPrematureExitFile()5320   ~ScopedPrematureExitFile() {
5321     if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
5322       remove(premature_exit_filepath_);
5323     }
5324   }
5325 
5326  private:
5327   const char* const premature_exit_filepath_;
5328 
5329   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5330 };
5331 
5332 }  // namespace internal
5333 
5334 // class TestEventListeners
5335 
TestEventListeners()5336 TestEventListeners::TestEventListeners()
5337     : repeater_(new internal::TestEventRepeater()),
5338       default_result_printer_(NULL),
5339       default_xml_generator_(NULL) {
5340 }
5341 
~TestEventListeners()5342 TestEventListeners::~TestEventListeners() { delete repeater_; }
5343 
5344 // Returns the standard listener responsible for the default console
5345 // output.  Can be removed from the listeners list to shut down default
5346 // console output.  Note that removing this object from the listener list
5347 // with Release transfers its ownership to the user.
Append(TestEventListener * listener)5348 void TestEventListeners::Append(TestEventListener* listener) {
5349   repeater_->Append(listener);
5350 }
5351 
5352 // Removes the given event listener from the list and returns it.  It then
5353 // becomes the caller's responsibility to delete the listener. Returns
5354 // NULL if the listener is not found in the list.
Release(TestEventListener * listener)5355 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5356   if (listener == default_result_printer_)
5357     default_result_printer_ = NULL;
5358   else if (listener == default_xml_generator_)
5359     default_xml_generator_ = NULL;
5360   return repeater_->Release(listener);
5361 }
5362 
5363 // Returns repeater that broadcasts the TestEventListener events to all
5364 // subscribers.
repeater()5365 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5366 
5367 // Sets the default_result_printer attribute to the provided listener.
5368 // The listener is also added to the listener list and previous
5369 // default_result_printer is removed from it and deleted. The listener can
5370 // also be NULL in which case it will not be added to the list. Does
5371 // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)5372 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5373   if (default_result_printer_ != listener) {
5374     // It is an error to pass this method a listener that is already in the
5375     // list.
5376     delete Release(default_result_printer_);
5377     default_result_printer_ = listener;
5378     if (listener != NULL)
5379       Append(listener);
5380   }
5381 }
5382 
5383 // Sets the default_xml_generator attribute to the provided listener.  The
5384 // listener is also added to the listener list and previous
5385 // default_xml_generator is removed from it and deleted. The listener can
5386 // also be NULL in which case it will not be added to the list. Does
5387 // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)5388 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5389   if (default_xml_generator_ != listener) {
5390     // It is an error to pass this method a listener that is already in the
5391     // list.
5392     delete Release(default_xml_generator_);
5393     default_xml_generator_ = listener;
5394     if (listener != NULL)
5395       Append(listener);
5396   }
5397 }
5398 
5399 // Controls whether events will be forwarded by the repeater to the
5400 // listeners in the list.
EventForwardingEnabled() const5401 bool TestEventListeners::EventForwardingEnabled() const {
5402   return repeater_->forwarding_enabled();
5403 }
5404 
SuppressEventForwarding()5405 void TestEventListeners::SuppressEventForwarding() {
5406   repeater_->set_forwarding_enabled(false);
5407 }
5408 
5409 // class UnitTest
5410 
5411 // Gets the singleton UnitTest object.  The first time this method is
5412 // called, a UnitTest object is constructed and returned.  Consecutive
5413 // calls will return the same object.
5414 //
5415 // We don't protect this under mutex_ as a user is not supposed to
5416 // call this before main() starts, from which point on the return
5417 // value will never change.
GetInstance()5418 UnitTest* UnitTest::GetInstance() {
5419   // When compiled with MSVC 7.1 in optimized mode, destroying the
5420   // UnitTest object upon exiting the program messes up the exit code,
5421   // causing successful tests to appear failed.  We have to use a
5422   // different implementation in this case to bypass the compiler bug.
5423   // This implementation makes the compiler happy, at the cost of
5424   // leaking the UnitTest object.
5425 
5426   // CodeGear C++Builder insists on a public destructor for the
5427   // default implementation.  Use this implementation to keep good OO
5428   // design with private destructor.
5429 
5430 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5431   static UnitTest* const instance = new UnitTest;
5432   return instance;
5433 #else
5434   static UnitTest instance;
5435   return &instance;
5436 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5437 }
5438 
5439 // Gets the number of successful test cases.
successful_test_case_count() const5440 int UnitTest::successful_test_case_count() const {
5441   return impl()->successful_test_case_count();
5442 }
5443 
5444 // Gets the number of failed test cases.
failed_test_case_count() const5445 int UnitTest::failed_test_case_count() const {
5446   return impl()->failed_test_case_count();
5447 }
5448 
5449 // Gets the number of all test cases.
total_test_case_count() const5450 int UnitTest::total_test_case_count() const {
5451   return impl()->total_test_case_count();
5452 }
5453 
5454 // Gets the number of all test cases that contain at least one test
5455 // that should run.
test_case_to_run_count() const5456 int UnitTest::test_case_to_run_count() const {
5457   return impl()->test_case_to_run_count();
5458 }
5459 
5460 // Gets the number of successful tests.
successful_test_count() const5461 int UnitTest::successful_test_count() const {
5462   return impl()->successful_test_count();
5463 }
5464 
5465 // Gets the number of failed tests.
failed_test_count() const5466 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5467 
5468 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const5469 int UnitTest::reportable_disabled_test_count() const {
5470   return impl()->reportable_disabled_test_count();
5471 }
5472 
5473 // Gets the number of disabled tests.
disabled_test_count() const5474 int UnitTest::disabled_test_count() const {
5475   return impl()->disabled_test_count();
5476 }
5477 
5478 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const5479 int UnitTest::reportable_test_count() const {
5480   return impl()->reportable_test_count();
5481 }
5482 
5483 // Gets the number of all tests.
total_test_count() const5484 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5485 
5486 // Gets the number of tests that should run.
test_to_run_count() const5487 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5488 
5489 // Gets the time of the test program start, in ms from the start of the
5490 // UNIX epoch.
start_timestamp() const5491 internal::TimeInMillis UnitTest::start_timestamp() const {
5492     return impl()->start_timestamp();
5493 }
5494 
5495 // Gets the elapsed time, in milliseconds.
elapsed_time() const5496 internal::TimeInMillis UnitTest::elapsed_time() const {
5497   return impl()->elapsed_time();
5498 }
5499 
5500 // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const5501 bool UnitTest::Passed() const { return impl()->Passed(); }
5502 
5503 // Returns true iff the unit test failed (i.e. some test case failed
5504 // or something outside of all tests failed).
Failed() const5505 bool UnitTest::Failed() const { return impl()->Failed(); }
5506 
5507 // Gets the i-th test case among all the test cases. i can range from 0 to
5508 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const5509 const TestCase* UnitTest::GetTestCase(int i) const {
5510   return impl()->GetTestCase(i);
5511 }
5512 
5513 // Returns the TestResult containing information on test failures and
5514 // properties logged outside of individual test cases.
ad_hoc_test_result() const5515 const TestResult& UnitTest::ad_hoc_test_result() const {
5516   return *impl()->ad_hoc_test_result();
5517 }
5518 
5519 // Gets the i-th test case among all the test cases. i can range from 0 to
5520 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)5521 TestCase* UnitTest::GetMutableTestCase(int i) {
5522   return impl()->GetMutableTestCase(i);
5523 }
5524 
5525 // Returns the list of event listeners that can be used to track events
5526 // inside Google Test.
listeners()5527 TestEventListeners& UnitTest::listeners() {
5528   return *impl()->listeners();
5529 }
5530 
5531 // Registers and returns a global test environment.  When a test
5532 // program is run, all global test environments will be set-up in the
5533 // order they were registered.  After all tests in the program have
5534 // finished, all global test environments will be torn-down in the
5535 // *reverse* order they were registered.
5536 //
5537 // The UnitTest object takes ownership of the given environment.
5538 //
5539 // We don't protect this under mutex_, as we only support calling it
5540 // from the main thread.
AddEnvironment(Environment * env)5541 Environment* UnitTest::AddEnvironment(Environment* env) {
5542   if (env == NULL) {
5543     return NULL;
5544   }
5545 
5546   impl_->environments().push_back(env);
5547   return env;
5548 }
5549 
5550 // Adds a TestPartResult to the current TestResult object.  All Google Test
5551 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5552 // this to report their results.  The user code should use the
5553 // 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)5554 void UnitTest::AddTestPartResult(
5555     TestPartResult::Type result_type,
5556     const char* file_name,
5557     int line_number,
5558     const std::string& message,
5559     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
5560   Message msg;
5561   msg << message;
5562 
5563   internal::MutexLock lock(&mutex_);
5564   if (impl_->gtest_trace_stack().size() > 0) {
5565     msg << "\n" << GTEST_NAME_ << " trace:";
5566 
5567     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5568          i > 0; --i) {
5569       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5570       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5571           << " " << trace.message;
5572     }
5573   }
5574 
5575   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5576     msg << internal::kStackTraceMarker << os_stack_trace;
5577   }
5578 
5579   const TestPartResult result =
5580     TestPartResult(result_type, file_name, line_number,
5581                    msg.GetString().c_str());
5582   impl_->GetTestPartResultReporterForCurrentThread()->
5583       ReportTestPartResult(result);
5584 
5585   if (result_type != TestPartResult::kSuccess) {
5586     // gtest_break_on_failure takes precedence over
5587     // gtest_throw_on_failure.  This allows a user to set the latter
5588     // in the code (perhaps in order to use Google Test assertions
5589     // with another testing framework) and specify the former on the
5590     // command line for debugging.
5591     if (GTEST_FLAG(break_on_failure)) {
5592 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5593       // Using DebugBreak on Windows allows gtest to still break into a debugger
5594       // when a failure happens and both the --gtest_break_on_failure and
5595       // the --gtest_catch_exceptions flags are specified.
5596       DebugBreak();
5597 #else
5598       // Dereference NULL through a volatile pointer to prevent the compiler
5599       // from removing. We use this rather than abort() or __builtin_trap() for
5600       // portability: Symbian doesn't implement abort() well, and some debuggers
5601       // don't correctly trap abort().
5602       *static_cast<volatile int*>(NULL) = 1;
5603 #endif  // GTEST_OS_WINDOWS
5604     } else if (GTEST_FLAG(throw_on_failure)) {
5605 #if GTEST_HAS_EXCEPTIONS
5606       throw internal::GoogleTestFailureException(result);
5607 #else
5608       // We cannot call abort() as it generates a pop-up in debug mode
5609       // that cannot be suppressed in VC 7.1 or below.
5610       exit(1);
5611 #endif
5612     }
5613   }
5614 }
5615 
5616 // Adds a TestProperty to the current TestResult object when invoked from
5617 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5618 // from SetUpTestCase or TearDownTestCase, or to the global property set
5619 // when invoked elsewhere.  If the result already contains a property with
5620 // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)5621 void UnitTest::RecordProperty(const std::string& key,
5622                               const std::string& value) {
5623   impl_->RecordProperty(TestProperty(key, value));
5624 }
5625 
5626 // Runs all tests in this UnitTest object and prints the result.
5627 // Returns 0 if successful, or 1 otherwise.
5628 //
5629 // We don't protect this under mutex_, as we only support calling it
5630 // from the main thread.
Run()5631 int UnitTest::Run() {
5632   const bool in_death_test_child_process =
5633       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5634 
5635   // Google Test implements this protocol for catching that a test
5636   // program exits before returning control to Google Test:
5637   //
5638   //   1. Upon start, Google Test creates a file whose absolute path
5639   //      is specified by the environment variable
5640   //      TEST_PREMATURE_EXIT_FILE.
5641   //   2. When Google Test has finished its work, it deletes the file.
5642   //
5643   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5644   // running a Google-Test-based test program and check the existence
5645   // of the file at the end of the test execution to see if it has
5646   // exited prematurely.
5647 
5648   // If we are in the child process of a death test, don't
5649   // create/delete the premature exit file, as doing so is unnecessary
5650   // and will confuse the parent process.  Otherwise, create/delete
5651   // the file upon entering/leaving this function.  If the program
5652   // somehow exits before this function has a chance to return, the
5653   // premature-exit file will be left undeleted, causing a test runner
5654   // that understands the premature-exit-file protocol to report the
5655   // test as having failed.
5656   const internal::ScopedPrematureExitFile premature_exit_file(
5657       in_death_test_child_process ?
5658       NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5659 
5660   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
5661   // used for the duration of the program.
5662   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5663 
5664 #if GTEST_HAS_SEH
5665   // Either the user wants Google Test to catch exceptions thrown by the
5666   // tests or this is executing in the context of death test child
5667   // process. In either case the user does not want to see pop-up dialogs
5668   // about crashes - they are expected.
5669   if (impl()->catch_exceptions() || in_death_test_child_process) {
5670 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5671     // SetErrorMode doesn't exist on CE.
5672     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5673                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5674 # endif  // !GTEST_OS_WINDOWS_MOBILE
5675 
5676 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5677     // Death test children can be terminated with _abort().  On Windows,
5678     // _abort() can show a dialog with a warning message.  This forces the
5679     // abort message to go to stderr instead.
5680     _set_error_mode(_OUT_TO_STDERR);
5681 # endif
5682 
5683 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5684     // In the debug version, Visual Studio pops up a separate dialog
5685     // offering a choice to debug the aborted program. We need to suppress
5686     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5687     // executed. Google Test will notify the user of any unexpected
5688     // failure via stderr.
5689     //
5690     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5691     // Users of prior VC versions shall suffer the agony and pain of
5692     // clicking through the countless debug dialogs.
5693     // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5694     // debug mode when compiled with VC 7.1 or lower.
5695     if (!GTEST_FLAG(break_on_failure))
5696       _set_abort_behavior(
5697           0x0,                                    // Clear the following flags:
5698           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
5699 # endif
5700   }
5701 #endif  // GTEST_HAS_SEH
5702 
5703   return internal::HandleExceptionsInMethodIfSupported(
5704       impl(),
5705       &internal::UnitTestImpl::RunAllTests,
5706       "auxiliary test code (environments or event listeners)") ? 0 : 1;
5707 }
5708 
5709 // Returns the working directory when the first TEST() or TEST_F() was
5710 // executed.
original_working_dir() const5711 const char* UnitTest::original_working_dir() const {
5712   return impl_->original_working_dir_.c_str();
5713 }
5714 
5715 // Returns the TestCase object for the test that's currently running,
5716 // or NULL if no test is running.
current_test_case() const5717 const TestCase* UnitTest::current_test_case() const
5718     GTEST_LOCK_EXCLUDED_(mutex_) {
5719   internal::MutexLock lock(&mutex_);
5720   return impl_->current_test_case();
5721 }
5722 
5723 // Returns the TestInfo object for the test that's currently running,
5724 // or NULL if no test is running.
current_test_info() const5725 const TestInfo* UnitTest::current_test_info() const
5726     GTEST_LOCK_EXCLUDED_(mutex_) {
5727   internal::MutexLock lock(&mutex_);
5728   return impl_->current_test_info();
5729 }
5730 
5731 // Returns the random seed used at the start of the current test run.
random_seed() const5732 int UnitTest::random_seed() const { return impl_->random_seed(); }
5733 
5734 #if GTEST_HAS_PARAM_TEST
5735 // Returns ParameterizedTestCaseRegistry object used to keep track of
5736 // value-parameterized tests and instantiate and register them.
5737 internal::ParameterizedTestCaseRegistry&
parameterized_test_registry()5738     UnitTest::parameterized_test_registry()
5739         GTEST_LOCK_EXCLUDED_(mutex_) {
5740   return impl_->parameterized_test_registry();
5741 }
5742 #endif  // GTEST_HAS_PARAM_TEST
5743 
5744 // Creates an empty UnitTest.
UnitTest()5745 UnitTest::UnitTest() {
5746   impl_ = new internal::UnitTestImpl(this);
5747 }
5748 
5749 // Destructor of UnitTest.
~UnitTest()5750 UnitTest::~UnitTest() {
5751   delete impl_;
5752 }
5753 
5754 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5755 // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)5756 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5757     GTEST_LOCK_EXCLUDED_(mutex_) {
5758   internal::MutexLock lock(&mutex_);
5759   impl_->gtest_trace_stack().push_back(trace);
5760 }
5761 
5762 // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()5763 void UnitTest::PopGTestTrace()
5764     GTEST_LOCK_EXCLUDED_(mutex_) {
5765   internal::MutexLock lock(&mutex_);
5766   impl_->gtest_trace_stack().pop_back();
5767 }
5768 
5769 namespace internal {
5770 
UnitTestImpl(UnitTest * parent)5771 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5772     : parent_(parent),
5773       GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
5774       default_global_test_part_result_reporter_(this),
5775       default_per_thread_test_part_result_reporter_(this),
5776       GTEST_DISABLE_MSC_WARNINGS_POP_()
5777       global_test_part_result_repoter_(
5778           &default_global_test_part_result_reporter_),
5779       per_thread_test_part_result_reporter_(
5780           &default_per_thread_test_part_result_reporter_),
5781 #if GTEST_HAS_PARAM_TEST
5782       parameterized_test_registry_(),
5783       parameterized_tests_registered_(false),
5784 #endif  // GTEST_HAS_PARAM_TEST
5785       last_death_test_case_(-1),
5786       current_test_case_(NULL),
5787       current_test_info_(NULL),
5788       ad_hoc_test_result_(),
5789       os_stack_trace_getter_(NULL),
5790       post_flag_parse_init_performed_(false),
5791       random_seed_(0),  // Will be overridden by the flag before first use.
5792       random_(0),  // Will be reseeded before first use.
5793       start_timestamp_(0),
5794       elapsed_time_(0),
5795 #if GTEST_HAS_DEATH_TEST
5796       death_test_factory_(new DefaultDeathTestFactory),
5797 #endif
5798       // Will be overridden by the flag before first use.
5799       catch_exceptions_(false) {
5800   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5801 }
5802 
~UnitTestImpl()5803 UnitTestImpl::~UnitTestImpl() {
5804   // Deletes every TestCase.
5805   ForEach(test_cases_, internal::Delete<TestCase>);
5806 
5807   // Deletes every Environment.
5808   ForEach(environments_, internal::Delete<Environment>);
5809 
5810   delete os_stack_trace_getter_;
5811 }
5812 
5813 // Adds a TestProperty to the current TestResult object when invoked in a
5814 // context of a test, to current test case's ad_hoc_test_result when invoke
5815 // from SetUpTestCase/TearDownTestCase, or to the global property set
5816 // otherwise.  If the result already contains a property with the same key,
5817 // the value will be updated.
RecordProperty(const TestProperty & test_property)5818 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5819   std::string xml_element;
5820   TestResult* test_result;  // TestResult appropriate for property recording.
5821 
5822   if (current_test_info_ != NULL) {
5823     xml_element = "testcase";
5824     test_result = &(current_test_info_->result_);
5825   } else if (current_test_case_ != NULL) {
5826     xml_element = "testsuite";
5827     test_result = &(current_test_case_->ad_hoc_test_result_);
5828   } else {
5829     xml_element = "testsuites";
5830     test_result = &ad_hoc_test_result_;
5831   }
5832   test_result->RecordProperty(xml_element, test_property);
5833 }
5834 
5835 #if GTEST_HAS_DEATH_TEST
5836 // Disables event forwarding if the control is currently in a death test
5837 // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()5838 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5839   if (internal_run_death_test_flag_.get() != NULL)
5840     listeners()->SuppressEventForwarding();
5841 }
5842 #endif  // GTEST_HAS_DEATH_TEST
5843 
5844 // Initializes event listeners performing XML output as specified by
5845 // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()5846 void UnitTestImpl::ConfigureXmlOutput() {
5847   const std::string& output_format = UnitTestOptions::GetOutputFormat();
5848   if (output_format == "xml") {
5849     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5850         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5851   } else if (output_format != "") {
5852     printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5853            output_format.c_str());
5854     fflush(stdout);
5855   }
5856 }
5857 
5858 #if GTEST_CAN_STREAM_RESULTS_
5859 // Initializes event listeners for streaming test results in string form.
5860 // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()5861 void UnitTestImpl::ConfigureStreamingOutput() {
5862   const std::string& target = GTEST_FLAG(stream_result_to);
5863   if (!target.empty()) {
5864     const size_t pos = target.find(':');
5865     if (pos != std::string::npos) {
5866       listeners()->Append(new StreamingListener(target.substr(0, pos),
5867                                                 target.substr(pos+1)));
5868     } else {
5869       printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5870              target.c_str());
5871       fflush(stdout);
5872     }
5873   }
5874 }
5875 #endif  // GTEST_CAN_STREAM_RESULTS_
5876 
5877 // Performs initialization dependent upon flag values obtained in
5878 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
5879 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
5880 // this function is also called from RunAllTests.  Since this function can be
5881 // called more than once, it has to be idempotent.
PostFlagParsingInit()5882 void UnitTestImpl::PostFlagParsingInit() {
5883   // Ensures that this function does not execute more than once.
5884   if (!post_flag_parse_init_performed_) {
5885     post_flag_parse_init_performed_ = true;
5886 
5887 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5888     // Register to send notifications about key process state changes.
5889     listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5890 #endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5891 
5892 #if GTEST_HAS_DEATH_TEST
5893     InitDeathTestSubprocessControlInfo();
5894     SuppressTestEventsIfInSubprocess();
5895 #endif  // GTEST_HAS_DEATH_TEST
5896 
5897     // Registers parameterized tests. This makes parameterized tests
5898     // available to the UnitTest reflection API without running
5899     // RUN_ALL_TESTS.
5900     RegisterParameterizedTests();
5901 
5902     // Configures listeners for XML output. This makes it possible for users
5903     // to shut down the default XML output before invoking RUN_ALL_TESTS.
5904     ConfigureXmlOutput();
5905 
5906 #if GTEST_CAN_STREAM_RESULTS_
5907     // Configures listeners for streaming test results to the specified server.
5908     ConfigureStreamingOutput();
5909 #endif  // GTEST_CAN_STREAM_RESULTS_
5910   }
5911 }
5912 
5913 // A predicate that checks the name of a TestCase against a known
5914 // value.
5915 //
5916 // This is used for implementation of the UnitTest class only.  We put
5917 // it in the anonymous namespace to prevent polluting the outer
5918 // namespace.
5919 //
5920 // TestCaseNameIs is copyable.
5921 class TestCaseNameIs {
5922  public:
5923   // Constructor.
TestCaseNameIs(const std::string & name)5924   explicit TestCaseNameIs(const std::string& name)
5925       : name_(name) {}
5926 
5927   // Returns true iff the name of test_case matches name_.
operator ()(const TestCase * test_case) const5928   bool operator()(const TestCase* test_case) const {
5929     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5930   }
5931 
5932  private:
5933   std::string name_;
5934 };
5935 
5936 // Finds and returns a TestCase with the given name.  If one doesn't
5937 // exist, creates one and returns it.  It's the CALLER'S
5938 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5939 // TESTS ARE NOT SHUFFLED.
5940 //
5941 // Arguments:
5942 //
5943 //   test_case_name: name of the test case
5944 //   type_param:     the name of the test case's type parameter, or NULL if
5945 //                   this is not a typed or a type-parameterized test case.
5946 //   set_up_tc:      pointer to the function that sets up the test case
5947 //   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)5948 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5949                                     const char* type_param,
5950                                     Test::SetUpTestCaseFunc set_up_tc,
5951                                     Test::TearDownTestCaseFunc tear_down_tc) {
5952   // Can we find a TestCase with the given name?
5953   const std::vector<TestCase*>::const_iterator test_case =
5954       std::find_if(test_cases_.begin(), test_cases_.end(),
5955                    TestCaseNameIs(test_case_name));
5956 
5957   if (test_case != test_cases_.end())
5958     return *test_case;
5959 
5960   // No.  Let's create one.
5961   TestCase* const new_test_case =
5962       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5963 
5964   // Is this a death test case?
5965   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5966                                                kDeathTestCaseFilter)) {
5967     // Yes.  Inserts the test case after the last death test case
5968     // defined so far.  This only works when the test cases haven't
5969     // been shuffled.  Otherwise we may end up running a death test
5970     // after a non-death test.
5971     ++last_death_test_case_;
5972     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5973                        new_test_case);
5974   } else {
5975     // No.  Appends to the end of the list.
5976     test_cases_.push_back(new_test_case);
5977   }
5978 
5979   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5980   return new_test_case;
5981 }
5982 
5983 // Helpers for setting up / tearing down the given environment.  They
5984 // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)5985 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)5986 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5987 
5988 // Runs all tests in this UnitTest object, prints the result, and
5989 // returns true if all tests are successful.  If any exception is
5990 // thrown during a test, the test is considered to be failed, but the
5991 // rest of the tests will still be run.
5992 //
5993 // When parameterized tests are enabled, it expands and registers
5994 // parameterized tests first in RegisterParameterizedTests().
5995 // All other functions called from RunAllTests() may safely assume that
5996 // parameterized tests are ready to be counted and run.
RunAllTests()5997 bool UnitTestImpl::RunAllTests() {
5998   // Makes sure InitGoogleTest() was called.
5999   if (!GTestIsInitialized()) {
6000     printf("%s",
6001            "\nThis test program did NOT call ::testing::InitGoogleTest "
6002            "before calling RUN_ALL_TESTS().  Please fix it.\n");
6003     return false;
6004   }
6005 
6006   // Do not run any test if the --help flag was specified.
6007   if (g_help_flag)
6008     return true;
6009 
6010   // Repeats the call to the post-flag parsing initialization in case the
6011   // user didn't call InitGoogleTest.
6012   PostFlagParsingInit();
6013 
6014   // Even if sharding is not on, test runners may want to use the
6015   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6016   // protocol.
6017   internal::WriteToShardStatusFileIfNeeded();
6018 
6019   // True iff we are in a subprocess for running a thread-safe-style
6020   // death test.
6021   bool in_subprocess_for_death_test = false;
6022 
6023 #if GTEST_HAS_DEATH_TEST
6024   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
6025 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6026   if (in_subprocess_for_death_test) {
6027     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6028   }
6029 # endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6030 #endif  // GTEST_HAS_DEATH_TEST
6031 
6032   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6033                                         in_subprocess_for_death_test);
6034 
6035   // Compares the full test names with the filter to decide which
6036   // tests to run.
6037   const bool has_tests_to_run = FilterTests(should_shard
6038                                               ? HONOR_SHARDING_PROTOCOL
6039                                               : IGNORE_SHARDING_PROTOCOL) > 0;
6040 
6041   // Lists the tests and exits if the --gtest_list_tests flag was specified.
6042   if (GTEST_FLAG(list_tests)) {
6043     // This must be called *after* FilterTests() has been called.
6044     ListTestsMatchingFilter();
6045     return true;
6046   }
6047 
6048   random_seed_ = GTEST_FLAG(shuffle) ?
6049       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6050 
6051   // True iff at least one test has failed.
6052   bool failed = false;
6053 
6054   TestEventListener* repeater = listeners()->repeater();
6055 
6056   start_timestamp_ = GetTimeInMillis();
6057   repeater->OnTestProgramStart(*parent_);
6058 
6059   // How many times to repeat the tests?  We don't want to repeat them
6060   // when we are inside the subprocess of a death test.
6061   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6062   // Repeats forever if the repeat count is negative.
6063   const bool forever = repeat < 0;
6064   for (int i = 0; forever || i != repeat; i++) {
6065     // We want to preserve failures generated by ad-hoc test
6066     // assertions executed before RUN_ALL_TESTS().
6067     ClearNonAdHocTestResult();
6068 
6069     const TimeInMillis start = GetTimeInMillis();
6070 
6071     // Shuffles test cases and tests if requested.
6072     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6073       random()->Reseed(random_seed_);
6074       // This should be done before calling OnTestIterationStart(),
6075       // such that a test event listener can see the actual test order
6076       // in the event.
6077       ShuffleTests();
6078     }
6079 
6080     // Tells the unit test event listeners that the tests are about to start.
6081     repeater->OnTestIterationStart(*parent_, i);
6082 
6083     // Runs each test case if there is at least one test to run.
6084     if (has_tests_to_run) {
6085       // Sets up all environments beforehand.
6086       repeater->OnEnvironmentsSetUpStart(*parent_);
6087       ForEach(environments_, SetUpEnvironment);
6088       repeater->OnEnvironmentsSetUpEnd(*parent_);
6089 
6090       // Runs the tests only if there was no fatal failure during global
6091       // set-up.
6092       if (!Test::HasFatalFailure()) {
6093         for (int test_index = 0; test_index < total_test_case_count();
6094              test_index++) {
6095           GetMutableTestCase(test_index)->Run();
6096         }
6097       }
6098 
6099       // Tears down all environments in reverse order afterwards.
6100       repeater->OnEnvironmentsTearDownStart(*parent_);
6101       std::for_each(environments_.rbegin(), environments_.rend(),
6102                     TearDownEnvironment);
6103       repeater->OnEnvironmentsTearDownEnd(*parent_);
6104     }
6105 
6106     elapsed_time_ = GetTimeInMillis() - start;
6107 
6108     // Tells the unit test event listener that the tests have just finished.
6109     repeater->OnTestIterationEnd(*parent_, i);
6110 
6111     // Gets the result and clears it.
6112     if (!Passed()) {
6113       failed = true;
6114     }
6115 
6116     // Restores the original test order after the iteration.  This
6117     // allows the user to quickly repro a failure that happens in the
6118     // N-th iteration without repeating the first (N - 1) iterations.
6119     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6120     // case the user somehow changes the value of the flag somewhere
6121     // (it's always safe to unshuffle the tests).
6122     UnshuffleTests();
6123 
6124     if (GTEST_FLAG(shuffle)) {
6125       // Picks a new random seed for each iteration.
6126       random_seed_ = GetNextRandomSeed(random_seed_);
6127     }
6128   }
6129 
6130   repeater->OnTestProgramEnd(*parent_);
6131 
6132   return !failed;
6133 }
6134 
6135 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6136 // if the variable is present. If a file already exists at this location, this
6137 // function will write over it. If the variable is present, but the file cannot
6138 // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()6139 void WriteToShardStatusFileIfNeeded() {
6140   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6141   if (test_shard_file != NULL) {
6142     FILE* const file = posix::FOpen(test_shard_file, "w");
6143     if (file == NULL) {
6144       ColoredPrintf(COLOR_RED,
6145                     "Could not write to the test shard status file \"%s\" "
6146                     "specified by the %s environment variable.\n",
6147                     test_shard_file, kTestShardStatusFile);
6148       fflush(stdout);
6149       exit(EXIT_FAILURE);
6150     }
6151     fclose(file);
6152   }
6153 }
6154 
6155 // Checks whether sharding is enabled by examining the relevant
6156 // environment variable values. If the variables are present,
6157 // but inconsistent (i.e., shard_index >= total_shards), prints
6158 // an error and exits. If in_subprocess_for_death_test, sharding is
6159 // disabled because it must only be applied to the original test
6160 // 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)6161 bool ShouldShard(const char* total_shards_env,
6162                  const char* shard_index_env,
6163                  bool in_subprocess_for_death_test) {
6164   if (in_subprocess_for_death_test) {
6165     return false;
6166   }
6167 
6168   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6169   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6170 
6171   if (total_shards == -1 && shard_index == -1) {
6172     return false;
6173   } else if (total_shards == -1 && shard_index != -1) {
6174     const Message msg = Message()
6175       << "Invalid environment variables: you have "
6176       << kTestShardIndex << " = " << shard_index
6177       << ", but have left " << kTestTotalShards << " unset.\n";
6178     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6179     fflush(stdout);
6180     exit(EXIT_FAILURE);
6181   } else if (total_shards != -1 && shard_index == -1) {
6182     const Message msg = Message()
6183       << "Invalid environment variables: you have "
6184       << kTestTotalShards << " = " << total_shards
6185       << ", but have left " << kTestShardIndex << " unset.\n";
6186     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6187     fflush(stdout);
6188     exit(EXIT_FAILURE);
6189   } else if (shard_index < 0 || shard_index >= total_shards) {
6190     const Message msg = Message()
6191       << "Invalid environment variables: we require 0 <= "
6192       << kTestShardIndex << " < " << kTestTotalShards
6193       << ", but you have " << kTestShardIndex << "=" << shard_index
6194       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
6195     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6196     fflush(stdout);
6197     exit(EXIT_FAILURE);
6198   }
6199 
6200   return total_shards > 1;
6201 }
6202 
6203 // Parses the environment variable var as an Int32. If it is unset,
6204 // returns default_val. If it is not an Int32, prints an error
6205 // and aborts.
Int32FromEnvOrDie(const char * var,Int32 default_val)6206 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6207   const char* str_val = posix::GetEnv(var);
6208   if (str_val == NULL) {
6209     return default_val;
6210   }
6211 
6212   Int32 result;
6213   if (!ParseInt32(Message() << "The value of environment variable " << var,
6214                   str_val, &result)) {
6215     exit(EXIT_FAILURE);
6216   }
6217   return result;
6218 }
6219 
6220 // Given the total number of shards, the shard index, and the test id,
6221 // returns true iff the test should be run on this shard. The test id is
6222 // some arbitrary but unique non-negative integer assigned to each test
6223 // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)6224 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6225   return (test_id % total_shards) == shard_index;
6226 }
6227 
6228 // Compares the name of each test with the user-specified filter to
6229 // decide whether the test should be run, then records the result in
6230 // each TestCase and TestInfo object.
6231 // If shard_tests == true, further filters tests based on sharding
6232 // variables in the environment - see
6233 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
6234 // Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)6235 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6236   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6237       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6238   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6239       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6240 
6241   // num_runnable_tests are the number of tests that will
6242   // run across all shards (i.e., match filter and are not disabled).
6243   // num_selected_tests are the number of tests to be run on
6244   // this shard.
6245   int num_runnable_tests = 0;
6246   int num_selected_tests = 0;
6247   for (size_t i = 0; i < test_cases_.size(); i++) {
6248     TestCase* const test_case = test_cases_[i];
6249     const std::string &test_case_name = test_case->name();
6250     test_case->set_should_run(false);
6251 
6252     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6253       TestInfo* const test_info = test_case->test_info_list()[j];
6254       const std::string test_name(test_info->name());
6255       // A test is disabled if test case name or test name matches
6256       // kDisableTestFilter.
6257       const bool is_disabled =
6258           internal::UnitTestOptions::MatchesFilter(test_case_name,
6259                                                    kDisableTestFilter) ||
6260           internal::UnitTestOptions::MatchesFilter(test_name,
6261                                                    kDisableTestFilter);
6262       test_info->is_disabled_ = is_disabled;
6263 
6264       const bool matches_filter =
6265           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
6266                                                        test_name);
6267       test_info->matches_filter_ = matches_filter;
6268 
6269       const bool is_runnable =
6270           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6271           matches_filter;
6272 
6273       const bool is_selected = is_runnable &&
6274           (shard_tests == IGNORE_SHARDING_PROTOCOL ||
6275            ShouldRunTestOnShard(total_shards, shard_index,
6276                                 num_runnable_tests));
6277 
6278       num_runnable_tests += is_runnable;
6279       num_selected_tests += is_selected;
6280 
6281       test_info->should_run_ = is_selected;
6282       test_case->set_should_run(test_case->should_run() || is_selected);
6283     }
6284   }
6285   return num_selected_tests;
6286 }
6287 
6288 // Prints the given C-string on a single line by replacing all '\n'
6289 // characters with string "\\n".  If the output takes more than
6290 // max_length characters, only prints the first max_length characters
6291 // and "...".
PrintOnOneLine(const char * str,int max_length)6292 static void PrintOnOneLine(const char* str, int max_length) {
6293   if (str != NULL) {
6294     for (int i = 0; *str != '\0'; ++str) {
6295       if (i >= max_length) {
6296         printf("...");
6297         break;
6298       }
6299       if (*str == '\n') {
6300         printf("\\n");
6301         i += 2;
6302       } else {
6303         printf("%c", *str);
6304         ++i;
6305       }
6306     }
6307   }
6308 }
6309 
6310 // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()6311 void UnitTestImpl::ListTestsMatchingFilter() {
6312   // Print at most this many characters for each type/value parameter.
6313   const int kMaxParamLength = 250;
6314 
6315   for (size_t i = 0; i < test_cases_.size(); i++) {
6316     const TestCase* const test_case = test_cases_[i];
6317     bool printed_test_case_name = false;
6318 
6319     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6320       const TestInfo* const test_info =
6321           test_case->test_info_list()[j];
6322       if (test_info->matches_filter_) {
6323         if (!printed_test_case_name) {
6324           printed_test_case_name = true;
6325           printf("%s.", test_case->name());
6326           if (test_case->type_param() != NULL) {
6327             printf("  # %s = ", kTypeParamLabel);
6328             // We print the type parameter on a single line to make
6329             // the output easy to parse by a program.
6330             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6331           }
6332           printf("\n");
6333         }
6334         printf("  %s", test_info->name());
6335         if (test_info->value_param() != NULL) {
6336           printf("  # %s = ", kValueParamLabel);
6337           // We print the value parameter on a single line to make the
6338           // output easy to parse by a program.
6339           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6340         }
6341         printf("\n");
6342       }
6343     }
6344   }
6345   fflush(stdout);
6346 }
6347 
6348 // Sets the OS stack trace getter.
6349 //
6350 // Does nothing if the input and the current OS stack trace getter are
6351 // the same; otherwise, deletes the old getter and makes the input the
6352 // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)6353 void UnitTestImpl::set_os_stack_trace_getter(
6354     OsStackTraceGetterInterface* getter) {
6355   if (os_stack_trace_getter_ != getter) {
6356     delete os_stack_trace_getter_;
6357     os_stack_trace_getter_ = getter;
6358   }
6359 }
6360 
6361 // Returns the current OS stack trace getter if it is not NULL;
6362 // otherwise, creates an OsStackTraceGetter, makes it the current
6363 // getter, and returns it.
os_stack_trace_getter()6364 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6365   if (os_stack_trace_getter_ == NULL) {
6366 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6367     os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
6368 #else
6369     os_stack_trace_getter_ = new OsStackTraceGetter;
6370 #endif  // GTEST_OS_STACK_TRACE_GETTER_
6371   }
6372 
6373   return os_stack_trace_getter_;
6374 }
6375 
6376 // Returns the TestResult for the test that's currently running, or
6377 // the TestResult for the ad hoc test if no test is running.
current_test_result()6378 TestResult* UnitTestImpl::current_test_result() {
6379   return current_test_info_ ?
6380       &(current_test_info_->result_) : &ad_hoc_test_result_;
6381 }
6382 
6383 // Shuffles all test cases, and the tests within each test case,
6384 // making sure that death tests are still run first.
ShuffleTests()6385 void UnitTestImpl::ShuffleTests() {
6386   // Shuffles the death test cases.
6387   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6388 
6389   // Shuffles the non-death test cases.
6390   ShuffleRange(random(), last_death_test_case_ + 1,
6391                static_cast<int>(test_cases_.size()), &test_case_indices_);
6392 
6393   // Shuffles the tests inside each test case.
6394   for (size_t i = 0; i < test_cases_.size(); i++) {
6395     test_cases_[i]->ShuffleTests(random());
6396   }
6397 }
6398 
6399 // Restores the test cases and tests to their order before the first shuffle.
UnshuffleTests()6400 void UnitTestImpl::UnshuffleTests() {
6401   for (size_t i = 0; i < test_cases_.size(); i++) {
6402     // Unshuffles the tests in each test case.
6403     test_cases_[i]->UnshuffleTests();
6404     // Resets the index of each test case.
6405     test_case_indices_[i] = static_cast<int>(i);
6406   }
6407 }
6408 
6409 // Returns the current OS stack trace as an std::string.
6410 //
6411 // The maximum number of stack frames to be included is specified by
6412 // the gtest_stack_trace_depth flag.  The skip_count parameter
6413 // specifies the number of top frames to be skipped, which doesn't
6414 // count against the number of frames to be included.
6415 //
6416 // For example, if Foo() calls Bar(), which in turn calls
6417 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6418 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)6419 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
6420                                             int skip_count) {
6421   // We pass skip_count + 1 to skip this wrapper function in addition
6422   // to what the user really wants to skip.
6423   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6424 }
6425 
6426 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6427 // suppress unreachable code warnings.
6428 namespace {
6429 class ClassUniqueToAlwaysTrue {};
6430 }
6431 
IsTrue(bool condition)6432 bool IsTrue(bool condition) { return condition; }
6433 
AlwaysTrue()6434 bool AlwaysTrue() {
6435 #if GTEST_HAS_EXCEPTIONS
6436   // This condition is always false so AlwaysTrue() never actually throws,
6437   // but it makes the compiler think that it may throw.
6438   if (IsTrue(false))
6439     throw ClassUniqueToAlwaysTrue();
6440 #endif  // GTEST_HAS_EXCEPTIONS
6441   return true;
6442 }
6443 
6444 // If *pstr starts with the given prefix, modifies *pstr to be right
6445 // past the prefix and returns true; otherwise leaves *pstr unchanged
6446 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)6447 bool SkipPrefix(const char* prefix, const char** pstr) {
6448   const size_t prefix_len = strlen(prefix);
6449   if (strncmp(*pstr, prefix, prefix_len) == 0) {
6450     *pstr += prefix_len;
6451     return true;
6452   }
6453   return false;
6454 }
6455 
6456 // Parses a string as a command line flag.  The string should have
6457 // the format "--flag=value".  When def_optional is true, the "=value"
6458 // part can be omitted.
6459 //
6460 // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)6461 const char* ParseFlagValue(const char* str,
6462                            const char* flag,
6463                            bool def_optional) {
6464   // str and flag must not be NULL.
6465   if (str == NULL || flag == NULL) return NULL;
6466 
6467   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6468   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6469   const size_t flag_len = flag_str.length();
6470   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6471 
6472   // Skips the flag name.
6473   const char* flag_end = str + flag_len;
6474 
6475   // When def_optional is true, it's OK to not have a "=value" part.
6476   if (def_optional && (flag_end[0] == '\0')) {
6477     return flag_end;
6478   }
6479 
6480   // If def_optional is true and there are more characters after the
6481   // flag name, or if def_optional is false, there must be a '=' after
6482   // the flag name.
6483   if (flag_end[0] != '=') return NULL;
6484 
6485   // Returns the string after "=".
6486   return flag_end + 1;
6487 }
6488 
6489 // Parses a string for a bool flag, in the form of either
6490 // "--flag=value" or "--flag".
6491 //
6492 // In the former case, the value is taken as true as long as it does
6493 // not start with '0', 'f', or 'F'.
6494 //
6495 // In the latter case, the value is taken as true.
6496 //
6497 // On success, stores the value of the flag in *value, and returns
6498 // true.  On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)6499 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6500   // Gets the value of the flag as a string.
6501   const char* const value_str = ParseFlagValue(str, flag, true);
6502 
6503   // Aborts if the parsing failed.
6504   if (value_str == NULL) return false;
6505 
6506   // Converts the string value to a bool.
6507   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6508   return true;
6509 }
6510 
6511 // Parses a string for an Int32 flag, in the form of
6512 // "--flag=value".
6513 //
6514 // On success, stores the value of the flag in *value, and returns
6515 // true.  On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,Int32 * value)6516 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6517   // Gets the value of the flag as a string.
6518   const char* const value_str = ParseFlagValue(str, flag, false);
6519 
6520   // Aborts if the parsing failed.
6521   if (value_str == NULL) return false;
6522 
6523   // Sets *value to the value of the flag.
6524   return ParseInt32(Message() << "The value of flag --" << flag,
6525                     value_str, value);
6526 }
6527 
6528 // Parses a string for a string flag, in the form of
6529 // "--flag=value".
6530 //
6531 // On success, stores the value of the flag in *value, and returns
6532 // true.  On failure, returns false without changing *value.
ParseStringFlag(const char * str,const char * flag,std::string * value)6533 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6534   // Gets the value of the flag as a string.
6535   const char* const value_str = ParseFlagValue(str, flag, false);
6536 
6537   // Aborts if the parsing failed.
6538   if (value_str == NULL) return false;
6539 
6540   // Sets *value to the value of the flag.
6541   *value = value_str;
6542   return true;
6543 }
6544 
6545 // Determines whether a string has a prefix that Google Test uses for its
6546 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6547 // If Google Test detects that a command line flag has its prefix but is not
6548 // recognized, it will print its help message. Flags starting with
6549 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6550 // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)6551 static bool HasGoogleTestFlagPrefix(const char* str) {
6552   return (SkipPrefix("--", &str) ||
6553           SkipPrefix("-", &str) ||
6554           SkipPrefix("/", &str)) &&
6555          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6556          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6557           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6558 }
6559 
6560 // Prints a string containing code-encoded text.  The following escape
6561 // sequences can be used in the string to control the text color:
6562 //
6563 //   @@    prints a single '@' character.
6564 //   @R    changes the color to red.
6565 //   @G    changes the color to green.
6566 //   @Y    changes the color to yellow.
6567 //   @D    changes to the default terminal text color.
6568 //
6569 // TODO(wan@google.com): Write tests for this once we add stdout
6570 // capturing to Google Test.
PrintColorEncoded(const char * str)6571 static void PrintColorEncoded(const char* str) {
6572   GTestColor color = COLOR_DEFAULT;  // The current color.
6573 
6574   // Conceptually, we split the string into segments divided by escape
6575   // sequences.  Then we print one segment at a time.  At the end of
6576   // each iteration, the str pointer advances to the beginning of the
6577   // next segment.
6578   for (;;) {
6579     const char* p = strchr(str, '@');
6580     if (p == NULL) {
6581       ColoredPrintf(color, "%s", str);
6582       return;
6583     }
6584 
6585     ColoredPrintf(color, "%s", std::string(str, p).c_str());
6586 
6587     const char ch = p[1];
6588     str = p + 2;
6589     if (ch == '@') {
6590       ColoredPrintf(color, "@");
6591     } else if (ch == 'D') {
6592       color = COLOR_DEFAULT;
6593     } else if (ch == 'R') {
6594       color = COLOR_RED;
6595     } else if (ch == 'G') {
6596       color = COLOR_GREEN;
6597     } else if (ch == 'Y') {
6598       color = COLOR_YELLOW;
6599     } else {
6600       --str;
6601     }
6602   }
6603 }
6604 
6605 static const char kColorEncodedHelpMessage[] =
6606 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6607 "following command line flags to control its behavior:\n"
6608 "\n"
6609 "Test Selection:\n"
6610 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6611 "      List the names of all tests instead of running them. The name of\n"
6612 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
6613 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6614     "[@G-@YNEGATIVE_PATTERNS]@D\n"
6615 "      Run only the tests whose name matches one of the positive patterns but\n"
6616 "      none of the negative patterns. '?' matches any single character; '*'\n"
6617 "      matches any substring; ':' separates two patterns.\n"
6618 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6619 "      Run all disabled tests too.\n"
6620 "\n"
6621 "Test Execution:\n"
6622 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6623 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
6624 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6625 "      Randomize tests' orders on every iteration.\n"
6626 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6627 "      Random number seed to use for shuffling test orders (between 1 and\n"
6628 "      99999, or 0 to use a seed based on the current time).\n"
6629 "\n"
6630 "Test Output:\n"
6631 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6632 "      Enable/disable colored output. The default is @Gauto@D.\n"
6633 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6634 "      Don't print the elapsed time of each test.\n"
6635 "  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6636     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6637 "      Generate an XML report in the given directory or with the given file\n"
6638 "      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6639 #if GTEST_CAN_STREAM_RESULTS_
6640 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6641 "      Stream test results to the given server.\n"
6642 #endif  // GTEST_CAN_STREAM_RESULTS_
6643 "\n"
6644 "Assertion Behavior:\n"
6645 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6646 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6647 "      Set the default death test style.\n"
6648 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6649 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6650 "      Turn assertion failures into debugger break-points.\n"
6651 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6652 "      Turn assertion failures into C++ exceptions.\n"
6653 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6654 "      Do not report exceptions as test failures. Instead, allow them\n"
6655 "      to crash the program or throw a pop-up (on Windows).\n"
6656 "\n"
6657 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6658     "the corresponding\n"
6659 "environment variable of a flag (all letters in upper-case). For example, to\n"
6660 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6661     "color=no@D or set\n"
6662 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6663 "\n"
6664 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6665 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6666 "(not one in your own code or tests), please report it to\n"
6667 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6668 
ParseGoogleTestFlag(const char * const arg)6669 bool ParseGoogleTestFlag(const char* const arg) {
6670   return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6671                        &GTEST_FLAG(also_run_disabled_tests)) ||
6672       ParseBoolFlag(arg, kBreakOnFailureFlag,
6673                     &GTEST_FLAG(break_on_failure)) ||
6674       ParseBoolFlag(arg, kCatchExceptionsFlag,
6675                     &GTEST_FLAG(catch_exceptions)) ||
6676       ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6677       ParseStringFlag(arg, kDeathTestStyleFlag,
6678                       &GTEST_FLAG(death_test_style)) ||
6679       ParseBoolFlag(arg, kDeathTestUseFork,
6680                     &GTEST_FLAG(death_test_use_fork)) ||
6681       ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6682       ParseStringFlag(arg, kInternalRunDeathTestFlag,
6683                       &GTEST_FLAG(internal_run_death_test)) ||
6684       ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6685       ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
6686       ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6687       ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
6688       ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6689       ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6690       ParseInt32Flag(arg, kStackTraceDepthFlag,
6691                      &GTEST_FLAG(stack_trace_depth)) ||
6692       ParseStringFlag(arg, kStreamResultToFlag,
6693                       &GTEST_FLAG(stream_result_to)) ||
6694       ParseBoolFlag(arg, kThrowOnFailureFlag,
6695                     &GTEST_FLAG(throw_on_failure));
6696 }
6697 
6698 #if GTEST_USE_OWN_FLAGFILE_FLAG_
LoadFlagsFromFile(const std::string & path)6699 void LoadFlagsFromFile(const std::string& path) {
6700   FILE* flagfile = posix::FOpen(path.c_str(), "r");
6701   if (!flagfile) {
6702     fprintf(stderr,
6703             "Unable to open file \"%s\"\n",
6704             GTEST_FLAG(flagfile).c_str());
6705     fflush(stderr);
6706     exit(EXIT_FAILURE);
6707   }
6708   std::string contents(ReadEntireFile(flagfile));
6709   posix::FClose(flagfile);
6710   std::vector<std::string> lines;
6711   SplitString(contents, '\n', &lines);
6712   for (size_t i = 0; i < lines.size(); ++i) {
6713     if (lines[i].empty())
6714       continue;
6715     if (!ParseGoogleTestFlag(lines[i].c_str()))
6716       g_help_flag = true;
6717   }
6718 }
6719 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
6720 
6721 // Parses the command line for Google Test flags, without initializing
6722 // other parts of Google Test.  The type parameter CharType can be
6723 // instantiated to either char or wchar_t.
6724 template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)6725 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6726   for (int i = 1; i < *argc; i++) {
6727     const std::string arg_string = StreamableToString(argv[i]);
6728     const char* const arg = arg_string.c_str();
6729 
6730     using internal::ParseBoolFlag;
6731     using internal::ParseInt32Flag;
6732     using internal::ParseStringFlag;
6733 
6734     bool remove_flag = false;
6735     if (ParseGoogleTestFlag(arg)) {
6736       remove_flag = true;
6737 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6738     } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
6739       LoadFlagsFromFile(GTEST_FLAG(flagfile));
6740       remove_flag = true;
6741 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
6742     } else if (arg_string == "--help" || arg_string == "-h" ||
6743                arg_string == "-?" || arg_string == "/?" ||
6744                HasGoogleTestFlagPrefix(arg)) {
6745       // Both help flag and unrecognized Google Test flags (excluding
6746       // internal ones) trigger help display.
6747       g_help_flag = true;
6748     }
6749 
6750     if (remove_flag) {
6751       // Shift the remainder of the argv list left by one.  Note
6752       // that argv has (*argc + 1) elements, the last one always being
6753       // NULL.  The following loop moves the trailing NULL element as
6754       // well.
6755       for (int j = i; j != *argc; j++) {
6756         argv[j] = argv[j + 1];
6757       }
6758 
6759       // Decrements the argument count.
6760       (*argc)--;
6761 
6762       // We also need to decrement the iterator as we just removed
6763       // an element.
6764       i--;
6765     }
6766   }
6767 
6768   if (g_help_flag) {
6769     // We print the help here instead of in RUN_ALL_TESTS(), as the
6770     // latter may not be called at all if the user is using Google
6771     // Test with another testing framework.
6772     PrintColorEncoded(kColorEncodedHelpMessage);
6773   }
6774 }
6775 
6776 // Parses the command line for Google Test flags, without initializing
6777 // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)6778 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6779   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6780 }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)6781 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6782   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6783 }
6784 
6785 // The internal implementation of InitGoogleTest().
6786 //
6787 // The type parameter CharType can be instantiated to either char or
6788 // wchar_t.
6789 template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)6790 void InitGoogleTestImpl(int* argc, CharType** argv) {
6791   // We don't want to run the initialization code twice.
6792   if (GTestIsInitialized()) return;
6793 
6794   if (*argc <= 0) return;
6795 
6796   g_argvs.clear();
6797   for (int i = 0; i != *argc; i++) {
6798     g_argvs.push_back(StreamableToString(argv[i]));
6799   }
6800 
6801   ParseGoogleTestFlagsOnly(argc, argv);
6802   GetUnitTestImpl()->PostFlagParsingInit();
6803 }
6804 
6805 }  // namespace internal
6806 
6807 // Initializes Google Test.  This must be called before calling
6808 // RUN_ALL_TESTS().  In particular, it parses a command line for the
6809 // flags that Google Test recognizes.  Whenever a Google Test flag is
6810 // seen, it is removed from argv, and *argc is decremented.
6811 //
6812 // No value is returned.  Instead, the Google Test flag variables are
6813 // updated.
6814 //
6815 // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)6816 void InitGoogleTest(int* argc, char** argv) {
6817 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6818   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6819 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6820   internal::InitGoogleTestImpl(argc, argv);
6821 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6822 }
6823 
6824 // This overloaded version can be used in Windows programs compiled in
6825 // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)6826 void InitGoogleTest(int* argc, wchar_t** argv) {
6827 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6828   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6829 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6830   internal::InitGoogleTestImpl(argc, argv);
6831 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6832 }
6833 
6834 }  // namespace testing
6835 // Copyright 2005, Google Inc.
6836 // All rights reserved.
6837 //
6838 // Redistribution and use in source and binary forms, with or without
6839 // modification, are permitted provided that the following conditions are
6840 // met:
6841 //
6842 //     * Redistributions of source code must retain the above copyright
6843 // notice, this list of conditions and the following disclaimer.
6844 //     * Redistributions in binary form must reproduce the above
6845 // copyright notice, this list of conditions and the following disclaimer
6846 // in the documentation and/or other materials provided with the
6847 // distribution.
6848 //     * Neither the name of Google Inc. nor the names of its
6849 // contributors may be used to endorse or promote products derived from
6850 // this software without specific prior written permission.
6851 //
6852 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6853 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6854 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6855 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6856 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6857 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6858 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6859 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6860 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6861 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6862 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6863 //
6864 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6865 //
6866 // This file implements death tests.
6867 
6868 
6869 #if GTEST_HAS_DEATH_TEST
6870 
6871 # if GTEST_OS_MAC
6872 #  include <crt_externs.h>
6873 # endif  // GTEST_OS_MAC
6874 
6875 # include <errno.h>
6876 # include <fcntl.h>
6877 # include <limits.h>
6878 
6879 # if GTEST_OS_LINUX
6880 #  include <signal.h>
6881 # endif  // GTEST_OS_LINUX
6882 
6883 # include <stdarg.h>
6884 
6885 # if GTEST_OS_WINDOWS
6886 #  include <windows.h>
6887 # else
6888 #  include <sys/mman.h>
6889 #  include <sys/wait.h>
6890 # endif  // GTEST_OS_WINDOWS
6891 
6892 # if GTEST_OS_QNX
6893 #  include <spawn.h>
6894 # endif  // GTEST_OS_QNX
6895 
6896 #endif  // GTEST_HAS_DEATH_TEST
6897 
6898 
6899 // Indicates that this translation unit is part of Google Test's
6900 // implementation.  It must come before gtest-internal-inl.h is
6901 // included, or there will be a compiler error.  This trick exists to
6902 // prevent the accidental inclusion of gtest-internal-inl.h in the
6903 // user's code.
6904 #define GTEST_IMPLEMENTATION_ 1
6905 #undef GTEST_IMPLEMENTATION_
6906 
6907 namespace testing {
6908 
6909 // Constants.
6910 
6911 // The default death test style.
6912 static const char kDefaultDeathTestStyle[] = "fast";
6913 
6914 GTEST_DEFINE_string_(
6915     death_test_style,
6916     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6917     "Indicates how to run a death test in a forked child process: "
6918     "\"threadsafe\" (child process re-executes the test binary "
6919     "from the beginning, running only the specific death test) or "
6920     "\"fast\" (child process runs the death test immediately "
6921     "after forking).");
6922 
6923 GTEST_DEFINE_bool_(
6924     death_test_use_fork,
6925     internal::BoolFromGTestEnv("death_test_use_fork", false),
6926     "Instructs to use fork()/_exit() instead of clone() in death tests. "
6927     "Ignored and always uses fork() on POSIX systems where clone() is not "
6928     "implemented. Useful when running under valgrind or similar tools if "
6929     "those do not support clone(). Valgrind 3.3.1 will just fail if "
6930     "it sees an unsupported combination of clone() flags. "
6931     "It is not recommended to use this flag w/o valgrind though it will "
6932     "work in 99% of the cases. Once valgrind is fixed, this flag will "
6933     "most likely be removed.");
6934 
6935 namespace internal {
6936 GTEST_DEFINE_string_(
6937     internal_run_death_test, "",
6938     "Indicates the file, line number, temporal index of "
6939     "the single death test to run, and a file descriptor to "
6940     "which a success code may be sent, all separated by "
6941     "the '|' characters.  This flag is specified if and only if the current "
6942     "process is a sub-process launched for running a thread-safe "
6943     "death test.  FOR INTERNAL USE ONLY.");
6944 }  // namespace internal
6945 
6946 #if GTEST_HAS_DEATH_TEST
6947 
6948 namespace internal {
6949 
6950 // Valid only for fast death tests. Indicates the code is running in the
6951 // child process of a fast style death test.
6952 # if !GTEST_OS_WINDOWS
6953 static bool g_in_fast_death_test_child = false;
6954 # endif
6955 
6956 // Returns a Boolean value indicating whether the caller is currently
6957 // executing in the context of the death test child process.  Tools such as
6958 // Valgrind heap checkers may need this to modify their behavior in death
6959 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
6960 // implementation of death tests.  User code MUST NOT use it.
InDeathTestChild()6961 bool InDeathTestChild() {
6962 # if GTEST_OS_WINDOWS
6963 
6964   // On Windows, death tests are thread-safe regardless of the value of the
6965   // death_test_style flag.
6966   return !GTEST_FLAG(internal_run_death_test).empty();
6967 
6968 # else
6969 
6970   if (GTEST_FLAG(death_test_style) == "threadsafe")
6971     return !GTEST_FLAG(internal_run_death_test).empty();
6972   else
6973     return g_in_fast_death_test_child;
6974 #endif
6975 }
6976 
6977 }  // namespace internal
6978 
6979 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)6980 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6981 }
6982 
6983 // ExitedWithCode function-call operator.
operator ()(int exit_status) const6984 bool ExitedWithCode::operator()(int exit_status) const {
6985 # if GTEST_OS_WINDOWS
6986 
6987   return exit_status == exit_code_;
6988 
6989 # else
6990 
6991   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6992 
6993 # endif  // GTEST_OS_WINDOWS
6994 }
6995 
6996 # if !GTEST_OS_WINDOWS
6997 // KilledBySignal constructor.
KilledBySignal(int signum)6998 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6999 }
7000 
7001 // KilledBySignal function-call operator.
operator ()(int exit_status) const7002 bool KilledBySignal::operator()(int exit_status) const {
7003 #  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7004   {
7005     bool result;
7006     if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7007       return result;
7008     }
7009   }
7010 #  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7011   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7012 }
7013 # endif  // !GTEST_OS_WINDOWS
7014 
7015 namespace internal {
7016 
7017 // Utilities needed for death tests.
7018 
7019 // Generates a textual description of a given exit code, in the format
7020 // specified by wait(2).
ExitSummary(int exit_code)7021 static std::string ExitSummary(int exit_code) {
7022   Message m;
7023 
7024 # if GTEST_OS_WINDOWS
7025 
7026   m << "Exited with exit status " << exit_code;
7027 
7028 # else
7029 
7030   if (WIFEXITED(exit_code)) {
7031     m << "Exited with exit status " << WEXITSTATUS(exit_code);
7032   } else if (WIFSIGNALED(exit_code)) {
7033     m << "Terminated by signal " << WTERMSIG(exit_code);
7034   }
7035 #  ifdef WCOREDUMP
7036   if (WCOREDUMP(exit_code)) {
7037     m << " (core dumped)";
7038   }
7039 #  endif
7040 # endif  // GTEST_OS_WINDOWS
7041 
7042   return m.GetString();
7043 }
7044 
7045 // Returns true if exit_status describes a process that was terminated
7046 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)7047 bool ExitedUnsuccessfully(int exit_status) {
7048   return !ExitedWithCode(0)(exit_status);
7049 }
7050 
7051 # if !GTEST_OS_WINDOWS
7052 // Generates a textual failure message when a death test finds more than
7053 // one thread running, or cannot determine the number of threads, prior
7054 // to executing the given statement.  It is the responsibility of the
7055 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)7056 static std::string DeathTestThreadWarning(size_t thread_count) {
7057   Message msg;
7058   msg << "Death tests use fork(), which is unsafe particularly"
7059       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
7060   if (thread_count == 0)
7061     msg << "couldn't detect the number of threads.";
7062   else
7063     msg << "detected " << thread_count << " threads.";
7064   return msg.GetString();
7065 }
7066 # endif  // !GTEST_OS_WINDOWS
7067 
7068 // Flag characters for reporting a death test that did not die.
7069 static const char kDeathTestLived = 'L';
7070 static const char kDeathTestReturned = 'R';
7071 static const char kDeathTestThrew = 'T';
7072 static const char kDeathTestInternalError = 'I';
7073 
7074 // An enumeration describing all of the possible ways that a death test can
7075 // conclude.  DIED means that the process died while executing the test
7076 // code; LIVED means that process lived beyond the end of the test code;
7077 // RETURNED means that the test statement attempted to execute a return
7078 // statement, which is not allowed; THREW means that the test statement
7079 // returned control by throwing an exception.  IN_PROGRESS means the test
7080 // has not yet concluded.
7081 // TODO(vladl@google.com): Unify names and possibly values for
7082 // AbortReason, DeathTestOutcome, and flag characters above.
7083 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7084 
7085 // Routine for aborting the program which is safe to call from an
7086 // exec-style death test child process, in which case the error
7087 // message is propagated back to the parent process.  Otherwise, the
7088 // message is simply printed to stderr.  In either case, the program
7089 // then exits with status 1.
DeathTestAbort(const std::string & message)7090 void DeathTestAbort(const std::string& message) {
7091   // On a POSIX system, this function may be called from a threadsafe-style
7092   // death test child process, which operates on a very small stack.  Use
7093   // the heap for any additional non-minuscule memory requirements.
7094   const InternalRunDeathTestFlag* const flag =
7095       GetUnitTestImpl()->internal_run_death_test_flag();
7096   if (flag != NULL) {
7097     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7098     fputc(kDeathTestInternalError, parent);
7099     fprintf(parent, "%s", message.c_str());
7100     fflush(parent);
7101     _exit(1);
7102   } else {
7103     fprintf(stderr, "%s", message.c_str());
7104     fflush(stderr);
7105     posix::Abort();
7106   }
7107 }
7108 
7109 // A replacement for CHECK that calls DeathTestAbort if the assertion
7110 // fails.
7111 # define GTEST_DEATH_TEST_CHECK_(expression) \
7112   do { \
7113     if (!::testing::internal::IsTrue(expression)) { \
7114       DeathTestAbort( \
7115           ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
7116           + ::testing::internal::StreamableToString(__LINE__) + ": " \
7117           + #expression); \
7118     } \
7119   } while (::testing::internal::AlwaysFalse())
7120 
7121 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7122 // evaluating any system call that fulfills two conditions: it must return
7123 // -1 on failure, and set errno to EINTR when it is interrupted and
7124 // should be tried again.  The macro expands to a loop that repeatedly
7125 // evaluates the expression as long as it evaluates to -1 and sets
7126 // errno to EINTR.  If the expression evaluates to -1 but errno is
7127 // something other than EINTR, DeathTestAbort is called.
7128 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7129   do { \
7130     int gtest_retval; \
7131     do { \
7132       gtest_retval = (expression); \
7133     } while (gtest_retval == -1 && errno == EINTR); \
7134     if (gtest_retval == -1) { \
7135       DeathTestAbort( \
7136           ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7137           + ::testing::internal::StreamableToString(__LINE__) + ": " \
7138           + #expression + " != -1"); \
7139     } \
7140   } while (::testing::internal::AlwaysFalse())
7141 
7142 // Returns the message describing the last system error in errno.
GetLastErrnoDescription()7143 std::string GetLastErrnoDescription() {
7144     return errno == 0 ? "" : posix::StrError(errno);
7145 }
7146 
7147 // This is called from a death test parent process to read a failure
7148 // message from the death test child process and log it with the FATAL
7149 // severity. On Windows, the message is read from a pipe handle. On other
7150 // platforms, it is read from a file descriptor.
FailFromInternalError(int fd)7151 static void FailFromInternalError(int fd) {
7152   Message error;
7153   char buffer[256];
7154   int num_read;
7155 
7156   do {
7157     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7158       buffer[num_read] = '\0';
7159       error << buffer;
7160     }
7161   } while (num_read == -1 && errno == EINTR);
7162 
7163   if (num_read == 0) {
7164     GTEST_LOG_(FATAL) << error.GetString();
7165   } else {
7166     const int last_error = errno;
7167     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7168                       << GetLastErrnoDescription() << " [" << last_error << "]";
7169   }
7170 }
7171 
7172 // Death test constructor.  Increments the running death test count
7173 // for the current test.
DeathTest()7174 DeathTest::DeathTest() {
7175   TestInfo* const info = GetUnitTestImpl()->current_test_info();
7176   if (info == NULL) {
7177     DeathTestAbort("Cannot run a death test outside of a TEST or "
7178                    "TEST_F construct");
7179   }
7180 }
7181 
7182 // Creates and returns a death test by dispatching to the current
7183 // death test factory.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)7184 bool DeathTest::Create(const char* statement, const RE* regex,
7185                        const char* file, int line, DeathTest** test) {
7186   return GetUnitTestImpl()->death_test_factory()->Create(
7187       statement, regex, file, line, test);
7188 }
7189 
LastMessage()7190 const char* DeathTest::LastMessage() {
7191   return last_death_test_message_.c_str();
7192 }
7193 
set_last_death_test_message(const std::string & message)7194 void DeathTest::set_last_death_test_message(const std::string& message) {
7195   last_death_test_message_ = message;
7196 }
7197 
7198 std::string DeathTest::last_death_test_message_;
7199 
7200 // Provides cross platform implementation for some death functionality.
7201 class DeathTestImpl : public DeathTest {
7202  protected:
DeathTestImpl(const char * a_statement,const RE * a_regex)7203   DeathTestImpl(const char* a_statement, const RE* a_regex)
7204       : statement_(a_statement),
7205         regex_(a_regex),
7206         spawned_(false),
7207         status_(-1),
7208         outcome_(IN_PROGRESS),
7209         read_fd_(-1),
7210         write_fd_(-1) {}
7211 
7212   // read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl()7213   ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7214 
7215   void Abort(AbortReason reason);
7216   virtual bool Passed(bool status_ok);
7217 
statement() const7218   const char* statement() const { return statement_; }
regex() const7219   const RE* regex() const { return regex_; }
spawned() const7220   bool spawned() const { return spawned_; }
set_spawned(bool is_spawned)7221   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
status() const7222   int status() const { return status_; }
set_status(int a_status)7223   void set_status(int a_status) { status_ = a_status; }
outcome() const7224   DeathTestOutcome outcome() const { return outcome_; }
set_outcome(DeathTestOutcome an_outcome)7225   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
read_fd() const7226   int read_fd() const { return read_fd_; }
set_read_fd(int fd)7227   void set_read_fd(int fd) { read_fd_ = fd; }
write_fd() const7228   int write_fd() const { return write_fd_; }
set_write_fd(int fd)7229   void set_write_fd(int fd) { write_fd_ = fd; }
7230 
7231   // Called in the parent process only. Reads the result code of the death
7232   // test child process via a pipe, interprets it to set the outcome_
7233   // member, and closes read_fd_.  Outputs diagnostics and terminates in
7234   // case of unexpected codes.
7235   void ReadAndInterpretStatusByte();
7236 
7237  private:
7238   // The textual content of the code this object is testing.  This class
7239   // doesn't own this string and should not attempt to delete it.
7240   const char* const statement_;
7241   // The regular expression which test output must match.  DeathTestImpl
7242   // doesn't own this object and should not attempt to delete it.
7243   const RE* const regex_;
7244   // True if the death test child process has been successfully spawned.
7245   bool spawned_;
7246   // The exit status of the child process.
7247   int status_;
7248   // How the death test concluded.
7249   DeathTestOutcome outcome_;
7250   // Descriptor to the read end of the pipe to the child process.  It is
7251   // always -1 in the child process.  The child keeps its write end of the
7252   // pipe in write_fd_.
7253   int read_fd_;
7254   // Descriptor to the child's write end of the pipe to the parent process.
7255   // It is always -1 in the parent process.  The parent keeps its end of the
7256   // pipe in read_fd_.
7257   int write_fd_;
7258 };
7259 
7260 // Called in the parent process only. Reads the result code of the death
7261 // test child process via a pipe, interprets it to set the outcome_
7262 // member, and closes read_fd_.  Outputs diagnostics and terminates in
7263 // case of unexpected codes.
ReadAndInterpretStatusByte()7264 void DeathTestImpl::ReadAndInterpretStatusByte() {
7265   char flag;
7266   int bytes_read;
7267 
7268   // The read() here blocks until data is available (signifying the
7269   // failure of the death test) or until the pipe is closed (signifying
7270   // its success), so it's okay to call this in the parent before
7271   // the child process has exited.
7272   do {
7273     bytes_read = posix::Read(read_fd(), &flag, 1);
7274   } while (bytes_read == -1 && errno == EINTR);
7275 
7276   if (bytes_read == 0) {
7277     set_outcome(DIED);
7278   } else if (bytes_read == 1) {
7279     switch (flag) {
7280       case kDeathTestReturned:
7281         set_outcome(RETURNED);
7282         break;
7283       case kDeathTestThrew:
7284         set_outcome(THREW);
7285         break;
7286       case kDeathTestLived:
7287         set_outcome(LIVED);
7288         break;
7289       case kDeathTestInternalError:
7290         FailFromInternalError(read_fd());  // Does not return.
7291         break;
7292       default:
7293         GTEST_LOG_(FATAL) << "Death test child process reported "
7294                           << "unexpected status byte ("
7295                           << static_cast<unsigned int>(flag) << ")";
7296     }
7297   } else {
7298     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
7299                       << GetLastErrnoDescription();
7300   }
7301   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
7302   set_read_fd(-1);
7303 }
7304 
7305 // Signals that the death test code which should have exited, didn't.
7306 // Should be called only in a death test child process.
7307 // Writes a status byte to the child's status file descriptor, then
7308 // calls _exit(1).
Abort(AbortReason reason)7309 void DeathTestImpl::Abort(AbortReason reason) {
7310   // The parent process considers the death test to be a failure if
7311   // it finds any data in our pipe.  So, here we write a single flag byte
7312   // to the pipe, then exit.
7313   const char status_ch =
7314       reason == TEST_DID_NOT_DIE ? kDeathTestLived :
7315       reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
7316 
7317   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
7318   // We are leaking the descriptor here because on some platforms (i.e.,
7319   // when built as Windows DLL), destructors of global objects will still
7320   // run after calling _exit(). On such systems, write_fd_ will be
7321   // indirectly closed from the destructor of UnitTestImpl, causing double
7322   // close if it is also closed here. On debug configurations, double close
7323   // may assert. As there are no in-process buffers to flush here, we are
7324   // relying on the OS to close the descriptor after the process terminates
7325   // when the destructors are not run.
7326   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
7327 }
7328 
7329 // Returns an indented copy of stderr output for a death test.
7330 // This makes distinguishing death test output lines from regular log lines
7331 // much easier.
FormatDeathTestOutput(const::std::string & output)7332 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
7333   ::std::string ret;
7334   for (size_t at = 0; ; ) {
7335     const size_t line_end = output.find('\n', at);
7336     ret += "[  DEATH   ] ";
7337     if (line_end == ::std::string::npos) {
7338       ret += output.substr(at);
7339       break;
7340     }
7341     ret += output.substr(at, line_end + 1 - at);
7342     at = line_end + 1;
7343   }
7344   return ret;
7345 }
7346 
7347 // Assesses the success or failure of a death test, using both private
7348 // members which have previously been set, and one argument:
7349 //
7350 // Private data members:
7351 //   outcome:  An enumeration describing how the death test
7352 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
7353 //             fails in the latter three cases.
7354 //   status:   The exit status of the child process. On *nix, it is in the
7355 //             in the format specified by wait(2). On Windows, this is the
7356 //             value supplied to the ExitProcess() API or a numeric code
7357 //             of the exception that terminated the program.
7358 //   regex:    A regular expression object to be applied to
7359 //             the test's captured standard error output; the death test
7360 //             fails if it does not match.
7361 //
7362 // Argument:
7363 //   status_ok: true if exit_status is acceptable in the context of
7364 //              this particular death test, which fails if it is false
7365 //
7366 // Returns true iff all of the above conditions are met.  Otherwise, the
7367 // first failing condition, in the order given above, is the one that is
7368 // reported. Also sets the last death test message string.
Passed(bool status_ok)7369 bool DeathTestImpl::Passed(bool status_ok) {
7370   if (!spawned())
7371     return false;
7372 
7373   const std::string error_message = GetCapturedStderr();
7374 
7375   bool success = false;
7376   Message buffer;
7377 
7378   buffer << "Death test: " << statement() << "\n";
7379   switch (outcome()) {
7380     case LIVED:
7381       buffer << "    Result: failed to die.\n"
7382              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7383       break;
7384     case THREW:
7385       buffer << "    Result: threw an exception.\n"
7386              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7387       break;
7388     case RETURNED:
7389       buffer << "    Result: illegal return in test statement.\n"
7390              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7391       break;
7392     case DIED:
7393       if (status_ok) {
7394         const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7395         if (matched) {
7396           success = true;
7397         } else {
7398           buffer << "    Result: died but not with expected error.\n"
7399                  << "  Expected: " << regex()->pattern() << "\n"
7400                  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7401         }
7402       } else {
7403         buffer << "    Result: died but not with expected exit code:\n"
7404                << "            " << ExitSummary(status()) << "\n"
7405                << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7406       }
7407       break;
7408     case IN_PROGRESS:
7409     default:
7410       GTEST_LOG_(FATAL)
7411           << "DeathTest::Passed somehow called before conclusion of test";
7412   }
7413 
7414   DeathTest::set_last_death_test_message(buffer.GetString());
7415   return success;
7416 }
7417 
7418 # if GTEST_OS_WINDOWS
7419 // WindowsDeathTest implements death tests on Windows. Due to the
7420 // specifics of starting new processes on Windows, death tests there are
7421 // always threadsafe, and Google Test considers the
7422 // --gtest_death_test_style=fast setting to be equivalent to
7423 // --gtest_death_test_style=threadsafe there.
7424 //
7425 // A few implementation notes:  Like the Linux version, the Windows
7426 // implementation uses pipes for child-to-parent communication. But due to
7427 // the specifics of pipes on Windows, some extra steps are required:
7428 //
7429 // 1. The parent creates a communication pipe and stores handles to both
7430 //    ends of it.
7431 // 2. The parent starts the child and provides it with the information
7432 //    necessary to acquire the handle to the write end of the pipe.
7433 // 3. The child acquires the write end of the pipe and signals the parent
7434 //    using a Windows event.
7435 // 4. Now the parent can release the write end of the pipe on its side. If
7436 //    this is done before step 3, the object's reference count goes down to
7437 //    0 and it is destroyed, preventing the child from acquiring it. The
7438 //    parent now has to release it, or read operations on the read end of
7439 //    the pipe will not return when the child terminates.
7440 // 5. The parent reads child's output through the pipe (outcome code and
7441 //    any possible error messages) from the pipe, and its stderr and then
7442 //    determines whether to fail the test.
7443 //
7444 // Note: to distinguish Win32 API calls from the local method and function
7445 // calls, the former are explicitly resolved in the global namespace.
7446 //
7447 class WindowsDeathTest : public DeathTestImpl {
7448  public:
WindowsDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)7449   WindowsDeathTest(const char* a_statement,
7450                    const RE* a_regex,
7451                    const char* file,
7452                    int line)
7453       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7454 
7455   // All of these virtual functions are inherited from DeathTest.
7456   virtual int Wait();
7457   virtual TestRole AssumeRole();
7458 
7459  private:
7460   // The name of the file in which the death test is located.
7461   const char* const file_;
7462   // The line number on which the death test is located.
7463   const int line_;
7464   // Handle to the write end of the pipe to the child process.
7465   AutoHandle write_handle_;
7466   // Child process handle.
7467   AutoHandle child_handle_;
7468   // Event the child process uses to signal the parent that it has
7469   // acquired the handle to the write end of the pipe. After seeing this
7470   // event the parent can release its own handles to make sure its
7471   // ReadFile() calls return when the child terminates.
7472   AutoHandle event_handle_;
7473 };
7474 
7475 // Waits for the child in a death test to exit, returning its exit
7476 // status, or 0 if no child process exists.  As a side effect, sets the
7477 // outcome data member.
Wait()7478 int WindowsDeathTest::Wait() {
7479   if (!spawned())
7480     return 0;
7481 
7482   // Wait until the child either signals that it has acquired the write end
7483   // of the pipe or it dies.
7484   const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7485   switch (::WaitForMultipleObjects(2,
7486                                    wait_handles,
7487                                    FALSE,  // Waits for any of the handles.
7488                                    INFINITE)) {
7489     case WAIT_OBJECT_0:
7490     case WAIT_OBJECT_0 + 1:
7491       break;
7492     default:
7493       GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
7494   }
7495 
7496   // The child has acquired the write end of the pipe or exited.
7497   // We release the handle on our side and continue.
7498   write_handle_.Reset();
7499   event_handle_.Reset();
7500 
7501   ReadAndInterpretStatusByte();
7502 
7503   // Waits for the child process to exit if it haven't already. This
7504   // returns immediately if the child has already exited, regardless of
7505   // whether previous calls to WaitForMultipleObjects synchronized on this
7506   // handle or not.
7507   GTEST_DEATH_TEST_CHECK_(
7508       WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7509                                              INFINITE));
7510   DWORD status_code;
7511   GTEST_DEATH_TEST_CHECK_(
7512       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7513   child_handle_.Reset();
7514   set_status(static_cast<int>(status_code));
7515   return status();
7516 }
7517 
7518 // The AssumeRole process for a Windows death test.  It creates a child
7519 // process with the same executable as the current process to run the
7520 // death test.  The child process is given the --gtest_filter and
7521 // --gtest_internal_run_death_test flags such that it knows to run the
7522 // current death test only.
AssumeRole()7523 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7524   const UnitTestImpl* const impl = GetUnitTestImpl();
7525   const InternalRunDeathTestFlag* const flag =
7526       impl->internal_run_death_test_flag();
7527   const TestInfo* const info = impl->current_test_info();
7528   const int death_test_index = info->result()->death_test_count();
7529 
7530   if (flag != NULL) {
7531     // ParseInternalRunDeathTestFlag() has performed all the necessary
7532     // processing.
7533     set_write_fd(flag->write_fd());
7534     return EXECUTE_TEST;
7535   }
7536 
7537   // WindowsDeathTest uses an anonymous pipe to communicate results of
7538   // a death test.
7539   SECURITY_ATTRIBUTES handles_are_inheritable = {
7540     sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7541   HANDLE read_handle, write_handle;
7542   GTEST_DEATH_TEST_CHECK_(
7543       ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7544                    0)  // Default buffer size.
7545       != FALSE);
7546   set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7547                                 O_RDONLY));
7548   write_handle_.Reset(write_handle);
7549   event_handle_.Reset(::CreateEvent(
7550       &handles_are_inheritable,
7551       TRUE,    // The event will automatically reset to non-signaled state.
7552       FALSE,   // The initial state is non-signalled.
7553       NULL));  // The even is unnamed.
7554   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7555   const std::string filter_flag =
7556       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
7557       info->test_case_name() + "." + info->name();
7558   const std::string internal_flag =
7559       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
7560       "=" + file_ + "|" + StreamableToString(line_) + "|" +
7561       StreamableToString(death_test_index) + "|" +
7562       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7563       // size_t has the same width as pointers on both 32-bit and 64-bit
7564       // Windows platforms.
7565       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7566       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
7567       "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7568 
7569   char executable_path[_MAX_PATH + 1];  // NOLINT
7570   GTEST_DEATH_TEST_CHECK_(
7571       _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7572                                             executable_path,
7573                                             _MAX_PATH));
7574 
7575   std::string command_line =
7576       std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
7577       internal_flag + "\"";
7578 
7579   DeathTest::set_last_death_test_message("");
7580 
7581   CaptureStderr();
7582   // Flush the log buffers since the log streams are shared with the child.
7583   FlushInfoLog();
7584 
7585   // The child process will share the standard handles with the parent.
7586   STARTUPINFOA startup_info;
7587   memset(&startup_info, 0, sizeof(STARTUPINFO));
7588   startup_info.dwFlags = STARTF_USESTDHANDLES;
7589   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7590   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7591   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7592 
7593   PROCESS_INFORMATION process_info;
7594   GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7595       executable_path,
7596       const_cast<char*>(command_line.c_str()),
7597       NULL,   // Retuned process handle is not inheritable.
7598       NULL,   // Retuned thread handle is not inheritable.
7599       TRUE,   // Child inherits all inheritable handles (for write_handle_).
7600       0x0,    // Default creation flags.
7601       NULL,   // Inherit the parent's environment.
7602       UnitTest::GetInstance()->original_working_dir(),
7603       &startup_info,
7604       &process_info) != FALSE);
7605   child_handle_.Reset(process_info.hProcess);
7606   ::CloseHandle(process_info.hThread);
7607   set_spawned(true);
7608   return OVERSEE_TEST;
7609 }
7610 # else  // We are not on Windows.
7611 
7612 // ForkingDeathTest provides implementations for most of the abstract
7613 // methods of the DeathTest interface.  Only the AssumeRole method is
7614 // left undefined.
7615 class ForkingDeathTest : public DeathTestImpl {
7616  public:
7617   ForkingDeathTest(const char* statement, const RE* regex);
7618 
7619   // All of these virtual functions are inherited from DeathTest.
7620   virtual int Wait();
7621 
7622  protected:
set_child_pid(pid_t child_pid)7623   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7624 
7625  private:
7626   // PID of child process during death test; 0 in the child process itself.
7627   pid_t child_pid_;
7628 };
7629 
7630 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * a_statement,const RE * a_regex)7631 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7632     : DeathTestImpl(a_statement, a_regex),
7633       child_pid_(-1) {}
7634 
7635 // Waits for the child in a death test to exit, returning its exit
7636 // status, or 0 if no child process exists.  As a side effect, sets the
7637 // outcome data member.
Wait()7638 int ForkingDeathTest::Wait() {
7639   if (!spawned())
7640     return 0;
7641 
7642   ReadAndInterpretStatusByte();
7643 
7644   int status_value;
7645   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7646   set_status(status_value);
7647   return status_value;
7648 }
7649 
7650 // A concrete death test class that forks, then immediately runs the test
7651 // in the child process.
7652 class NoExecDeathTest : public ForkingDeathTest {
7653  public:
NoExecDeathTest(const char * a_statement,const RE * a_regex)7654   NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7655       ForkingDeathTest(a_statement, a_regex) { }
7656   virtual TestRole AssumeRole();
7657 };
7658 
7659 // The AssumeRole process for a fork-and-run death test.  It implements a
7660 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()7661 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7662   const size_t thread_count = GetThreadCount();
7663   if (thread_count != 1) {
7664     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7665   }
7666 
7667   int pipe_fd[2];
7668   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7669 
7670   DeathTest::set_last_death_test_message("");
7671   CaptureStderr();
7672   // When we fork the process below, the log file buffers are copied, but the
7673   // file descriptors are shared.  We flush all log files here so that closing
7674   // the file descriptors in the child process doesn't throw off the
7675   // synchronization between descriptors and buffers in the parent process.
7676   // This is as close to the fork as possible to avoid a race condition in case
7677   // there are multiple threads running before the death test, and another
7678   // thread writes to the log file.
7679   FlushInfoLog();
7680 
7681   const pid_t child_pid = fork();
7682   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7683   set_child_pid(child_pid);
7684   if (child_pid == 0) {
7685     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7686     set_write_fd(pipe_fd[1]);
7687     // Redirects all logging to stderr in the child process to prevent
7688     // concurrent writes to the log files.  We capture stderr in the parent
7689     // process and append the child process' output to a log.
7690     LogToStderr();
7691     // Event forwarding to the listeners of event listener API mush be shut
7692     // down in death test subprocesses.
7693     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7694     g_in_fast_death_test_child = true;
7695     return EXECUTE_TEST;
7696   } else {
7697     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7698     set_read_fd(pipe_fd[0]);
7699     set_spawned(true);
7700     return OVERSEE_TEST;
7701   }
7702 }
7703 
7704 // A concrete death test class that forks and re-executes the main
7705 // program from the beginning, with command-line flags set that cause
7706 // only this specific death test to be run.
7707 class ExecDeathTest : public ForkingDeathTest {
7708  public:
ExecDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)7709   ExecDeathTest(const char* a_statement, const RE* a_regex,
7710                 const char* file, int line) :
7711       ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7712   virtual TestRole AssumeRole();
7713  private:
7714   static ::std::vector<testing::internal::string>
GetArgvsForDeathTestChildProcess()7715   GetArgvsForDeathTestChildProcess() {
7716     ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7717 #  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7718     ::std::vector<testing::internal::string> extra_args =
7719         GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
7720     args.insert(args.end(), extra_args.begin(), extra_args.end());
7721 #  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7722     return args;
7723   }
7724   // The name of the file in which the death test is located.
7725   const char* const file_;
7726   // The line number on which the death test is located.
7727   const int line_;
7728 };
7729 
7730 // Utility class for accumulating command-line arguments.
7731 class Arguments {
7732  public:
Arguments()7733   Arguments() {
7734     args_.push_back(NULL);
7735   }
7736 
~Arguments()7737   ~Arguments() {
7738     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7739          ++i) {
7740       free(*i);
7741     }
7742   }
AddArgument(const char * argument)7743   void AddArgument(const char* argument) {
7744     args_.insert(args_.end() - 1, posix::StrDup(argument));
7745   }
7746 
7747   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)7748   void AddArguments(const ::std::vector<Str>& arguments) {
7749     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7750          i != arguments.end();
7751          ++i) {
7752       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7753     }
7754   }
Argv()7755   char* const* Argv() {
7756     return &args_[0];
7757   }
7758 
7759  private:
7760   std::vector<char*> args_;
7761 };
7762 
7763 // A struct that encompasses the arguments to the child process of a
7764 // threadsafe-style death test process.
7765 struct ExecDeathTestArgs {
7766   char* const* argv;  // Command-line arguments for the child's call to exec
7767   int close_fd;       // File descriptor to close; the read end of a pipe
7768 };
7769 
7770 #  if GTEST_OS_MAC
GetEnviron()7771 inline char** GetEnviron() {
7772   // When Google Test is built as a framework on MacOS X, the environ variable
7773   // is unavailable. Apple's documentation (man environ) recommends using
7774   // _NSGetEnviron() instead.
7775   return *_NSGetEnviron();
7776 }
7777 #  else
7778 // Some POSIX platforms expect you to declare environ. extern "C" makes
7779 // it reside in the global namespace.
7780 extern "C" char** environ;
GetEnviron()7781 inline char** GetEnviron() { return environ; }
7782 #  endif  // GTEST_OS_MAC
7783 
7784 #  if !GTEST_OS_QNX
7785 // The main function for a threadsafe-style death test child process.
7786 // This function is called in a clone()-ed process and thus must avoid
7787 // any potentially unsafe operations like malloc or libc functions.
ExecDeathTestChildMain(void * child_arg)7788 static int ExecDeathTestChildMain(void* child_arg) {
7789   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7790   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7791 
7792   // We need to execute the test program in the same environment where
7793   // it was originally invoked.  Therefore we change to the original
7794   // working directory first.
7795   const char* const original_dir =
7796       UnitTest::GetInstance()->original_working_dir();
7797   // We can safely call chdir() as it's a direct system call.
7798   if (chdir(original_dir) != 0) {
7799     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7800                    GetLastErrnoDescription());
7801     return EXIT_FAILURE;
7802   }
7803 
7804   // We can safely call execve() as it's a direct system call.  We
7805   // cannot use execvp() as it's a libc function and thus potentially
7806   // unsafe.  Since execve() doesn't search the PATH, the user must
7807   // invoke the test program via a valid path that contains at least
7808   // one path separator.
7809   execve(args->argv[0], args->argv, GetEnviron());
7810   DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7811                  original_dir + " failed: " +
7812                  GetLastErrnoDescription());
7813   return EXIT_FAILURE;
7814 }
7815 #  endif  // !GTEST_OS_QNX
7816 
7817 // Two utility routines that together determine the direction the stack
7818 // grows.
7819 // This could be accomplished more elegantly by a single recursive
7820 // function, but we want to guard against the unlikely possibility of
7821 // a smart compiler optimizing the recursion away.
7822 //
7823 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7824 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7825 // correct answer.
7826 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
StackLowerThanAddress(const void * ptr,bool * result)7827 void StackLowerThanAddress(const void* ptr, bool* result) {
7828   int dummy;
7829   *result = (&dummy < ptr);
7830 }
7831 
7832 // Make sure AddressSanitizer does not tamper with the stack here.
7833 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
StackGrowsDown()7834 bool StackGrowsDown() {
7835   int dummy;
7836   bool result;
7837   StackLowerThanAddress(&dummy, &result);
7838   return result;
7839 }
7840 
7841 // Spawns a child process with the same executable as the current process in
7842 // a thread-safe manner and instructs it to run the death test.  The
7843 // implementation uses fork(2) + exec.  On systems where clone(2) is
7844 // available, it is used instead, being slightly more thread-safe.  On QNX,
7845 // fork supports only single-threaded environments, so this function uses
7846 // spawn(2) there instead.  The function dies with an error message if
7847 // anything goes wrong.
ExecDeathTestSpawnChild(char * const * argv,int close_fd)7848 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7849   ExecDeathTestArgs args = { argv, close_fd };
7850   pid_t child_pid = -1;
7851 
7852 #  if GTEST_OS_QNX
7853   // Obtains the current directory and sets it to be closed in the child
7854   // process.
7855   const int cwd_fd = open(".", O_RDONLY);
7856   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7857   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7858   // We need to execute the test program in the same environment where
7859   // it was originally invoked.  Therefore we change to the original
7860   // working directory first.
7861   const char* const original_dir =
7862       UnitTest::GetInstance()->original_working_dir();
7863   // We can safely call chdir() as it's a direct system call.
7864   if (chdir(original_dir) != 0) {
7865     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7866                    GetLastErrnoDescription());
7867     return EXIT_FAILURE;
7868   }
7869 
7870   int fd_flags;
7871   // Set close_fd to be closed after spawn.
7872   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7873   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7874                                         fd_flags | FD_CLOEXEC));
7875   struct inheritance inherit = {0};
7876   // spawn is a system call.
7877   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7878   // Restores the current working directory.
7879   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7880   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7881 
7882 #  else   // GTEST_OS_QNX
7883 #   if GTEST_OS_LINUX
7884   // When a SIGPROF signal is received while fork() or clone() are executing,
7885   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7886   // it after the call to fork()/clone() is complete.
7887   struct sigaction saved_sigprof_action;
7888   struct sigaction ignore_sigprof_action;
7889   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7890   sigemptyset(&ignore_sigprof_action.sa_mask);
7891   ignore_sigprof_action.sa_handler = SIG_IGN;
7892   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7893       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7894 #   endif  // GTEST_OS_LINUX
7895 
7896 #   if GTEST_HAS_CLONE
7897   const bool use_fork = GTEST_FLAG(death_test_use_fork);
7898 
7899   if (!use_fork) {
7900     static const bool stack_grows_down = StackGrowsDown();
7901     const size_t stack_size = getpagesize();
7902     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7903     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7904                              MAP_ANON | MAP_PRIVATE, -1, 0);
7905     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7906 
7907     // Maximum stack alignment in bytes:  For a downward-growing stack, this
7908     // amount is subtracted from size of the stack space to get an address
7909     // that is within the stack space and is aligned on all systems we care
7910     // about.  As far as I know there is no ABI with stack alignment greater
7911     // than 64.  We assume stack and stack_size already have alignment of
7912     // kMaxStackAlignment.
7913     const size_t kMaxStackAlignment = 64;
7914     void* const stack_top =
7915         static_cast<char*>(stack) +
7916             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7917     GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7918         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7919 
7920     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7921 
7922     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7923   }
7924 #   else
7925   const bool use_fork = true;
7926 #   endif  // GTEST_HAS_CLONE
7927 
7928   if (use_fork && (child_pid = fork()) == 0) {
7929       ExecDeathTestChildMain(&args);
7930       _exit(0);
7931   }
7932 #  endif  // GTEST_OS_QNX
7933 #  if GTEST_OS_LINUX
7934   GTEST_DEATH_TEST_CHECK_SYSCALL_(
7935       sigaction(SIGPROF, &saved_sigprof_action, NULL));
7936 #  endif  // GTEST_OS_LINUX
7937 
7938   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7939   return child_pid;
7940 }
7941 
7942 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
7943 // main program from the beginning, setting the --gtest_filter
7944 // and --gtest_internal_run_death_test flags to cause only the current
7945 // death test to be re-run.
AssumeRole()7946 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7947   const UnitTestImpl* const impl = GetUnitTestImpl();
7948   const InternalRunDeathTestFlag* const flag =
7949       impl->internal_run_death_test_flag();
7950   const TestInfo* const info = impl->current_test_info();
7951   const int death_test_index = info->result()->death_test_count();
7952 
7953   if (flag != NULL) {
7954     set_write_fd(flag->write_fd());
7955     return EXECUTE_TEST;
7956   }
7957 
7958   int pipe_fd[2];
7959   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7960   // Clear the close-on-exec flag on the write end of the pipe, lest
7961   // it be closed when the child process does an exec:
7962   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7963 
7964   const std::string filter_flag =
7965       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
7966       + info->test_case_name() + "." + info->name();
7967   const std::string internal_flag =
7968       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
7969       + file_ + "|" + StreamableToString(line_) + "|"
7970       + StreamableToString(death_test_index) + "|"
7971       + StreamableToString(pipe_fd[1]);
7972   Arguments args;
7973   args.AddArguments(GetArgvsForDeathTestChildProcess());
7974   args.AddArgument(filter_flag.c_str());
7975   args.AddArgument(internal_flag.c_str());
7976 
7977   DeathTest::set_last_death_test_message("");
7978 
7979   CaptureStderr();
7980   // See the comment in NoExecDeathTest::AssumeRole for why the next line
7981   // is necessary.
7982   FlushInfoLog();
7983 
7984   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7985   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7986   set_child_pid(child_pid);
7987   set_read_fd(pipe_fd[0]);
7988   set_spawned(true);
7989   return OVERSEE_TEST;
7990 }
7991 
7992 # endif  // !GTEST_OS_WINDOWS
7993 
7994 // Creates a concrete DeathTest-derived class that depends on the
7995 // --gtest_death_test_style flag, and sets the pointer pointed to
7996 // by the "test" argument to its address.  If the test should be
7997 // skipped, sets that pointer to NULL.  Returns true, unless the
7998 // flag is set to an invalid value.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)7999 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
8000                                      const char* file, int line,
8001                                      DeathTest** test) {
8002   UnitTestImpl* const impl = GetUnitTestImpl();
8003   const InternalRunDeathTestFlag* const flag =
8004       impl->internal_run_death_test_flag();
8005   const int death_test_index = impl->current_test_info()
8006       ->increment_death_test_count();
8007 
8008   if (flag != NULL) {
8009     if (death_test_index > flag->index()) {
8010       DeathTest::set_last_death_test_message(
8011           "Death test count (" + StreamableToString(death_test_index)
8012           + ") somehow exceeded expected maximum ("
8013           + StreamableToString(flag->index()) + ")");
8014       return false;
8015     }
8016 
8017     if (!(flag->file() == file && flag->line() == line &&
8018           flag->index() == death_test_index)) {
8019       *test = NULL;
8020       return true;
8021     }
8022   }
8023 
8024 # if GTEST_OS_WINDOWS
8025 
8026   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
8027       GTEST_FLAG(death_test_style) == "fast") {
8028     *test = new WindowsDeathTest(statement, regex, file, line);
8029   }
8030 
8031 # else
8032 
8033   if (GTEST_FLAG(death_test_style) == "threadsafe") {
8034     *test = new ExecDeathTest(statement, regex, file, line);
8035   } else if (GTEST_FLAG(death_test_style) == "fast") {
8036     *test = new NoExecDeathTest(statement, regex);
8037   }
8038 
8039 # endif  // GTEST_OS_WINDOWS
8040 
8041   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
8042     DeathTest::set_last_death_test_message(
8043         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
8044         + "\" encountered");
8045     return false;
8046   }
8047 
8048   return true;
8049 }
8050 
8051 # if GTEST_OS_WINDOWS
8052 // Recreates the pipe and event handles from the provided parameters,
8053 // signals the event, and returns a file descriptor wrapped around the pipe
8054 // 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)8055 int GetStatusFileDescriptor(unsigned int parent_process_id,
8056                             size_t write_handle_as_size_t,
8057                             size_t event_handle_as_size_t) {
8058   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
8059                                                    FALSE,  // Non-inheritable.
8060                                                    parent_process_id));
8061   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
8062     DeathTestAbort("Unable to open parent process " +
8063                    StreamableToString(parent_process_id));
8064   }
8065 
8066   // TODO(vladl@google.com): Replace the following check with a
8067   // compile-time assertion when available.
8068   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
8069 
8070   const HANDLE write_handle =
8071       reinterpret_cast<HANDLE>(write_handle_as_size_t);
8072   HANDLE dup_write_handle;
8073 
8074   // The newly initialized handle is accessible only in in the parent
8075   // process. To obtain one accessible within the child, we need to use
8076   // DuplicateHandle.
8077   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
8078                          ::GetCurrentProcess(), &dup_write_handle,
8079                          0x0,    // Requested privileges ignored since
8080                                  // DUPLICATE_SAME_ACCESS is used.
8081                          FALSE,  // Request non-inheritable handler.
8082                          DUPLICATE_SAME_ACCESS)) {
8083     DeathTestAbort("Unable to duplicate the pipe handle " +
8084                    StreamableToString(write_handle_as_size_t) +
8085                    " from the parent process " +
8086                    StreamableToString(parent_process_id));
8087   }
8088 
8089   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
8090   HANDLE dup_event_handle;
8091 
8092   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
8093                          ::GetCurrentProcess(), &dup_event_handle,
8094                          0x0,
8095                          FALSE,
8096                          DUPLICATE_SAME_ACCESS)) {
8097     DeathTestAbort("Unable to duplicate the event handle " +
8098                    StreamableToString(event_handle_as_size_t) +
8099                    " from the parent process " +
8100                    StreamableToString(parent_process_id));
8101   }
8102 
8103   const int write_fd =
8104       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
8105   if (write_fd == -1) {
8106     DeathTestAbort("Unable to convert pipe handle " +
8107                    StreamableToString(write_handle_as_size_t) +
8108                    " to a file descriptor");
8109   }
8110 
8111   // Signals the parent that the write end of the pipe has been acquired
8112   // so the parent can release its own write end.
8113   ::SetEvent(dup_event_handle);
8114 
8115   return write_fd;
8116 }
8117 # endif  // GTEST_OS_WINDOWS
8118 
8119 // Returns a newly created InternalRunDeathTestFlag object with fields
8120 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
8121 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()8122 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
8123   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
8124 
8125   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
8126   // can use it here.
8127   int line = -1;
8128   int index = -1;
8129   ::std::vector< ::std::string> fields;
8130   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
8131   int write_fd = -1;
8132 
8133 # if GTEST_OS_WINDOWS
8134 
8135   unsigned int parent_process_id = 0;
8136   size_t write_handle_as_size_t = 0;
8137   size_t event_handle_as_size_t = 0;
8138 
8139   if (fields.size() != 6
8140       || !ParseNaturalNumber(fields[1], &line)
8141       || !ParseNaturalNumber(fields[2], &index)
8142       || !ParseNaturalNumber(fields[3], &parent_process_id)
8143       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
8144       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
8145     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
8146                    GTEST_FLAG(internal_run_death_test));
8147   }
8148   write_fd = GetStatusFileDescriptor(parent_process_id,
8149                                      write_handle_as_size_t,
8150                                      event_handle_as_size_t);
8151 # else
8152 
8153   if (fields.size() != 4
8154       || !ParseNaturalNumber(fields[1], &line)
8155       || !ParseNaturalNumber(fields[2], &index)
8156       || !ParseNaturalNumber(fields[3], &write_fd)) {
8157     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
8158         + GTEST_FLAG(internal_run_death_test));
8159   }
8160 
8161 # endif  // GTEST_OS_WINDOWS
8162 
8163   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
8164 }
8165 
8166 }  // namespace internal
8167 
8168 #endif  // GTEST_HAS_DEATH_TEST
8169 
8170 }  // namespace testing
8171 // Copyright 2008, Google Inc.
8172 // All rights reserved.
8173 //
8174 // Redistribution and use in source and binary forms, with or without
8175 // modification, are permitted provided that the following conditions are
8176 // met:
8177 //
8178 //     * Redistributions of source code must retain the above copyright
8179 // notice, this list of conditions and the following disclaimer.
8180 //     * Redistributions in binary form must reproduce the above
8181 // copyright notice, this list of conditions and the following disclaimer
8182 // in the documentation and/or other materials provided with the
8183 // distribution.
8184 //     * Neither the name of Google Inc. nor the names of its
8185 // contributors may be used to endorse or promote products derived from
8186 // this software without specific prior written permission.
8187 //
8188 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8189 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8190 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8191 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8192 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8193 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8194 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8195 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8196 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8197 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8198 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8199 //
8200 // Authors: keith.ray@gmail.com (Keith Ray)
8201 
8202 
8203 #include <stdlib.h>
8204 
8205 #if GTEST_OS_WINDOWS_MOBILE
8206 # include <windows.h>
8207 #elif GTEST_OS_WINDOWS
8208 # include <direct.h>
8209 # include <io.h>
8210 #elif GTEST_OS_SYMBIAN
8211 // Symbian OpenC has PATH_MAX in sys/syslimits.h
8212 # include <sys/syslimits.h>
8213 #else
8214 # include <limits.h>
8215 # include <climits>  // Some Linux distributions define PATH_MAX here.
8216 #endif  // GTEST_OS_WINDOWS_MOBILE
8217 
8218 #if GTEST_OS_WINDOWS
8219 # define GTEST_PATH_MAX_ _MAX_PATH
8220 #elif defined(PATH_MAX)
8221 # define GTEST_PATH_MAX_ PATH_MAX
8222 #elif defined(_XOPEN_PATH_MAX)
8223 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
8224 #else
8225 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
8226 #endif  // GTEST_OS_WINDOWS
8227 
8228 
8229 namespace testing {
8230 namespace internal {
8231 
8232 #if GTEST_OS_WINDOWS
8233 // On Windows, '\\' is the standard path separator, but many tools and the
8234 // Windows API also accept '/' as an alternate path separator. Unless otherwise
8235 // noted, a file path can contain either kind of path separators, or a mixture
8236 // of them.
8237 const char kPathSeparator = '\\';
8238 const char kAlternatePathSeparator = '/';
8239 const char kAlternatePathSeparatorString[] = "/";
8240 # if GTEST_OS_WINDOWS_MOBILE
8241 // Windows CE doesn't have a current directory. You should not use
8242 // the current directory in tests on Windows CE, but this at least
8243 // provides a reasonable fallback.
8244 const char kCurrentDirectoryString[] = "\\";
8245 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
8246 const DWORD kInvalidFileAttributes = 0xffffffff;
8247 # else
8248 const char kCurrentDirectoryString[] = ".\\";
8249 # endif  // GTEST_OS_WINDOWS_MOBILE
8250 #else
8251 const char kPathSeparator = '/';
8252 const char kCurrentDirectoryString[] = "./";
8253 #endif  // GTEST_OS_WINDOWS
8254 
8255 // Returns whether the given character is a valid path separator.
IsPathSeparator(char c)8256 static bool IsPathSeparator(char c) {
8257 #if GTEST_HAS_ALT_PATH_SEP_
8258   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
8259 #else
8260   return c == kPathSeparator;
8261 #endif
8262 }
8263 
8264 // Returns the current working directory, or "" if unsuccessful.
GetCurrentDir()8265 FilePath FilePath::GetCurrentDir() {
8266 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
8267   // Windows CE doesn't have a current directory, so we just return
8268   // something reasonable.
8269   return FilePath(kCurrentDirectoryString);
8270 #elif GTEST_OS_WINDOWS
8271   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
8272   return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
8273 #else
8274   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
8275   char* result = getcwd(cwd, sizeof(cwd));
8276 # if GTEST_OS_NACL
8277   // getcwd will likely fail in NaCl due to the sandbox, so return something
8278   // reasonable. The user may have provided a shim implementation for getcwd,
8279   // however, so fallback only when failure is detected.
8280   return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
8281 # endif  // GTEST_OS_NACL
8282   return FilePath(result == NULL ? "" : cwd);
8283 #endif  // GTEST_OS_WINDOWS_MOBILE
8284 }
8285 
8286 // Returns a copy of the FilePath with the case-insensitive extension removed.
8287 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
8288 // FilePath("dir/file"). If a case-insensitive extension is not
8289 // found, returns a copy of the original FilePath.
RemoveExtension(const char * extension) const8290 FilePath FilePath::RemoveExtension(const char* extension) const {
8291   const std::string dot_extension = std::string(".") + extension;
8292   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
8293     return FilePath(pathname_.substr(
8294         0, pathname_.length() - dot_extension.length()));
8295   }
8296   return *this;
8297 }
8298 
8299 // Returns a pointer to the last occurence of a valid path separator in
8300 // the FilePath. On Windows, for example, both '/' and '\' are valid path
8301 // separators. Returns NULL if no path separator was found.
FindLastPathSeparator() const8302 const char* FilePath::FindLastPathSeparator() const {
8303   const char* const last_sep = strrchr(c_str(), kPathSeparator);
8304 #if GTEST_HAS_ALT_PATH_SEP_
8305   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
8306   // Comparing two pointers of which only one is NULL is undefined.
8307   if (last_alt_sep != NULL &&
8308       (last_sep == NULL || last_alt_sep > last_sep)) {
8309     return last_alt_sep;
8310   }
8311 #endif
8312   return last_sep;
8313 }
8314 
8315 // Returns a copy of the FilePath with the directory part removed.
8316 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
8317 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
8318 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
8319 // returns an empty FilePath ("").
8320 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveDirectoryName() const8321 FilePath FilePath::RemoveDirectoryName() const {
8322   const char* const last_sep = FindLastPathSeparator();
8323   return last_sep ? FilePath(last_sep + 1) : *this;
8324 }
8325 
8326 // RemoveFileName returns the directory path with the filename removed.
8327 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
8328 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
8329 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
8330 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
8331 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveFileName() const8332 FilePath FilePath::RemoveFileName() const {
8333   const char* const last_sep = FindLastPathSeparator();
8334   std::string dir;
8335   if (last_sep) {
8336     dir = std::string(c_str(), last_sep + 1 - c_str());
8337   } else {
8338     dir = kCurrentDirectoryString;
8339   }
8340   return FilePath(dir);
8341 }
8342 
8343 // Helper functions for naming files in a directory for xml output.
8344 
8345 // Given directory = "dir", base_name = "test", number = 0,
8346 // extension = "xml", returns "dir/test.xml". If number is greater
8347 // than zero (e.g., 12), returns "dir/test_12.xml".
8348 // On Windows platform, uses \ as the separator rather than /.
MakeFileName(const FilePath & directory,const FilePath & base_name,int number,const char * extension)8349 FilePath FilePath::MakeFileName(const FilePath& directory,
8350                                 const FilePath& base_name,
8351                                 int number,
8352                                 const char* extension) {
8353   std::string file;
8354   if (number == 0) {
8355     file = base_name.string() + "." + extension;
8356   } else {
8357     file = base_name.string() + "_" + StreamableToString(number)
8358         + "." + extension;
8359   }
8360   return ConcatPaths(directory, FilePath(file));
8361 }
8362 
8363 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
8364 // On Windows, uses \ as the separator rather than /.
ConcatPaths(const FilePath & directory,const FilePath & relative_path)8365 FilePath FilePath::ConcatPaths(const FilePath& directory,
8366                                const FilePath& relative_path) {
8367   if (directory.IsEmpty())
8368     return relative_path;
8369   const FilePath dir(directory.RemoveTrailingPathSeparator());
8370   return FilePath(dir.string() + kPathSeparator + relative_path.string());
8371 }
8372 
8373 // Returns true if pathname describes something findable in the file-system,
8374 // either a file, directory, or whatever.
FileOrDirectoryExists() const8375 bool FilePath::FileOrDirectoryExists() const {
8376 #if GTEST_OS_WINDOWS_MOBILE
8377   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
8378   const DWORD attributes = GetFileAttributes(unicode);
8379   delete [] unicode;
8380   return attributes != kInvalidFileAttributes;
8381 #else
8382   posix::StatStruct file_stat;
8383   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
8384 #endif  // GTEST_OS_WINDOWS_MOBILE
8385 }
8386 
8387 // Returns true if pathname describes a directory in the file-system
8388 // that exists.
DirectoryExists() const8389 bool FilePath::DirectoryExists() const {
8390   bool result = false;
8391 #if GTEST_OS_WINDOWS
8392   // Don't strip off trailing separator if path is a root directory on
8393   // Windows (like "C:\\").
8394   const FilePath& path(IsRootDirectory() ? *this :
8395                                            RemoveTrailingPathSeparator());
8396 #else
8397   const FilePath& path(*this);
8398 #endif
8399 
8400 #if GTEST_OS_WINDOWS_MOBILE
8401   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
8402   const DWORD attributes = GetFileAttributes(unicode);
8403   delete [] unicode;
8404   if ((attributes != kInvalidFileAttributes) &&
8405       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8406     result = true;
8407   }
8408 #else
8409   posix::StatStruct file_stat;
8410   result = posix::Stat(path.c_str(), &file_stat) == 0 &&
8411       posix::IsDir(file_stat);
8412 #endif  // GTEST_OS_WINDOWS_MOBILE
8413 
8414   return result;
8415 }
8416 
8417 // Returns true if pathname describes a root directory. (Windows has one
8418 // root directory per disk drive.)
IsRootDirectory() const8419 bool FilePath::IsRootDirectory() const {
8420 #if GTEST_OS_WINDOWS
8421   // TODO(wan@google.com): on Windows a network share like
8422   // \\server\share can be a root directory, although it cannot be the
8423   // current directory.  Handle this properly.
8424   return pathname_.length() == 3 && IsAbsolutePath();
8425 #else
8426   return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
8427 #endif
8428 }
8429 
8430 // Returns true if pathname describes an absolute path.
IsAbsolutePath() const8431 bool FilePath::IsAbsolutePath() const {
8432   const char* const name = pathname_.c_str();
8433 #if GTEST_OS_WINDOWS
8434   return pathname_.length() >= 3 &&
8435      ((name[0] >= 'a' && name[0] <= 'z') ||
8436       (name[0] >= 'A' && name[0] <= 'Z')) &&
8437      name[1] == ':' &&
8438      IsPathSeparator(name[2]);
8439 #else
8440   return IsPathSeparator(name[0]);
8441 #endif
8442 }
8443 
8444 // Returns a pathname for a file that does not currently exist. The pathname
8445 // will be directory/base_name.extension or
8446 // directory/base_name_<number>.extension if directory/base_name.extension
8447 // already exists. The number will be incremented until a pathname is found
8448 // that does not already exist.
8449 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8450 // There could be a race condition if two or more processes are calling this
8451 // function at the same time -- they could both pick the same filename.
GenerateUniqueFileName(const FilePath & directory,const FilePath & base_name,const char * extension)8452 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
8453                                           const FilePath& base_name,
8454                                           const char* extension) {
8455   FilePath full_pathname;
8456   int number = 0;
8457   do {
8458     full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
8459   } while (full_pathname.FileOrDirectoryExists());
8460   return full_pathname;
8461 }
8462 
8463 // Returns true if FilePath ends with a path separator, which indicates that
8464 // it is intended to represent a directory. Returns false otherwise.
8465 // This does NOT check that a directory (or file) actually exists.
IsDirectory() const8466 bool FilePath::IsDirectory() const {
8467   return !pathname_.empty() &&
8468          IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
8469 }
8470 
8471 // Create directories so that path exists. Returns true if successful or if
8472 // the directories already exist; returns false if unable to create directories
8473 // for any reason.
CreateDirectoriesRecursively() const8474 bool FilePath::CreateDirectoriesRecursively() const {
8475   if (!this->IsDirectory()) {
8476     return false;
8477   }
8478 
8479   if (pathname_.length() == 0 || this->DirectoryExists()) {
8480     return true;
8481   }
8482 
8483   const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8484   return parent.CreateDirectoriesRecursively() && this->CreateFolder();
8485 }
8486 
8487 // Create the directory so that path exists. Returns true if successful or
8488 // if the directory already exists; returns false if unable to create the
8489 // directory for any reason, including if the parent directory does not
8490 // exist. Not named "CreateDirectory" because that's a macro on Windows.
CreateFolder() const8491 bool FilePath::CreateFolder() const {
8492 #if GTEST_OS_WINDOWS_MOBILE
8493   FilePath removed_sep(this->RemoveTrailingPathSeparator());
8494   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8495   int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8496   delete [] unicode;
8497 #elif GTEST_OS_WINDOWS
8498   int result = _mkdir(pathname_.c_str());
8499 #else
8500   int result = mkdir(pathname_.c_str(), 0777);
8501 #endif  // GTEST_OS_WINDOWS_MOBILE
8502 
8503   if (result == -1) {
8504     return this->DirectoryExists();  // An error is OK if the directory exists.
8505   }
8506   return true;  // No error.
8507 }
8508 
8509 // If input name has a trailing separator character, remove it and return the
8510 // name, otherwise return the name string unmodified.
8511 // On Windows platform, uses \ as the separator, other platforms use /.
RemoveTrailingPathSeparator() const8512 FilePath FilePath::RemoveTrailingPathSeparator() const {
8513   return IsDirectory()
8514       ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8515       : *this;
8516 }
8517 
8518 // Removes any redundant separators that might be in the pathname.
8519 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8520 // redundancies that might be in a pathname involving "." or "..".
8521 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
Normalize()8522 void FilePath::Normalize() {
8523   if (pathname_.c_str() == NULL) {
8524     pathname_ = "";
8525     return;
8526   }
8527   const char* src = pathname_.c_str();
8528   char* const dest = new char[pathname_.length() + 1];
8529   char* dest_ptr = dest;
8530   memset(dest_ptr, 0, pathname_.length() + 1);
8531 
8532   while (*src != '\0') {
8533     *dest_ptr = *src;
8534     if (!IsPathSeparator(*src)) {
8535       src++;
8536     } else {
8537 #if GTEST_HAS_ALT_PATH_SEP_
8538       if (*dest_ptr == kAlternatePathSeparator) {
8539         *dest_ptr = kPathSeparator;
8540       }
8541 #endif
8542       while (IsPathSeparator(*src))
8543         src++;
8544     }
8545     dest_ptr++;
8546   }
8547   *dest_ptr = '\0';
8548   pathname_ = dest;
8549   delete[] dest;
8550 }
8551 
8552 }  // namespace internal
8553 }  // namespace testing
8554 // Copyright 2008, Google Inc.
8555 // All rights reserved.
8556 //
8557 // Redistribution and use in source and binary forms, with or without
8558 // modification, are permitted provided that the following conditions are
8559 // met:
8560 //
8561 //     * Redistributions of source code must retain the above copyright
8562 // notice, this list of conditions and the following disclaimer.
8563 //     * Redistributions in binary form must reproduce the above
8564 // copyright notice, this list of conditions and the following disclaimer
8565 // in the documentation and/or other materials provided with the
8566 // distribution.
8567 //     * Neither the name of Google Inc. nor the names of its
8568 // contributors may be used to endorse or promote products derived from
8569 // this software without specific prior written permission.
8570 //
8571 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8572 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8573 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8574 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8575 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8576 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8577 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8578 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8579 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8580 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8581 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8582 //
8583 // Author: wan@google.com (Zhanyong Wan)
8584 
8585 
8586 #include <limits.h>
8587 #include <stdlib.h>
8588 #include <stdio.h>
8589 #include <string.h>
8590 #include <fstream>
8591 
8592 #if GTEST_OS_WINDOWS
8593 # include <windows.h>
8594 # include <io.h>
8595 # include <sys/stat.h>
8596 # include <map>  // Used in ThreadLocal.
8597 #else
8598 # include <unistd.h>
8599 #endif  // GTEST_OS_WINDOWS
8600 
8601 #if GTEST_OS_MAC
8602 # include <mach/mach_init.h>
8603 # include <mach/task.h>
8604 # include <mach/vm_map.h>
8605 #endif  // GTEST_OS_MAC
8606 
8607 #if GTEST_OS_QNX
8608 # include <devctl.h>
8609 # include <fcntl.h>
8610 # include <sys/procfs.h>
8611 #endif  // GTEST_OS_QNX
8612 
8613 
8614 // Indicates that this translation unit is part of Google Test's
8615 // implementation.  It must come before gtest-internal-inl.h is
8616 // included, or there will be a compiler error.  This trick exists to
8617 // prevent the accidental inclusion of gtest-internal-inl.h in the
8618 // user's code.
8619 #define GTEST_IMPLEMENTATION_ 1
8620 #undef GTEST_IMPLEMENTATION_
8621 
8622 namespace testing {
8623 namespace internal {
8624 
8625 #if defined(_MSC_VER) || defined(__BORLANDC__)
8626 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8627 const int kStdOutFileno = 1;
8628 const int kStdErrFileno = 2;
8629 #else
8630 const int kStdOutFileno = STDOUT_FILENO;
8631 const int kStdErrFileno = STDERR_FILENO;
8632 #endif  // _MSC_VER
8633 
8634 #if GTEST_OS_LINUX
8635 
8636 namespace {
8637 template <typename T>
ReadProcFileField(const string & filename,int field)8638 T ReadProcFileField(const string& filename, int field) {
8639   std::string dummy;
8640   std::ifstream file(filename.c_str());
8641   while (field-- > 0) {
8642     file >> dummy;
8643   }
8644   T output = 0;
8645   file >> output;
8646   return output;
8647 }
8648 }  // namespace
8649 
8650 // Returns the number of active threads, or 0 when there is an error.
GetThreadCount()8651 size_t GetThreadCount() {
8652   const string filename =
8653       (Message() << "/proc/" << getpid() << "/stat").GetString();
8654   return ReadProcFileField<int>(filename, 19);
8655 }
8656 
8657 #elif GTEST_OS_MAC
8658 
GetThreadCount()8659 size_t GetThreadCount() {
8660   const task_t task = mach_task_self();
8661   mach_msg_type_number_t thread_count;
8662   thread_act_array_t thread_list;
8663   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8664   if (status == KERN_SUCCESS) {
8665     // task_threads allocates resources in thread_list and we need to free them
8666     // to avoid leaks.
8667     vm_deallocate(task,
8668                   reinterpret_cast<vm_address_t>(thread_list),
8669                   sizeof(thread_t) * thread_count);
8670     return static_cast<size_t>(thread_count);
8671   } else {
8672     return 0;
8673   }
8674 }
8675 
8676 #elif GTEST_OS_QNX
8677 
8678 // Returns the number of threads running in the process, or 0 to indicate that
8679 // we cannot detect it.
GetThreadCount()8680 size_t GetThreadCount() {
8681   const int fd = open("/proc/self/as", O_RDONLY);
8682   if (fd < 0) {
8683     return 0;
8684   }
8685   procfs_info process_info;
8686   const int status =
8687       devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8688   close(fd);
8689   if (status == EOK) {
8690     return static_cast<size_t>(process_info.num_threads);
8691   } else {
8692     return 0;
8693   }
8694 }
8695 
8696 #else
8697 
GetThreadCount()8698 size_t GetThreadCount() {
8699   // There's no portable way to detect the number of threads, so we just
8700   // return 0 to indicate that we cannot detect it.
8701   return 0;
8702 }
8703 
8704 #endif  // GTEST_OS_LINUX
8705 
8706 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
8707 
SleepMilliseconds(int n)8708 void SleepMilliseconds(int n) {
8709   ::Sleep(n);
8710 }
8711 
AutoHandle()8712 AutoHandle::AutoHandle()
8713     : handle_(INVALID_HANDLE_VALUE) {}
8714 
AutoHandle(Handle handle)8715 AutoHandle::AutoHandle(Handle handle)
8716     : handle_(handle) {}
8717 
~AutoHandle()8718 AutoHandle::~AutoHandle() {
8719   Reset();
8720 }
8721 
Get() const8722 AutoHandle::Handle AutoHandle::Get() const {
8723   return handle_;
8724 }
8725 
Reset()8726 void AutoHandle::Reset() {
8727   Reset(INVALID_HANDLE_VALUE);
8728 }
8729 
Reset(HANDLE handle)8730 void AutoHandle::Reset(HANDLE handle) {
8731   // Resetting with the same handle we already own is invalid.
8732   if (handle_ != handle) {
8733     if (IsCloseable()) {
8734       ::CloseHandle(handle_);
8735     }
8736     handle_ = handle;
8737   } else {
8738     GTEST_CHECK_(!IsCloseable())
8739         << "Resetting a valid handle to itself is likely a programmer error "
8740             "and thus not allowed.";
8741   }
8742 }
8743 
IsCloseable() const8744 bool AutoHandle::IsCloseable() const {
8745   // Different Windows APIs may use either of these values to represent an
8746   // invalid handle.
8747   return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
8748 }
8749 
Notification()8750 Notification::Notification()
8751     : event_(::CreateEvent(NULL,   // Default security attributes.
8752                            TRUE,   // Do not reset automatically.
8753                            FALSE,  // Initially unset.
8754                            NULL)) {  // Anonymous event.
8755   GTEST_CHECK_(event_.Get() != NULL);
8756 }
8757 
Notify()8758 void Notification::Notify() {
8759   GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
8760 }
8761 
WaitForNotification()8762 void Notification::WaitForNotification() {
8763   GTEST_CHECK_(
8764       ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
8765 }
8766 
Mutex()8767 Mutex::Mutex()
8768     : owner_thread_id_(0),
8769       type_(kDynamic),
8770       critical_section_init_phase_(0),
8771       critical_section_(new CRITICAL_SECTION) {
8772   ::InitializeCriticalSection(critical_section_);
8773 }
8774 
~Mutex()8775 Mutex::~Mutex() {
8776   // Static mutexes are leaked intentionally. It is not thread-safe to try
8777   // to clean them up.
8778   // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
8779   // nothing to clean it up but is available only on Vista and later.
8780   // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
8781   if (type_ == kDynamic) {
8782     ::DeleteCriticalSection(critical_section_);
8783     delete critical_section_;
8784     critical_section_ = NULL;
8785   }
8786 }
8787 
Lock()8788 void Mutex::Lock() {
8789   ThreadSafeLazyInit();
8790   ::EnterCriticalSection(critical_section_);
8791   owner_thread_id_ = ::GetCurrentThreadId();
8792 }
8793 
Unlock()8794 void Mutex::Unlock() {
8795   ThreadSafeLazyInit();
8796   // We don't protect writing to owner_thread_id_ here, as it's the
8797   // caller's responsibility to ensure that the current thread holds the
8798   // mutex when this is called.
8799   owner_thread_id_ = 0;
8800   ::LeaveCriticalSection(critical_section_);
8801 }
8802 
8803 // Does nothing if the current thread holds the mutex. Otherwise, crashes
8804 // with high probability.
AssertHeld()8805 void Mutex::AssertHeld() {
8806   ThreadSafeLazyInit();
8807   GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
8808       << "The current thread is not holding the mutex @" << this;
8809 }
8810 
8811 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
ThreadSafeLazyInit()8812 void Mutex::ThreadSafeLazyInit() {
8813   // Dynamic mutexes are initialized in the constructor.
8814   if (type_ == kStatic) {
8815     switch (
8816         ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
8817       case 0:
8818         // If critical_section_init_phase_ was 0 before the exchange, we
8819         // are the first to test it and need to perform the initialization.
8820         owner_thread_id_ = 0;
8821         critical_section_ = new CRITICAL_SECTION;
8822         ::InitializeCriticalSection(critical_section_);
8823         // Updates the critical_section_init_phase_ to 2 to signal
8824         // initialization complete.
8825         GTEST_CHECK_(::InterlockedCompareExchange(
8826                           &critical_section_init_phase_, 2L, 1L) ==
8827                       1L);
8828         break;
8829       case 1:
8830         // Somebody else is already initializing the mutex; spin until they
8831         // are done.
8832         while (::InterlockedCompareExchange(&critical_section_init_phase_,
8833                                             2L,
8834                                             2L) != 2L) {
8835           // Possibly yields the rest of the thread's time slice to other
8836           // threads.
8837           ::Sleep(0);
8838         }
8839         break;
8840 
8841       case 2:
8842         break;  // The mutex is already initialized and ready for use.
8843 
8844       default:
8845         GTEST_CHECK_(false)
8846             << "Unexpected value of critical_section_init_phase_ "
8847             << "while initializing a static mutex.";
8848     }
8849   }
8850 }
8851 
8852 namespace {
8853 
8854 class ThreadWithParamSupport : public ThreadWithParamBase {
8855  public:
CreateThread(Runnable * runnable,Notification * thread_can_start)8856   static HANDLE CreateThread(Runnable* runnable,
8857                              Notification* thread_can_start) {
8858     ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
8859     DWORD thread_id;
8860     // TODO(yukawa): Consider to use _beginthreadex instead.
8861     HANDLE thread_handle = ::CreateThread(
8862         NULL,    // Default security.
8863         0,       // Default stack size.
8864         &ThreadWithParamSupport::ThreadMain,
8865         param,   // Parameter to ThreadMainStatic
8866         0x0,     // Default creation flags.
8867         &thread_id);  // Need a valid pointer for the call to work under Win98.
8868     GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
8869                                         << ::GetLastError() << ".";
8870     if (thread_handle == NULL) {
8871       delete param;
8872     }
8873     return thread_handle;
8874   }
8875 
8876  private:
8877   struct ThreadMainParam {
ThreadMainParamtesting::internal::__anon77204b490911::ThreadWithParamSupport::ThreadMainParam8878     ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
8879         : runnable_(runnable),
8880           thread_can_start_(thread_can_start) {
8881     }
8882     scoped_ptr<Runnable> runnable_;
8883     // Does not own.
8884     Notification* thread_can_start_;
8885   };
8886 
ThreadMain(void * ptr)8887   static DWORD WINAPI ThreadMain(void* ptr) {
8888     // Transfers ownership.
8889     scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
8890     if (param->thread_can_start_ != NULL)
8891       param->thread_can_start_->WaitForNotification();
8892     param->runnable_->Run();
8893     return 0;
8894   }
8895 
8896   // Prohibit instantiation.
8897   ThreadWithParamSupport();
8898 
8899   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
8900 };
8901 
8902 }  // namespace
8903 
ThreadWithParamBase(Runnable * runnable,Notification * thread_can_start)8904 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
8905                                          Notification* thread_can_start)
8906       : thread_(ThreadWithParamSupport::CreateThread(runnable,
8907                                                      thread_can_start)) {
8908 }
8909 
~ThreadWithParamBase()8910 ThreadWithParamBase::~ThreadWithParamBase() {
8911   Join();
8912 }
8913 
Join()8914 void ThreadWithParamBase::Join() {
8915   GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
8916       << "Failed to join the thread with error " << ::GetLastError() << ".";
8917 }
8918 
8919 // Maps a thread to a set of ThreadIdToThreadLocals that have values
8920 // instantiated on that thread and notifies them when the thread exits.  A
8921 // ThreadLocal instance is expected to persist until all threads it has
8922 // values on have terminated.
8923 class ThreadLocalRegistryImpl {
8924  public:
8925   // Registers thread_local_instance as having value on the current thread.
8926   // Returns a value that can be used to identify the thread from other threads.
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)8927   static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
8928       const ThreadLocalBase* thread_local_instance) {
8929     DWORD current_thread = ::GetCurrentThreadId();
8930     MutexLock lock(&mutex_);
8931     ThreadIdToThreadLocals* const thread_to_thread_locals =
8932         GetThreadLocalsMapLocked();
8933     ThreadIdToThreadLocals::iterator thread_local_pos =
8934         thread_to_thread_locals->find(current_thread);
8935     if (thread_local_pos == thread_to_thread_locals->end()) {
8936       thread_local_pos = thread_to_thread_locals->insert(
8937           std::make_pair(current_thread, ThreadLocalValues())).first;
8938       StartWatcherThreadFor(current_thread);
8939     }
8940     ThreadLocalValues& thread_local_values = thread_local_pos->second;
8941     ThreadLocalValues::iterator value_pos =
8942         thread_local_values.find(thread_local_instance);
8943     if (value_pos == thread_local_values.end()) {
8944       value_pos =
8945           thread_local_values
8946               .insert(std::make_pair(
8947                   thread_local_instance,
8948                   linked_ptr<ThreadLocalValueHolderBase>(
8949                       thread_local_instance->NewValueForCurrentThread())))
8950               .first;
8951     }
8952     return value_pos->second.get();
8953   }
8954 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)8955   static void OnThreadLocalDestroyed(
8956       const ThreadLocalBase* thread_local_instance) {
8957     std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
8958     // Clean up the ThreadLocalValues data structure while holding the lock, but
8959     // defer the destruction of the ThreadLocalValueHolderBases.
8960     {
8961       MutexLock lock(&mutex_);
8962       ThreadIdToThreadLocals* const thread_to_thread_locals =
8963           GetThreadLocalsMapLocked();
8964       for (ThreadIdToThreadLocals::iterator it =
8965           thread_to_thread_locals->begin();
8966           it != thread_to_thread_locals->end();
8967           ++it) {
8968         ThreadLocalValues& thread_local_values = it->second;
8969         ThreadLocalValues::iterator value_pos =
8970             thread_local_values.find(thread_local_instance);
8971         if (value_pos != thread_local_values.end()) {
8972           value_holders.push_back(value_pos->second);
8973           thread_local_values.erase(value_pos);
8974           // This 'if' can only be successful at most once, so theoretically we
8975           // could break out of the loop here, but we don't bother doing so.
8976         }
8977       }
8978     }
8979     // Outside the lock, let the destructor for 'value_holders' deallocate the
8980     // ThreadLocalValueHolderBases.
8981   }
8982 
OnThreadExit(DWORD thread_id)8983   static void OnThreadExit(DWORD thread_id) {
8984     GTEST_CHECK_(thread_id != 0) << ::GetLastError();
8985     std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
8986     // Clean up the ThreadIdToThreadLocals data structure while holding the
8987     // lock, but defer the destruction of the ThreadLocalValueHolderBases.
8988     {
8989       MutexLock lock(&mutex_);
8990       ThreadIdToThreadLocals* const thread_to_thread_locals =
8991           GetThreadLocalsMapLocked();
8992       ThreadIdToThreadLocals::iterator thread_local_pos =
8993           thread_to_thread_locals->find(thread_id);
8994       if (thread_local_pos != thread_to_thread_locals->end()) {
8995         ThreadLocalValues& thread_local_values = thread_local_pos->second;
8996         for (ThreadLocalValues::iterator value_pos =
8997             thread_local_values.begin();
8998             value_pos != thread_local_values.end();
8999             ++value_pos) {
9000           value_holders.push_back(value_pos->second);
9001         }
9002         thread_to_thread_locals->erase(thread_local_pos);
9003       }
9004     }
9005     // Outside the lock, let the destructor for 'value_holders' deallocate the
9006     // ThreadLocalValueHolderBases.
9007   }
9008 
9009  private:
9010   // In a particular thread, maps a ThreadLocal object to its value.
9011   typedef std::map<const ThreadLocalBase*,
9012                    linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
9013   // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
9014   // thread's ID.
9015   typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
9016 
9017   // Holds the thread id and thread handle that we pass from
9018   // StartWatcherThreadFor to WatcherThreadFunc.
9019   typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
9020 
StartWatcherThreadFor(DWORD thread_id)9021   static void StartWatcherThreadFor(DWORD thread_id) {
9022     // The returned handle will be kept in thread_map and closed by
9023     // watcher_thread in WatcherThreadFunc.
9024     HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
9025                                  FALSE,
9026                                  thread_id);
9027     GTEST_CHECK_(thread != NULL);
9028     // We need to to pass a valid thread ID pointer into CreateThread for it
9029     // to work correctly under Win98.
9030     DWORD watcher_thread_id;
9031     HANDLE watcher_thread = ::CreateThread(
9032         NULL,   // Default security.
9033         0,      // Default stack size
9034         &ThreadLocalRegistryImpl::WatcherThreadFunc,
9035         reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
9036         CREATE_SUSPENDED,
9037         &watcher_thread_id);
9038     GTEST_CHECK_(watcher_thread != NULL);
9039     // Give the watcher thread the same priority as ours to avoid being
9040     // blocked by it.
9041     ::SetThreadPriority(watcher_thread,
9042                         ::GetThreadPriority(::GetCurrentThread()));
9043     ::ResumeThread(watcher_thread);
9044     ::CloseHandle(watcher_thread);
9045   }
9046 
9047   // Monitors exit from a given thread and notifies those
9048   // ThreadIdToThreadLocals about thread termination.
WatcherThreadFunc(LPVOID param)9049   static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
9050     const ThreadIdAndHandle* tah =
9051         reinterpret_cast<const ThreadIdAndHandle*>(param);
9052     GTEST_CHECK_(
9053         ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
9054     OnThreadExit(tah->first);
9055     ::CloseHandle(tah->second);
9056     delete tah;
9057     return 0;
9058   }
9059 
9060   // Returns map of thread local instances.
GetThreadLocalsMapLocked()9061   static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
9062     mutex_.AssertHeld();
9063     static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;
9064     return map;
9065   }
9066 
9067   // Protects access to GetThreadLocalsMapLocked() and its return value.
9068   static Mutex mutex_;
9069   // Protects access to GetThreadMapLocked() and its return value.
9070   static Mutex thread_map_mutex_;
9071 };
9072 
9073 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
9074 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
9075 
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)9076 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
9077       const ThreadLocalBase* thread_local_instance) {
9078   return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
9079       thread_local_instance);
9080 }
9081 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)9082 void ThreadLocalRegistry::OnThreadLocalDestroyed(
9083       const ThreadLocalBase* thread_local_instance) {
9084   ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
9085 }
9086 
9087 #endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9088 
9089 #if GTEST_USES_POSIX_RE
9090 
9091 // Implements RE.  Currently only needed for death tests.
9092 
~RE()9093 RE::~RE() {
9094   if (is_valid_) {
9095     // regfree'ing an invalid regex might crash because the content
9096     // of the regex is undefined. Since the regex's are essentially
9097     // the same, one cannot be valid (or invalid) without the other
9098     // being so too.
9099     regfree(&partial_regex_);
9100     regfree(&full_regex_);
9101   }
9102   free(const_cast<char*>(pattern_));
9103 }
9104 
9105 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)9106 bool RE::FullMatch(const char* str, const RE& re) {
9107   if (!re.is_valid_) return false;
9108 
9109   regmatch_t match;
9110   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
9111 }
9112 
9113 // Returns true iff regular expression re matches a substring of str
9114 // (including str itself).
PartialMatch(const char * str,const RE & re)9115 bool RE::PartialMatch(const char* str, const RE& re) {
9116   if (!re.is_valid_) return false;
9117 
9118   regmatch_t match;
9119   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
9120 }
9121 
9122 // Initializes an RE from its string representation.
Init(const char * regex)9123 void RE::Init(const char* regex) {
9124   pattern_ = posix::StrDup(regex);
9125 
9126   // Reserves enough bytes to hold the regular expression used for a
9127   // full match.
9128   const size_t full_regex_len = strlen(regex) + 10;
9129   char* const full_pattern = new char[full_regex_len];
9130 
9131   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
9132   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
9133   // We want to call regcomp(&partial_regex_, ...) even if the
9134   // previous expression returns false.  Otherwise partial_regex_ may
9135   // not be properly initialized can may cause trouble when it's
9136   // freed.
9137   //
9138   // Some implementation of POSIX regex (e.g. on at least some
9139   // versions of Cygwin) doesn't accept the empty string as a valid
9140   // regex.  We change it to an equivalent form "()" to be safe.
9141   if (is_valid_) {
9142     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
9143     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
9144   }
9145   EXPECT_TRUE(is_valid_)
9146       << "Regular expression \"" << regex
9147       << "\" is not a valid POSIX Extended regular expression.";
9148 
9149   delete[] full_pattern;
9150 }
9151 
9152 #elif GTEST_USES_SIMPLE_RE
9153 
9154 // Returns true iff ch appears anywhere in str (excluding the
9155 // terminating '\0' character).
IsInSet(char ch,const char * str)9156 bool IsInSet(char ch, const char* str) {
9157   return ch != '\0' && strchr(str, ch) != NULL;
9158 }
9159 
9160 // Returns true iff ch belongs to the given classification.  Unlike
9161 // similar functions in <ctype.h>, these aren't affected by the
9162 // current locale.
IsAsciiDigit(char ch)9163 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)9164 bool IsAsciiPunct(char ch) {
9165   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
9166 }
IsRepeat(char ch)9167 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)9168 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)9169 bool IsAsciiWordChar(char ch) {
9170   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
9171       ('0' <= ch && ch <= '9') || ch == '_';
9172 }
9173 
9174 // Returns true iff "\\c" is a supported escape sequence.
IsValidEscape(char c)9175 bool IsValidEscape(char c) {
9176   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
9177 }
9178 
9179 // Returns true iff the given atom (specified by escaped and pattern)
9180 // matches ch.  The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)9181 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
9182   if (escaped) {  // "\\p" where p is pattern_char.
9183     switch (pattern_char) {
9184       case 'd': return IsAsciiDigit(ch);
9185       case 'D': return !IsAsciiDigit(ch);
9186       case 'f': return ch == '\f';
9187       case 'n': return ch == '\n';
9188       case 'r': return ch == '\r';
9189       case 's': return IsAsciiWhiteSpace(ch);
9190       case 'S': return !IsAsciiWhiteSpace(ch);
9191       case 't': return ch == '\t';
9192       case 'v': return ch == '\v';
9193       case 'w': return IsAsciiWordChar(ch);
9194       case 'W': return !IsAsciiWordChar(ch);
9195     }
9196     return IsAsciiPunct(pattern_char) && pattern_char == ch;
9197   }
9198 
9199   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
9200 }
9201 
9202 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)9203 std::string FormatRegexSyntaxError(const char* regex, int index) {
9204   return (Message() << "Syntax error at index " << index
9205           << " in simple regular expression \"" << regex << "\": ").GetString();
9206 }
9207 
9208 // Generates non-fatal failures and returns false if regex is invalid;
9209 // otherwise returns true.
ValidateRegex(const char * regex)9210 bool ValidateRegex(const char* regex) {
9211   if (regex == NULL) {
9212     // TODO(wan@google.com): fix the source file location in the
9213     // assertion failures to match where the regex is used in user
9214     // code.
9215     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
9216     return false;
9217   }
9218 
9219   bool is_valid = true;
9220 
9221   // True iff ?, *, or + can follow the previous atom.
9222   bool prev_repeatable = false;
9223   for (int i = 0; regex[i]; i++) {
9224     if (regex[i] == '\\') {  // An escape sequence
9225       i++;
9226       if (regex[i] == '\0') {
9227         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9228                       << "'\\' cannot appear at the end.";
9229         return false;
9230       }
9231 
9232       if (!IsValidEscape(regex[i])) {
9233         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9234                       << "invalid escape sequence \"\\" << regex[i] << "\".";
9235         is_valid = false;
9236       }
9237       prev_repeatable = true;
9238     } else {  // Not an escape sequence.
9239       const char ch = regex[i];
9240 
9241       if (ch == '^' && i > 0) {
9242         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9243                       << "'^' can only appear at the beginning.";
9244         is_valid = false;
9245       } else if (ch == '$' && regex[i + 1] != '\0') {
9246         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9247                       << "'$' can only appear at the end.";
9248         is_valid = false;
9249       } else if (IsInSet(ch, "()[]{}|")) {
9250         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9251                       << "'" << ch << "' is unsupported.";
9252         is_valid = false;
9253       } else if (IsRepeat(ch) && !prev_repeatable) {
9254         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9255                       << "'" << ch << "' can only follow a repeatable token.";
9256         is_valid = false;
9257       }
9258 
9259       prev_repeatable = !IsInSet(ch, "^$?*+");
9260     }
9261   }
9262 
9263   return is_valid;
9264 }
9265 
9266 // Matches a repeated regex atom followed by a valid simple regular
9267 // expression.  The regex atom is defined as c if escaped is false,
9268 // or \c otherwise.  repeat is the repetition meta character (?, *,
9269 // or +).  The behavior is undefined if str contains too many
9270 // characters to be indexable by size_t, in which case the test will
9271 // probably time out anyway.  We are fine with this limitation as
9272 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)9273 bool MatchRepetitionAndRegexAtHead(
9274     bool escaped, char c, char repeat, const char* regex,
9275     const char* str) {
9276   const size_t min_count = (repeat == '+') ? 1 : 0;
9277   const size_t max_count = (repeat == '?') ? 1 :
9278       static_cast<size_t>(-1) - 1;
9279   // We cannot call numeric_limits::max() as it conflicts with the
9280   // max() macro on Windows.
9281 
9282   for (size_t i = 0; i <= max_count; ++i) {
9283     // We know that the atom matches each of the first i characters in str.
9284     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
9285       // We have enough matches at the head, and the tail matches too.
9286       // Since we only care about *whether* the pattern matches str
9287       // (as opposed to *how* it matches), there is no need to find a
9288       // greedy match.
9289       return true;
9290     }
9291     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
9292       return false;
9293   }
9294   return false;
9295 }
9296 
9297 // Returns true iff regex matches a prefix of str.  regex must be a
9298 // valid simple regular expression and not start with "^", or the
9299 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)9300 bool MatchRegexAtHead(const char* regex, const char* str) {
9301   if (*regex == '\0')  // An empty regex matches a prefix of anything.
9302     return true;
9303 
9304   // "$" only matches the end of a string.  Note that regex being
9305   // valid guarantees that there's nothing after "$" in it.
9306   if (*regex == '$')
9307     return *str == '\0';
9308 
9309   // Is the first thing in regex an escape sequence?
9310   const bool escaped = *regex == '\\';
9311   if (escaped)
9312     ++regex;
9313   if (IsRepeat(regex[1])) {
9314     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
9315     // here's an indirect recursion.  It terminates as the regex gets
9316     // shorter in each recursion.
9317     return MatchRepetitionAndRegexAtHead(
9318         escaped, regex[0], regex[1], regex + 2, str);
9319   } else {
9320     // regex isn't empty, isn't "$", and doesn't start with a
9321     // repetition.  We match the first atom of regex with the first
9322     // character of str and recurse.
9323     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
9324         MatchRegexAtHead(regex + 1, str + 1);
9325   }
9326 }
9327 
9328 // Returns true iff regex matches any substring of str.  regex must be
9329 // a valid simple regular expression, or the result is undefined.
9330 //
9331 // The algorithm is recursive, but the recursion depth doesn't exceed
9332 // the regex length, so we won't need to worry about running out of
9333 // stack space normally.  In rare cases the time complexity can be
9334 // exponential with respect to the regex length + the string length,
9335 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)9336 bool MatchRegexAnywhere(const char* regex, const char* str) {
9337   if (regex == NULL || str == NULL)
9338     return false;
9339 
9340   if (*regex == '^')
9341     return MatchRegexAtHead(regex + 1, str);
9342 
9343   // A successful match can be anywhere in str.
9344   do {
9345     if (MatchRegexAtHead(regex, str))
9346       return true;
9347   } while (*str++ != '\0');
9348   return false;
9349 }
9350 
9351 // Implements the RE class.
9352 
~RE()9353 RE::~RE() {
9354   free(const_cast<char*>(pattern_));
9355   free(const_cast<char*>(full_pattern_));
9356 }
9357 
9358 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)9359 bool RE::FullMatch(const char* str, const RE& re) {
9360   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
9361 }
9362 
9363 // Returns true iff regular expression re matches a substring of str
9364 // (including str itself).
PartialMatch(const char * str,const RE & re)9365 bool RE::PartialMatch(const char* str, const RE& re) {
9366   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
9367 }
9368 
9369 // Initializes an RE from its string representation.
Init(const char * regex)9370 void RE::Init(const char* regex) {
9371   pattern_ = full_pattern_ = NULL;
9372   if (regex != NULL) {
9373     pattern_ = posix::StrDup(regex);
9374   }
9375 
9376   is_valid_ = ValidateRegex(regex);
9377   if (!is_valid_) {
9378     // No need to calculate the full pattern when the regex is invalid.
9379     return;
9380   }
9381 
9382   const size_t len = strlen(regex);
9383   // Reserves enough bytes to hold the regular expression used for a
9384   // full match: we need space to prepend a '^', append a '$', and
9385   // terminate the string with '\0'.
9386   char* buffer = static_cast<char*>(malloc(len + 3));
9387   full_pattern_ = buffer;
9388 
9389   if (*regex != '^')
9390     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
9391 
9392   // We don't use snprintf or strncpy, as they trigger a warning when
9393   // compiled with VC++ 8.0.
9394   memcpy(buffer, regex, len);
9395   buffer += len;
9396 
9397   if (len == 0 || regex[len - 1] != '$')
9398     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
9399 
9400   *buffer = '\0';
9401 }
9402 
9403 #endif  // GTEST_USES_POSIX_RE
9404 
9405 const char kUnknownFile[] = "unknown file";
9406 
9407 // Formats a source file path and a line number as they would appear
9408 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)9409 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
9410   const std::string file_name(file == NULL ? kUnknownFile : file);
9411 
9412   if (line < 0) {
9413     return file_name + ":";
9414   }
9415 #ifdef _MSC_VER
9416   return file_name + "(" + StreamableToString(line) + "):";
9417 #else
9418   return file_name + ":" + StreamableToString(line) + ":";
9419 #endif  // _MSC_VER
9420 }
9421 
9422 // Formats a file location for compiler-independent XML output.
9423 // Although this function is not platform dependent, we put it next to
9424 // FormatFileLocation in order to contrast the two functions.
9425 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
9426 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)9427 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
9428     const char* file, int line) {
9429   const std::string file_name(file == NULL ? kUnknownFile : file);
9430 
9431   if (line < 0)
9432     return file_name;
9433   else
9434     return file_name + ":" + StreamableToString(line);
9435 }
9436 
GTestLog(GTestLogSeverity severity,const char * file,int line)9437 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
9438     : severity_(severity) {
9439   const char* const marker =
9440       severity == GTEST_INFO ?    "[  INFO ]" :
9441       severity == GTEST_WARNING ? "[WARNING]" :
9442       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
9443   GetStream() << ::std::endl << marker << " "
9444               << FormatFileLocation(file, line).c_str() << ": ";
9445 }
9446 
9447 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()9448 GTestLog::~GTestLog() {
9449   GetStream() << ::std::endl;
9450   if (severity_ == GTEST_FATAL) {
9451     fflush(stderr);
9452     posix::Abort();
9453   }
9454 }
9455 // Disable Microsoft deprecation warnings for POSIX functions called from
9456 // this class (creat, dup, dup2, and close)
9457 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
9458 
9459 #if GTEST_HAS_STREAM_REDIRECTION
9460 
9461 // Object that captures an output stream (stdout/stderr).
9462 class CapturedStream {
9463  public:
9464   // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)9465   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
9466 # if GTEST_OS_WINDOWS
9467     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
9468     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
9469 
9470     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
9471     const UINT success = ::GetTempFileNameA(temp_dir_path,
9472                                             "gtest_redir",
9473                                             0,  // Generate unique file name.
9474                                             temp_file_path);
9475     GTEST_CHECK_(success != 0)
9476         << "Unable to create a temporary file in " << temp_dir_path;
9477     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
9478     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
9479                                     << temp_file_path;
9480     filename_ = temp_file_path;
9481 # else
9482     // There's no guarantee that a test has write access to the current
9483     // directory, so we create the temporary file in the /tmp directory
9484     // instead. We use /tmp on most systems, and /sdcard on Android.
9485     // That's because Android doesn't have /tmp.
9486 #  if GTEST_OS_LINUX_ANDROID
9487     // Note: Android applications are expected to call the framework's
9488     // Context.getExternalStorageDirectory() method through JNI to get
9489     // the location of the world-writable SD Card directory. However,
9490     // this requires a Context handle, which cannot be retrieved
9491     // globally from native code. Doing so also precludes running the
9492     // code as part of a regular standalone executable, which doesn't
9493     // run in a Dalvik process (e.g. when running it through 'adb shell').
9494     //
9495     // The location /sdcard is directly accessible from native code
9496     // and is the only location (unofficially) supported by the Android
9497     // team. It's generally a symlink to the real SD Card mount point
9498     // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
9499     // other OEM-customized locations. Never rely on these, and always
9500     // use /sdcard.
9501     char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
9502 #  else
9503     char name_template[] = "/tmp/captured_stream.XXXXXX";
9504 #  endif  // GTEST_OS_LINUX_ANDROID
9505     const int captured_fd = mkstemp(name_template);
9506     filename_ = name_template;
9507 # endif  // GTEST_OS_WINDOWS
9508     fflush(NULL);
9509     dup2(captured_fd, fd_);
9510     close(captured_fd);
9511   }
9512 
~CapturedStream()9513   ~CapturedStream() {
9514     remove(filename_.c_str());
9515   }
9516 
GetCapturedString()9517   std::string GetCapturedString() {
9518     if (uncaptured_fd_ != -1) {
9519       // Restores the original stream.
9520       fflush(NULL);
9521       dup2(uncaptured_fd_, fd_);
9522       close(uncaptured_fd_);
9523       uncaptured_fd_ = -1;
9524     }
9525 
9526     FILE* const file = posix::FOpen(filename_.c_str(), "r");
9527     const std::string content = ReadEntireFile(file);
9528     posix::FClose(file);
9529     return content;
9530   }
9531 
9532  private:
9533   const int fd_;  // A stream to capture.
9534   int uncaptured_fd_;
9535   // Name of the temporary file holding the stderr output.
9536   ::std::string filename_;
9537 
9538   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
9539 };
9540 
9541 GTEST_DISABLE_MSC_WARNINGS_POP_()
9542 
9543 static CapturedStream* g_captured_stderr = NULL;
9544 static CapturedStream* g_captured_stdout = NULL;
9545 
9546 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)9547 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
9548   if (*stream != NULL) {
9549     GTEST_LOG_(FATAL) << "Only one " << stream_name
9550                       << " capturer can exist at a time.";
9551   }
9552   *stream = new CapturedStream(fd);
9553 }
9554 
9555 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)9556 std::string GetCapturedStream(CapturedStream** captured_stream) {
9557   const std::string content = (*captured_stream)->GetCapturedString();
9558 
9559   delete *captured_stream;
9560   *captured_stream = NULL;
9561 
9562   return content;
9563 }
9564 
9565 // Starts capturing stdout.
CaptureStdout()9566 void CaptureStdout() {
9567   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
9568 }
9569 
9570 // Starts capturing stderr.
CaptureStderr()9571 void CaptureStderr() {
9572   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
9573 }
9574 
9575 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()9576 std::string GetCapturedStdout() {
9577   return GetCapturedStream(&g_captured_stdout);
9578 }
9579 
9580 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()9581 std::string GetCapturedStderr() {
9582   return GetCapturedStream(&g_captured_stderr);
9583 }
9584 
9585 #endif  // GTEST_HAS_STREAM_REDIRECTION
9586 
TempDir()9587 std::string TempDir() {
9588 #if GTEST_OS_WINDOWS_MOBILE
9589   return "\\temp\\";
9590 #elif GTEST_OS_WINDOWS
9591   const char* temp_dir = posix::GetEnv("TEMP");
9592   if (temp_dir == NULL || temp_dir[0] == '\0')
9593     return "\\temp\\";
9594   else if (temp_dir[strlen(temp_dir) - 1] == '\\')
9595     return temp_dir;
9596   else
9597     return std::string(temp_dir) + "\\";
9598 #elif GTEST_OS_LINUX_ANDROID
9599   return "/sdcard/";
9600 #else
9601   return "/tmp/";
9602 #endif  // GTEST_OS_WINDOWS_MOBILE
9603 }
9604 
GetFileSize(FILE * file)9605 size_t GetFileSize(FILE* file) {
9606   fseek(file, 0, SEEK_END);
9607   return static_cast<size_t>(ftell(file));
9608 }
9609 
ReadEntireFile(FILE * file)9610 std::string ReadEntireFile(FILE* file) {
9611   const size_t file_size = GetFileSize(file);
9612   char* const buffer = new char[file_size];
9613 
9614   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
9615   size_t bytes_read = 0;       // # of bytes read so far
9616 
9617   fseek(file, 0, SEEK_SET);
9618 
9619   // Keeps reading the file until we cannot read further or the
9620   // pre-determined file size is reached.
9621   do {
9622     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
9623     bytes_read += bytes_last_read;
9624   } while (bytes_last_read > 0 && bytes_read < file_size);
9625 
9626   const std::string content(buffer, bytes_read);
9627   delete[] buffer;
9628 
9629   return content;
9630 }
9631 
9632 #if GTEST_HAS_DEATH_TEST
9633 
9634 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
9635                                         NULL;  // Owned.
9636 
SetInjectableArgvs(const::std::vector<testing::internal::string> * argvs)9637 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
9638   if (g_injected_test_argvs != argvs)
9639     delete g_injected_test_argvs;
9640   g_injected_test_argvs = argvs;
9641 }
9642 
GetInjectableArgvs()9643 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
9644   if (g_injected_test_argvs != NULL) {
9645     return *g_injected_test_argvs;
9646   }
9647   return GetArgvs();
9648 }
9649 #endif  // GTEST_HAS_DEATH_TEST
9650 
9651 #if GTEST_OS_WINDOWS_MOBILE
9652 namespace posix {
Abort()9653 void Abort() {
9654   DebugBreak();
9655   TerminateProcess(GetCurrentProcess(), 1);
9656 }
9657 }  // namespace posix
9658 #endif  // GTEST_OS_WINDOWS_MOBILE
9659 
9660 // Returns the name of the environment variable corresponding to the
9661 // given flag.  For example, FlagToEnvVar("foo") will return
9662 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)9663 static std::string FlagToEnvVar(const char* flag) {
9664   const std::string full_flag =
9665       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
9666 
9667   Message env_var;
9668   for (size_t i = 0; i != full_flag.length(); i++) {
9669     env_var << ToUpper(full_flag.c_str()[i]);
9670   }
9671 
9672   return env_var.GetString();
9673 }
9674 
9675 // Parses 'str' for a 32-bit signed integer.  If successful, writes
9676 // the result to *value and returns true; otherwise leaves *value
9677 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)9678 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
9679   // Parses the environment variable as a decimal integer.
9680   char* end = NULL;
9681   const long long_value = strtol(str, &end, 10);  // NOLINT
9682 
9683   // Has strtol() consumed all characters in the string?
9684   if (*end != '\0') {
9685     // No - an invalid character was encountered.
9686     Message msg;
9687     msg << "WARNING: " << src_text
9688         << " is expected to be a 32-bit integer, but actually"
9689         << " has value \"" << str << "\".\n";
9690     printf("%s", msg.GetString().c_str());
9691     fflush(stdout);
9692     return false;
9693   }
9694 
9695   // Is the parsed value in the range of an Int32?
9696   const Int32 result = static_cast<Int32>(long_value);
9697   if (long_value == LONG_MAX || long_value == LONG_MIN ||
9698       // The parsed value overflows as a long.  (strtol() returns
9699       // LONG_MAX or LONG_MIN when the input overflows.)
9700       result != long_value
9701       // The parsed value overflows as an Int32.
9702       ) {
9703     Message msg;
9704     msg << "WARNING: " << src_text
9705         << " is expected to be a 32-bit integer, but actually"
9706         << " has value " << str << ", which overflows.\n";
9707     printf("%s", msg.GetString().c_str());
9708     fflush(stdout);
9709     return false;
9710   }
9711 
9712   *value = result;
9713   return true;
9714 }
9715 
9716 // Reads and returns the Boolean environment variable corresponding to
9717 // the given flag; if it's not set, returns default_value.
9718 //
9719 // The value is considered true iff it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)9720 bool BoolFromGTestEnv(const char* flag, bool default_value) {
9721 #if defined(GTEST_GET_BOOL_FROM_ENV_)
9722   return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
9723 #endif  // defined(GTEST_GET_BOOL_FROM_ENV_)
9724   const std::string env_var = FlagToEnvVar(flag);
9725   const char* const string_value = posix::GetEnv(env_var.c_str());
9726   return string_value == NULL ?
9727       default_value : strcmp(string_value, "0") != 0;
9728 }
9729 
9730 // Reads and returns a 32-bit integer stored in the environment
9731 // variable corresponding to the given flag; if it isn't set or
9732 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)9733 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
9734 #if defined(GTEST_GET_INT32_FROM_ENV_)
9735   return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
9736 #endif  // defined(GTEST_GET_INT32_FROM_ENV_)
9737   const std::string env_var = FlagToEnvVar(flag);
9738   const char* const string_value = posix::GetEnv(env_var.c_str());
9739   if (string_value == NULL) {
9740     // The environment variable is not set.
9741     return default_value;
9742   }
9743 
9744   Int32 result = default_value;
9745   if (!ParseInt32(Message() << "Environment variable " << env_var,
9746                   string_value, &result)) {
9747     printf("The default value %s is used.\n",
9748            (Message() << default_value).GetString().c_str());
9749     fflush(stdout);
9750     return default_value;
9751   }
9752 
9753   return result;
9754 }
9755 
9756 // Reads and returns the string environment variable corresponding to
9757 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)9758 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
9759 #if defined(GTEST_GET_STRING_FROM_ENV_)
9760   return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
9761 #endif  // defined(GTEST_GET_STRING_FROM_ENV_)
9762   const std::string env_var = FlagToEnvVar(flag);
9763   const char* const value = posix::GetEnv(env_var.c_str());
9764   return value == NULL ? default_value : value;
9765 }
9766 
9767 }  // namespace internal
9768 }  // namespace testing
9769 // Copyright 2007, Google Inc.
9770 // All rights reserved.
9771 //
9772 // Redistribution and use in source and binary forms, with or without
9773 // modification, are permitted provided that the following conditions are
9774 // met:
9775 //
9776 //     * Redistributions of source code must retain the above copyright
9777 // notice, this list of conditions and the following disclaimer.
9778 //     * Redistributions in binary form must reproduce the above
9779 // copyright notice, this list of conditions and the following disclaimer
9780 // in the documentation and/or other materials provided with the
9781 // distribution.
9782 //     * Neither the name of Google Inc. nor the names of its
9783 // contributors may be used to endorse or promote products derived from
9784 // this software without specific prior written permission.
9785 //
9786 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9787 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9788 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9789 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9790 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9791 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9792 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9793 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9794 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9795 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9796 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9797 //
9798 // Author: wan@google.com (Zhanyong Wan)
9799 
9800 // Google Test - The Google C++ Testing Framework
9801 //
9802 // This file implements a universal value printer that can print a
9803 // value of any type T:
9804 //
9805 //   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
9806 //
9807 // It uses the << operator when possible, and prints the bytes in the
9808 // object otherwise.  A user can override its behavior for a class
9809 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
9810 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
9811 // defines Foo.
9812 
9813 #include <ctype.h>
9814 #include <stdio.h>
9815 #include <cwchar>
9816 #include <ostream>  // NOLINT
9817 #include <string>
9818 
9819 namespace testing {
9820 
9821 namespace {
9822 
9823 using ::std::ostream;
9824 
9825 // Prints a segment of bytes in the given object.
9826 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
9827 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
9828 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintByteSegmentInObjectTo(const unsigned char * obj_bytes,size_t start,size_t count,ostream * os)9829 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
9830                                 size_t count, ostream* os) {
9831   char text[5] = "";
9832   for (size_t i = 0; i != count; i++) {
9833     const size_t j = start + i;
9834     if (i != 0) {
9835       // Organizes the bytes into groups of 2 for easy parsing by
9836       // human.
9837       if ((j % 2) == 0)
9838         *os << ' ';
9839       else
9840         *os << '-';
9841     }
9842     GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
9843     *os << text;
9844   }
9845 }
9846 
9847 // Prints the bytes in the given value to the given ostream.
PrintBytesInObjectToImpl(const unsigned char * obj_bytes,size_t count,ostream * os)9848 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
9849                               ostream* os) {
9850   // Tells the user how big the object is.
9851   *os << count << "-byte object <";
9852 
9853   const size_t kThreshold = 132;
9854   const size_t kChunkSize = 64;
9855   // If the object size is bigger than kThreshold, we'll have to omit
9856   // some details by printing only the first and the last kChunkSize
9857   // bytes.
9858   // TODO(wan): let the user control the threshold using a flag.
9859   if (count < kThreshold) {
9860     PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9861   } else {
9862     PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9863     *os << " ... ";
9864     // Rounds up to 2-byte boundary.
9865     const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9866     PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9867   }
9868   *os << ">";
9869 }
9870 
9871 }  // namespace
9872 
9873 namespace internal2 {
9874 
9875 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9876 // given object.  The delegation simplifies the implementation, which
9877 // uses the << operator and thus is easier done outside of the
9878 // ::testing::internal namespace, which contains a << operator that
9879 // sometimes conflicts with the one in STL.
PrintBytesInObjectTo(const unsigned char * obj_bytes,size_t count,ostream * os)9880 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
9881                           ostream* os) {
9882   PrintBytesInObjectToImpl(obj_bytes, count, os);
9883 }
9884 
9885 }  // namespace internal2
9886 
9887 namespace internal {
9888 
9889 // Depending on the value of a char (or wchar_t), we print it in one
9890 // of three formats:
9891 //   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9892 //   - as a hexidecimal escape sequence (e.g. '\x7F'), or
9893 //   - as a special escape sequence (e.g. '\r', '\n').
9894 enum CharFormat {
9895   kAsIs,
9896   kHexEscape,
9897   kSpecialEscape
9898 };
9899 
9900 // Returns true if c is a printable ASCII character.  We test the
9901 // value of c directly instead of calling isprint(), which is buggy on
9902 // Windows Mobile.
IsPrintableAscii(wchar_t c)9903 inline bool IsPrintableAscii(wchar_t c) {
9904   return 0x20 <= c && c <= 0x7E;
9905 }
9906 
9907 // Prints a wide or narrow char c as a character literal without the
9908 // quotes, escaping it when necessary; returns how c was formatted.
9909 // The template argument UnsignedChar is the unsigned version of Char,
9910 // which is the type of c.
9911 template <typename UnsignedChar, typename Char>
PrintAsCharLiteralTo(Char c,ostream * os)9912 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
9913   switch (static_cast<wchar_t>(c)) {
9914     case L'\0':
9915       *os << "\\0";
9916       break;
9917     case L'\'':
9918       *os << "\\'";
9919       break;
9920     case L'\\':
9921       *os << "\\\\";
9922       break;
9923     case L'\a':
9924       *os << "\\a";
9925       break;
9926     case L'\b':
9927       *os << "\\b";
9928       break;
9929     case L'\f':
9930       *os << "\\f";
9931       break;
9932     case L'\n':
9933       *os << "\\n";
9934       break;
9935     case L'\r':
9936       *os << "\\r";
9937       break;
9938     case L'\t':
9939       *os << "\\t";
9940       break;
9941     case L'\v':
9942       *os << "\\v";
9943       break;
9944     default:
9945       if (IsPrintableAscii(c)) {
9946         *os << static_cast<char>(c);
9947         return kAsIs;
9948       } else {
9949         *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9950         return kHexEscape;
9951       }
9952   }
9953   return kSpecialEscape;
9954 }
9955 
9956 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9957 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(wchar_t c,ostream * os)9958 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
9959   switch (c) {
9960     case L'\'':
9961       *os << "'";
9962       return kAsIs;
9963     case L'"':
9964       *os << "\\\"";
9965       return kSpecialEscape;
9966     default:
9967       return PrintAsCharLiteralTo<wchar_t>(c, os);
9968   }
9969 }
9970 
9971 // Prints a char c as if it's part of a string literal, escaping it when
9972 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char c,ostream * os)9973 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
9974   return PrintAsStringLiteralTo(
9975       static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
9976 }
9977 
9978 // Prints a wide or narrow character c and its code.  '\0' is printed
9979 // as "'\\0'", other unprintable characters are also properly escaped
9980 // using the standard C++ escape sequence.  The template argument
9981 // UnsignedChar is the unsigned version of Char, which is the type of c.
9982 template <typename UnsignedChar, typename Char>
PrintCharAndCodeTo(Char c,ostream * os)9983 void PrintCharAndCodeTo(Char c, ostream* os) {
9984   // First, print c as a literal in the most readable form we can find.
9985   *os << ((sizeof(c) > 1) ? "L'" : "'");
9986   const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9987   *os << "'";
9988 
9989   // To aid user debugging, we also print c's code in decimal, unless
9990   // it's 0 (in which case c was printed as '\\0', making the code
9991   // obvious).
9992   if (c == 0)
9993     return;
9994   *os << " (" << static_cast<int>(c);
9995 
9996   // For more convenience, we print c's code again in hexidecimal,
9997   // unless c was already printed in the form '\x##' or the code is in
9998   // [1, 9].
9999   if (format == kHexEscape || (1 <= c && c <= 9)) {
10000     // Do nothing.
10001   } else {
10002     *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
10003   }
10004   *os << ")";
10005 }
10006 
PrintTo(unsigned char c,::std::ostream * os)10007 void PrintTo(unsigned char c, ::std::ostream* os) {
10008   PrintCharAndCodeTo<unsigned char>(c, os);
10009 }
PrintTo(signed char c,::std::ostream * os)10010 void PrintTo(signed char c, ::std::ostream* os) {
10011   PrintCharAndCodeTo<unsigned char>(c, os);
10012 }
10013 
10014 // Prints a wchar_t as a symbol if it is printable or as its internal
10015 // code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
PrintTo(wchar_t wc,ostream * os)10016 void PrintTo(wchar_t wc, ostream* os) {
10017   PrintCharAndCodeTo<wchar_t>(wc, os);
10018 }
10019 
10020 // Prints the given array of characters to the ostream.  CharType must be either
10021 // char or wchar_t.
10022 // The array starts at begin, the length is len, it may include '\0' characters
10023 // and may not be NUL-terminated.
10024 template <typename CharType>
10025 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10026 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10027 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
PrintCharsAsStringTo(const CharType * begin,size_t len,ostream * os)10028 static void PrintCharsAsStringTo(
10029     const CharType* begin, size_t len, ostream* os) {
10030   const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
10031   *os << kQuoteBegin;
10032   bool is_previous_hex = false;
10033   for (size_t index = 0; index < len; ++index) {
10034     const CharType cur = begin[index];
10035     if (is_previous_hex && IsXDigit(cur)) {
10036       // Previous character is of '\x..' form and this character can be
10037       // interpreted as another hexadecimal digit in its number. Break string to
10038       // disambiguate.
10039       *os << "\" " << kQuoteBegin;
10040     }
10041     is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
10042   }
10043   *os << "\"";
10044 }
10045 
10046 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
10047 // 'begin'.  CharType must be either char or wchar_t.
10048 template <typename CharType>
10049 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10050 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10051 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
UniversalPrintCharArray(const CharType * begin,size_t len,ostream * os)10052 static void UniversalPrintCharArray(
10053     const CharType* begin, size_t len, ostream* os) {
10054   // The code
10055   //   const char kFoo[] = "foo";
10056   // generates an array of 4, not 3, elements, with the last one being '\0'.
10057   //
10058   // Therefore when printing a char array, we don't print the last element if
10059   // it's '\0', such that the output matches the string literal as it's
10060   // written in the source code.
10061   if (len > 0 && begin[len - 1] == '\0') {
10062     PrintCharsAsStringTo(begin, len - 1, os);
10063     return;
10064   }
10065 
10066   // If, however, the last element in the array is not '\0', e.g.
10067   //    const char kFoo[] = { 'f', 'o', 'o' };
10068   // we must print the entire array.  We also print a message to indicate
10069   // that the array is not NUL-terminated.
10070   PrintCharsAsStringTo(begin, len, os);
10071   *os << " (no terminating NUL)";
10072 }
10073 
10074 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
UniversalPrintArray(const char * begin,size_t len,ostream * os)10075 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
10076   UniversalPrintCharArray(begin, len, os);
10077 }
10078 
10079 // Prints a (const) wchar_t array of 'len' elements, starting at address
10080 // 'begin'.
UniversalPrintArray(const wchar_t * begin,size_t len,ostream * os)10081 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
10082   UniversalPrintCharArray(begin, len, os);
10083 }
10084 
10085 // Prints the given C string to the ostream.
PrintTo(const char * s,ostream * os)10086 void PrintTo(const char* s, ostream* os) {
10087   if (s == NULL) {
10088     *os << "NULL";
10089   } else {
10090     *os << ImplicitCast_<const void*>(s) << " pointing to ";
10091     PrintCharsAsStringTo(s, strlen(s), os);
10092   }
10093 }
10094 
10095 // MSVC compiler can be configured to define whar_t as a typedef
10096 // of unsigned short. Defining an overload for const wchar_t* in that case
10097 // would cause pointers to unsigned shorts be printed as wide strings,
10098 // possibly accessing more memory than intended and causing invalid
10099 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
10100 // wchar_t is implemented as a native type.
10101 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
10102 // Prints the given wide C string to the ostream.
PrintTo(const wchar_t * s,ostream * os)10103 void PrintTo(const wchar_t* s, ostream* os) {
10104   if (s == NULL) {
10105     *os << "NULL";
10106   } else {
10107     *os << ImplicitCast_<const void*>(s) << " pointing to ";
10108     PrintCharsAsStringTo(s, std::wcslen(s), os);
10109   }
10110 }
10111 #endif  // wchar_t is native
10112 
10113 // Prints a ::string object.
10114 #if GTEST_HAS_GLOBAL_STRING
PrintStringTo(const::string & s,ostream * os)10115 void PrintStringTo(const ::string& s, ostream* os) {
10116   PrintCharsAsStringTo(s.data(), s.size(), os);
10117 }
10118 #endif  // GTEST_HAS_GLOBAL_STRING
10119 
PrintStringTo(const::std::string & s,ostream * os)10120 void PrintStringTo(const ::std::string& s, ostream* os) {
10121   PrintCharsAsStringTo(s.data(), s.size(), os);
10122 }
10123 
10124 // Prints a ::wstring object.
10125 #if GTEST_HAS_GLOBAL_WSTRING
PrintWideStringTo(const::wstring & s,ostream * os)10126 void PrintWideStringTo(const ::wstring& s, ostream* os) {
10127   PrintCharsAsStringTo(s.data(), s.size(), os);
10128 }
10129 #endif  // GTEST_HAS_GLOBAL_WSTRING
10130 
10131 #if GTEST_HAS_STD_WSTRING
PrintWideStringTo(const::std::wstring & s,ostream * os)10132 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
10133   PrintCharsAsStringTo(s.data(), s.size(), os);
10134 }
10135 #endif  // GTEST_HAS_STD_WSTRING
10136 
10137 }  // namespace internal
10138 
10139 }  // namespace testing
10140 // Copyright 2008, Google Inc.
10141 // All rights reserved.
10142 //
10143 // Redistribution and use in source and binary forms, with or without
10144 // modification, are permitted provided that the following conditions are
10145 // met:
10146 //
10147 //     * Redistributions of source code must retain the above copyright
10148 // notice, this list of conditions and the following disclaimer.
10149 //     * Redistributions in binary form must reproduce the above
10150 // copyright notice, this list of conditions and the following disclaimer
10151 // in the documentation and/or other materials provided with the
10152 // distribution.
10153 //     * Neither the name of Google Inc. nor the names of its
10154 // contributors may be used to endorse or promote products derived from
10155 // this software without specific prior written permission.
10156 //
10157 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10158 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10159 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10160 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10161 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10162 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10163 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10164 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10165 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10166 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10167 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10168 //
10169 // Author: mheule@google.com (Markus Heule)
10170 //
10171 // The Google C++ Testing Framework (Google Test)
10172 
10173 
10174 // Indicates that this translation unit is part of Google Test's
10175 // implementation.  It must come before gtest-internal-inl.h is
10176 // included, or there will be a compiler error.  This trick exists to
10177 // prevent the accidental inclusion of gtest-internal-inl.h in the
10178 // user's code.
10179 #define GTEST_IMPLEMENTATION_ 1
10180 #undef GTEST_IMPLEMENTATION_
10181 
10182 namespace testing {
10183 
10184 using internal::GetUnitTestImpl;
10185 
10186 // Gets the summary of the failure message by omitting the stack trace
10187 // in it.
ExtractSummary(const char * message)10188 std::string TestPartResult::ExtractSummary(const char* message) {
10189   const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
10190   return stack_trace == NULL ? message :
10191       std::string(message, stack_trace);
10192 }
10193 
10194 // Prints a TestPartResult object.
operator <<(std::ostream & os,const TestPartResult & result)10195 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
10196   return os
10197       << result.file_name() << ":" << result.line_number() << ": "
10198       << (result.type() == TestPartResult::kSuccess ? "Success" :
10199           result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
10200           "Non-fatal failure") << ":\n"
10201       << result.message() << std::endl;
10202 }
10203 
10204 // Appends a TestPartResult to the array.
Append(const TestPartResult & result)10205 void TestPartResultArray::Append(const TestPartResult& result) {
10206   array_.push_back(result);
10207 }
10208 
10209 // Returns the TestPartResult at the given index (0-based).
GetTestPartResult(int index) const10210 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
10211   if (index < 0 || index >= size()) {
10212     printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
10213     internal::posix::Abort();
10214   }
10215 
10216   return array_[index];
10217 }
10218 
10219 // Returns the number of TestPartResult objects in the array.
size() const10220 int TestPartResultArray::size() const {
10221   return static_cast<int>(array_.size());
10222 }
10223 
10224 namespace internal {
10225 
HasNewFatalFailureHelper()10226 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
10227     : has_new_fatal_failure_(false),
10228       original_reporter_(GetUnitTestImpl()->
10229                          GetTestPartResultReporterForCurrentThread()) {
10230   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
10231 }
10232 
~HasNewFatalFailureHelper()10233 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
10234   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
10235       original_reporter_);
10236 }
10237 
ReportTestPartResult(const TestPartResult & result)10238 void HasNewFatalFailureHelper::ReportTestPartResult(
10239     const TestPartResult& result) {
10240   if (result.fatally_failed())
10241     has_new_fatal_failure_ = true;
10242   original_reporter_->ReportTestPartResult(result);
10243 }
10244 
10245 }  // namespace internal
10246 
10247 }  // namespace testing
10248 // Copyright 2008 Google Inc.
10249 // All Rights Reserved.
10250 //
10251 // Redistribution and use in source and binary forms, with or without
10252 // modification, are permitted provided that the following conditions are
10253 // met:
10254 //
10255 //     * Redistributions of source code must retain the above copyright
10256 // notice, this list of conditions and the following disclaimer.
10257 //     * Redistributions in binary form must reproduce the above
10258 // copyright notice, this list of conditions and the following disclaimer
10259 // in the documentation and/or other materials provided with the
10260 // distribution.
10261 //     * Neither the name of Google Inc. nor the names of its
10262 // contributors may be used to endorse or promote products derived from
10263 // this software without specific prior written permission.
10264 //
10265 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10266 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10267 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10268 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10269 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10270 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10271 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10272 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10273 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10274 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10275 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10276 //
10277 // Author: wan@google.com (Zhanyong Wan)
10278 
10279 
10280 namespace testing {
10281 namespace internal {
10282 
10283 #if GTEST_HAS_TYPED_TEST_P
10284 
10285 // Skips to the first non-space char in str. Returns an empty string if str
10286 // contains only whitespace characters.
SkipSpaces(const char * str)10287 static const char* SkipSpaces(const char* str) {
10288   while (IsSpace(*str))
10289     str++;
10290   return str;
10291 }
10292 
SplitIntoTestNames(const char * src)10293 static std::vector<std::string> SplitIntoTestNames(const char* src) {
10294   std::vector<std::string> name_vec;
10295   src = SkipSpaces(src);
10296   for (; src != NULL; src = SkipComma(src)) {
10297     name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
10298   }
10299   return name_vec;
10300 }
10301 
10302 // Verifies that registered_tests match the test names in
10303 // registered_tests_; returns registered_tests if successful, or
10304 // aborts the program otherwise.
VerifyRegisteredTestNames(const char * file,int line,const char * registered_tests)10305 const char* TypedTestCasePState::VerifyRegisteredTestNames(
10306     const char* file, int line, const char* registered_tests) {
10307   typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
10308   registered_ = true;
10309 
10310   std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
10311 
10312   Message errors;
10313 
10314   std::set<std::string> tests;
10315   for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
10316        name_it != name_vec.end(); ++name_it) {
10317     const std::string& name = *name_it;
10318     if (tests.count(name) != 0) {
10319       errors << "Test " << name << " is listed more than once.\n";
10320       continue;
10321     }
10322 
10323     bool found = false;
10324     for (RegisteredTestIter it = registered_tests_.begin();
10325          it != registered_tests_.end();
10326          ++it) {
10327       if (name == it->first) {
10328         found = true;
10329         break;
10330       }
10331     }
10332 
10333     if (found) {
10334       tests.insert(name);
10335     } else {
10336       errors << "No test named " << name
10337              << " can be found in this test case.\n";
10338     }
10339   }
10340 
10341   for (RegisteredTestIter it = registered_tests_.begin();
10342        it != registered_tests_.end();
10343        ++it) {
10344     if (tests.count(it->first) == 0) {
10345       errors << "You forgot to list test " << it->first << ".\n";
10346     }
10347   }
10348 
10349   const std::string& errors_str = errors.GetString();
10350   if (errors_str != "") {
10351     fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
10352             errors_str.c_str());
10353     fflush(stderr);
10354     posix::Abort();
10355   }
10356 
10357   return registered_tests;
10358 }
10359 
10360 #endif  // GTEST_HAS_TYPED_TEST_P
10361 
10362 }  // namespace internal
10363 }  // namespace testing
10364 // Copyright 2008, Google Inc.
10365 // All rights reserved.
10366 //
10367 // Redistribution and use in source and binary forms, with or without
10368 // modification, are permitted provided that the following conditions are
10369 // met:
10370 //
10371 //     * Redistributions of source code must retain the above copyright
10372 // notice, this list of conditions and the following disclaimer.
10373 //     * Redistributions in binary form must reproduce the above
10374 // copyright notice, this list of conditions and the following disclaimer
10375 // in the documentation and/or other materials provided with the
10376 // distribution.
10377 //     * Neither the name of Google Inc. nor the names of its
10378 // contributors may be used to endorse or promote products derived from
10379 // this software without specific prior written permission.
10380 //
10381 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10382 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10383 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10384 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10385 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10386 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10387 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10388 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10389 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10390 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10391 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10392 //
10393 // Author: wan@google.com (Zhanyong Wan)
10394 //
10395 // Google C++ Mocking Framework (Google Mock)
10396 //
10397 // This file #includes all Google Mock implementation .cc files.  The
10398 // purpose is to allow a user to build Google Mock by compiling this
10399 // file alone.
10400 
10401 // This line ensures that gmock.h can be compiled on its own, even
10402 // when it's fused.
10403 #include "gmock/gmock.h"
10404 
10405 // The following lines pull in the real gmock *.cc files.
10406 // Copyright 2007, Google Inc.
10407 // All rights reserved.
10408 //
10409 // Redistribution and use in source and binary forms, with or without
10410 // modification, are permitted provided that the following conditions are
10411 // met:
10412 //
10413 //     * Redistributions of source code must retain the above copyright
10414 // notice, this list of conditions and the following disclaimer.
10415 //     * Redistributions in binary form must reproduce the above
10416 // copyright notice, this list of conditions and the following disclaimer
10417 // in the documentation and/or other materials provided with the
10418 // distribution.
10419 //     * Neither the name of Google Inc. nor the names of its
10420 // contributors may be used to endorse or promote products derived from
10421 // this software without specific prior written permission.
10422 //
10423 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10424 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10425 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10426 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10427 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10428 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10429 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10430 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10431 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10432 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10433 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10434 //
10435 // Author: wan@google.com (Zhanyong Wan)
10436 
10437 // Google Mock - a framework for writing C++ mock classes.
10438 //
10439 // This file implements cardinalities.
10440 
10441 
10442 #include <limits.h>
10443 #include <ostream>  // NOLINT
10444 #include <sstream>
10445 #include <string>
10446 
10447 namespace testing {
10448 
10449 namespace {
10450 
10451 // Implements the Between(m, n) cardinality.
10452 class BetweenCardinalityImpl : public CardinalityInterface {
10453  public:
BetweenCardinalityImpl(int min,int max)10454   BetweenCardinalityImpl(int min, int max)
10455       : min_(min >= 0 ? min : 0),
10456         max_(max >= min_ ? max : min_) {
10457     std::stringstream ss;
10458     if (min < 0) {
10459       ss << "The invocation lower bound must be >= 0, "
10460          << "but is actually " << min << ".";
10461       internal::Expect(false, __FILE__, __LINE__, ss.str());
10462     } else if (max < 0) {
10463       ss << "The invocation upper bound must be >= 0, "
10464          << "but is actually " << max << ".";
10465       internal::Expect(false, __FILE__, __LINE__, ss.str());
10466     } else if (min > max) {
10467       ss << "The invocation upper bound (" << max
10468          << ") must be >= the invocation lower bound (" << min
10469          << ").";
10470       internal::Expect(false, __FILE__, __LINE__, ss.str());
10471     }
10472   }
10473 
10474   // Conservative estimate on the lower/upper bound of the number of
10475   // calls allowed.
ConservativeLowerBound() const10476   virtual int ConservativeLowerBound() const { return min_; }
ConservativeUpperBound() const10477   virtual int ConservativeUpperBound() const { return max_; }
10478 
IsSatisfiedByCallCount(int call_count) const10479   virtual bool IsSatisfiedByCallCount(int call_count) const {
10480     return min_ <= call_count && call_count <= max_;
10481   }
10482 
IsSaturatedByCallCount(int call_count) const10483   virtual bool IsSaturatedByCallCount(int call_count) const {
10484     return call_count >= max_;
10485   }
10486 
10487   virtual void DescribeTo(::std::ostream* os) const;
10488 
10489  private:
10490   const int min_;
10491   const int max_;
10492 
10493   GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
10494 };
10495 
10496 // Formats "n times" in a human-friendly way.
FormatTimes(int n)10497 inline internal::string FormatTimes(int n) {
10498   if (n == 1) {
10499     return "once";
10500   } else if (n == 2) {
10501     return "twice";
10502   } else {
10503     std::stringstream ss;
10504     ss << n << " times";
10505     return ss.str();
10506   }
10507 }
10508 
10509 // Describes the Between(m, n) cardinality in human-friendly text.
DescribeTo(::std::ostream * os) const10510 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
10511   if (min_ == 0) {
10512     if (max_ == 0) {
10513       *os << "never called";
10514     } else if (max_ == INT_MAX) {
10515       *os << "called any number of times";
10516     } else {
10517       *os << "called at most " << FormatTimes(max_);
10518     }
10519   } else if (min_ == max_) {
10520     *os << "called " << FormatTimes(min_);
10521   } else if (max_ == INT_MAX) {
10522     *os << "called at least " << FormatTimes(min_);
10523   } else {
10524     // 0 < min_ < max_ < INT_MAX
10525     *os << "called between " << min_ << " and " << max_ << " times";
10526   }
10527 }
10528 
10529 }  // Unnamed namespace
10530 
10531 // Describes the given call count to an ostream.
DescribeActualCallCountTo(int actual_call_count,::std::ostream * os)10532 void Cardinality::DescribeActualCallCountTo(int actual_call_count,
10533                                             ::std::ostream* os) {
10534   if (actual_call_count > 0) {
10535     *os << "called " << FormatTimes(actual_call_count);
10536   } else {
10537     *os << "never called";
10538   }
10539 }
10540 
10541 // Creates a cardinality that allows at least n calls.
AtLeast(int n)10542 GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
10543 
10544 // Creates a cardinality that allows at most n calls.
AtMost(int n)10545 GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
10546 
10547 // Creates a cardinality that allows any number of calls.
AnyNumber()10548 GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
10549 
10550 // Creates a cardinality that allows between min and max calls.
Between(int min,int max)10551 GTEST_API_ Cardinality Between(int min, int max) {
10552   return Cardinality(new BetweenCardinalityImpl(min, max));
10553 }
10554 
10555 // Creates a cardinality that allows exactly n calls.
Exactly(int n)10556 GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
10557 
10558 }  // namespace testing
10559 // Copyright 2007, Google Inc.
10560 // All rights reserved.
10561 //
10562 // Redistribution and use in source and binary forms, with or without
10563 // modification, are permitted provided that the following conditions are
10564 // met:
10565 //
10566 //     * Redistributions of source code must retain the above copyright
10567 // notice, this list of conditions and the following disclaimer.
10568 //     * Redistributions in binary form must reproduce the above
10569 // copyright notice, this list of conditions and the following disclaimer
10570 // in the documentation and/or other materials provided with the
10571 // distribution.
10572 //     * Neither the name of Google Inc. nor the names of its
10573 // contributors may be used to endorse or promote products derived from
10574 // this software without specific prior written permission.
10575 //
10576 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10577 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10578 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10579 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10580 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10581 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10582 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10583 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10584 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10585 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10586 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10587 //
10588 // Author: wan@google.com (Zhanyong Wan)
10589 
10590 // Google Mock - a framework for writing C++ mock classes.
10591 //
10592 // This file defines some utilities useful for implementing Google
10593 // Mock.  They are subject to change without notice, so please DO NOT
10594 // USE THEM IN USER CODE.
10595 
10596 
10597 #include <ctype.h>
10598 #include <ostream>  // NOLINT
10599 #include <string>
10600 
10601 namespace testing {
10602 namespace internal {
10603 
10604 // Converts an identifier name to a space-separated list of lower-case
10605 // words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
10606 // treated as one word.  For example, both "FooBar123" and
10607 // "foo_bar_123" are converted to "foo bar 123".
ConvertIdentifierNameToWords(const char * id_name)10608 GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
10609   string result;
10610   char prev_char = '\0';
10611   for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
10612     // We don't care about the current locale as the input is
10613     // guaranteed to be a valid C++ identifier name.
10614     const bool starts_new_word = IsUpper(*p) ||
10615         (!IsAlpha(prev_char) && IsLower(*p)) ||
10616         (!IsDigit(prev_char) && IsDigit(*p));
10617 
10618     if (IsAlNum(*p)) {
10619       if (starts_new_word && result != "")
10620         result += ' ';
10621       result += ToLower(*p);
10622     }
10623   }
10624   return result;
10625 }
10626 
10627 // This class reports Google Mock failures as Google Test failures.  A
10628 // user can define another class in a similar fashion if he intends to
10629 // use Google Mock with a testing framework other than Google Test.
10630 class GoogleTestFailureReporter : public FailureReporterInterface {
10631  public:
ReportFailure(FailureType type,const char * file,int line,const string & message)10632   virtual void ReportFailure(FailureType type, const char* file, int line,
10633                              const string& message) {
10634     AssertHelper(type == kFatal ?
10635                  TestPartResult::kFatalFailure :
10636                  TestPartResult::kNonFatalFailure,
10637                  file,
10638                  line,
10639                  message.c_str()) = Message();
10640     if (type == kFatal) {
10641       posix::Abort();
10642     }
10643   }
10644 };
10645 
10646 // Returns the global failure reporter.  Will create a
10647 // GoogleTestFailureReporter and return it the first time called.
GetFailureReporter()10648 GTEST_API_ FailureReporterInterface* GetFailureReporter() {
10649   // Points to the global failure reporter used by Google Mock.  gcc
10650   // guarantees that the following use of failure_reporter is
10651   // thread-safe.  We may need to add additional synchronization to
10652   // protect failure_reporter if we port Google Mock to other
10653   // compilers.
10654   static FailureReporterInterface* const failure_reporter =
10655       new GoogleTestFailureReporter();
10656   return failure_reporter;
10657 }
10658 
10659 // Protects global resources (stdout in particular) used by Log().
10660 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
10661 
10662 // Returns true iff a log with the given severity is visible according
10663 // to the --gmock_verbose flag.
LogIsVisible(LogSeverity severity)10664 GTEST_API_ bool LogIsVisible(LogSeverity severity) {
10665   if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
10666     // Always show the log if --gmock_verbose=info.
10667     return true;
10668   } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
10669     // Always hide it if --gmock_verbose=error.
10670     return false;
10671   } else {
10672     // If --gmock_verbose is neither "info" nor "error", we treat it
10673     // as "warning" (its default value).
10674     return severity == kWarning;
10675   }
10676 }
10677 
10678 // Prints the given message to stdout iff 'severity' >= the level
10679 // specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
10680 // 0, also prints the stack trace excluding the top
10681 // stack_frames_to_skip frames.  In opt mode, any positive
10682 // stack_frames_to_skip is treated as 0, since we don't know which
10683 // function calls will be inlined by the compiler and need to be
10684 // conservative.
Log(LogSeverity severity,const string & message,int stack_frames_to_skip)10685 GTEST_API_ void Log(LogSeverity severity,
10686                     const string& message,
10687                     int stack_frames_to_skip) {
10688   if (!LogIsVisible(severity))
10689     return;
10690 
10691   // Ensures that logs from different threads don't interleave.
10692   MutexLock l(&g_log_mutex);
10693 
10694   // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
10695   // macro.
10696 
10697   if (severity == kWarning) {
10698     // Prints a GMOCK WARNING marker to make the warnings easily searchable.
10699     std::cout << "\nGMOCK WARNING:";
10700   }
10701   // Pre-pends a new-line to message if it doesn't start with one.
10702   if (message.empty() || message[0] != '\n') {
10703     std::cout << "\n";
10704   }
10705   std::cout << message;
10706   if (stack_frames_to_skip >= 0) {
10707 #ifdef NDEBUG
10708     // In opt mode, we have to be conservative and skip no stack frame.
10709     const int actual_to_skip = 0;
10710 #else
10711     // In dbg mode, we can do what the caller tell us to do (plus one
10712     // for skipping this function's stack frame).
10713     const int actual_to_skip = stack_frames_to_skip + 1;
10714 #endif  // NDEBUG
10715 
10716     // Appends a new-line to message if it doesn't end with one.
10717     if (!message.empty() && *message.rbegin() != '\n') {
10718       std::cout << "\n";
10719     }
10720     std::cout << "Stack trace:\n"
10721          << ::testing::internal::GetCurrentOsStackTraceExceptTop(
10722              ::testing::UnitTest::GetInstance(), actual_to_skip);
10723   }
10724   std::cout << ::std::flush;
10725 }
10726 
10727 }  // namespace internal
10728 }  // namespace testing
10729 // Copyright 2007, Google Inc.
10730 // All rights reserved.
10731 //
10732 // Redistribution and use in source and binary forms, with or without
10733 // modification, are permitted provided that the following conditions are
10734 // met:
10735 //
10736 //     * Redistributions of source code must retain the above copyright
10737 // notice, this list of conditions and the following disclaimer.
10738 //     * Redistributions in binary form must reproduce the above
10739 // copyright notice, this list of conditions and the following disclaimer
10740 // in the documentation and/or other materials provided with the
10741 // distribution.
10742 //     * Neither the name of Google Inc. nor the names of its
10743 // contributors may be used to endorse or promote products derived from
10744 // this software without specific prior written permission.
10745 //
10746 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10747 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10748 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10749 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10750 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10751 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10752 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10753 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10754 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10755 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10756 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10757 //
10758 // Author: wan@google.com (Zhanyong Wan)
10759 
10760 // Google Mock - a framework for writing C++ mock classes.
10761 //
10762 // This file implements Matcher<const string&>, Matcher<string>, and
10763 // utilities for defining matchers.
10764 
10765 
10766 #include <string.h>
10767 #include <sstream>
10768 #include <string>
10769 
10770 namespace testing {
10771 
10772 // Constructs a matcher that matches a const string& whose value is
10773 // equal to s.
Matcher(const internal::string & s)10774 Matcher<const internal::string&>::Matcher(const internal::string& s) {
10775   *this = Eq(s);
10776 }
10777 
10778 // Constructs a matcher that matches a const string& whose value is
10779 // equal to s.
Matcher(const char * s)10780 Matcher<const internal::string&>::Matcher(const char* s) {
10781   *this = Eq(internal::string(s));
10782 }
10783 
10784 // Constructs a matcher that matches a string whose value is equal to s.
Matcher(const internal::string & s)10785 Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
10786 
10787 // Constructs a matcher that matches a string whose value is equal to s.
Matcher(const char * s)10788 Matcher<internal::string>::Matcher(const char* s) {
10789   *this = Eq(internal::string(s));
10790 }
10791 
10792 #if GTEST_HAS_STRING_PIECE_
10793 // Constructs a matcher that matches a const StringPiece& whose value is
10794 // equal to s.
Matcher(const internal::string & s)10795 Matcher<const StringPiece&>::Matcher(const internal::string& s) {
10796   *this = Eq(s);
10797 }
10798 
10799 // Constructs a matcher that matches a const StringPiece& whose value is
10800 // equal to s.
Matcher(const char * s)10801 Matcher<const StringPiece&>::Matcher(const char* s) {
10802   *this = Eq(internal::string(s));
10803 }
10804 
10805 // Constructs a matcher that matches a const StringPiece& whose value is
10806 // equal to s.
Matcher(StringPiece s)10807 Matcher<const StringPiece&>::Matcher(StringPiece s) {
10808   *this = Eq(s.ToString());
10809 }
10810 
10811 // Constructs a matcher that matches a StringPiece whose value is equal to s.
Matcher(const internal::string & s)10812 Matcher<StringPiece>::Matcher(const internal::string& s) {
10813   *this = Eq(s);
10814 }
10815 
10816 // Constructs a matcher that matches a StringPiece whose value is equal to s.
Matcher(const char * s)10817 Matcher<StringPiece>::Matcher(const char* s) {
10818   *this = Eq(internal::string(s));
10819 }
10820 
10821 // Constructs a matcher that matches a StringPiece whose value is equal to s.
Matcher(StringPiece s)10822 Matcher<StringPiece>::Matcher(StringPiece s) {
10823   *this = Eq(s.ToString());
10824 }
10825 #endif  // GTEST_HAS_STRING_PIECE_
10826 
10827 namespace internal {
10828 
10829 // Joins a vector of strings as if they are fields of a tuple; returns
10830 // the joined string.
JoinAsTuple(const Strings & fields)10831 GTEST_API_ string JoinAsTuple(const Strings& fields) {
10832   switch (fields.size()) {
10833     case 0:
10834       return "";
10835     case 1:
10836       return fields[0];
10837     default:
10838       string result = "(" + fields[0];
10839       for (size_t i = 1; i < fields.size(); i++) {
10840         result += ", ";
10841         result += fields[i];
10842       }
10843       result += ")";
10844       return result;
10845   }
10846 }
10847 
10848 // Returns the description for a matcher defined using the MATCHER*()
10849 // macro where the user-supplied description string is "", if
10850 // 'negation' is false; otherwise returns the description of the
10851 // negation of the matcher.  'param_values' contains a list of strings
10852 // that are the print-out of the matcher's parameters.
FormatMatcherDescription(bool negation,const char * matcher_name,const Strings & param_values)10853 GTEST_API_ string FormatMatcherDescription(bool negation,
10854                                            const char* matcher_name,
10855                                            const Strings& param_values) {
10856   string result = ConvertIdentifierNameToWords(matcher_name);
10857   if (param_values.size() >= 1)
10858     result += " " + JoinAsTuple(param_values);
10859   return negation ? "not (" + result + ")" : result;
10860 }
10861 
10862 // FindMaxBipartiteMatching and its helper class.
10863 //
10864 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
10865 // bipartite matching. Flow is considered to be from left to right.
10866 // There is an implicit source node that is connected to all of the left
10867 // nodes, and an implicit sink node that is connected to all of the
10868 // right nodes. All edges have unit capacity.
10869 //
10870 // Neither the flow graph nor the residual flow graph are represented
10871 // explicitly. Instead, they are implied by the information in 'graph' and
10872 // a vector<int> called 'left_' whose elements are initialized to the
10873 // value kUnused. This represents the initial state of the algorithm,
10874 // where the flow graph is empty, and the residual flow graph has the
10875 // following edges:
10876 //   - An edge from source to each left_ node
10877 //   - An edge from each right_ node to sink
10878 //   - An edge from each left_ node to each right_ node, if the
10879 //     corresponding edge exists in 'graph'.
10880 //
10881 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
10882 // nodes l and r. This induces the following changes:
10883 //   - The edges (source, l), (l, r), and (r, sink) are added to the
10884 //     flow graph.
10885 //   - The same three edges are removed from the residual flow graph.
10886 //   - The reverse edges (l, source), (r, l), and (sink, r) are added
10887 //     to the residual flow graph, which is a directional graph
10888 //     representing unused flow capacity.
10889 //
10890 // When the method augments a flow (moving left_[l] from some r1 to some
10891 // other r2), this can be thought of as "undoing" the above steps with
10892 // respect to r1 and "redoing" them with respect to r2.
10893 //
10894 // It bears repeating that the flow graph and residual flow graph are
10895 // never represented explicitly, but can be derived by looking at the
10896 // information in 'graph' and in left_.
10897 //
10898 // As an optimization, there is a second vector<int> called right_ which
10899 // does not provide any new information. Instead, it enables more
10900 // efficient queries about edges entering or leaving the right-side nodes
10901 // of the flow or residual flow graphs. The following invariants are
10902 // maintained:
10903 //
10904 // left[l] == kUnused or right[left[l]] == l
10905 // right[r] == kUnused or left[right[r]] == r
10906 //
10907 // . [ source ]                                        .
10908 // .   |||                                             .
10909 // .   |||                                             .
10910 // .   ||\--> left[0]=1  ---\    right[0]=-1 ----\     .
10911 // .   ||                   |                    |     .
10912 // .   |\---> left[1]=-1    \--> right[1]=0  ---\|     .
10913 // .   |                                        ||     .
10914 // .   \----> left[2]=2  ------> right[2]=2  --\||     .
10915 // .                                           |||     .
10916 // .         elements           matchers       vvv     .
10917 // .                                         [ sink ]  .
10918 //
10919 // See Also:
10920 //   [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
10921 //       "Introduction to Algorithms (Second ed.)", pp. 651-664.
10922 //   [2] "Ford-Fulkerson algorithm", Wikipedia,
10923 //       'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
10924 class MaxBipartiteMatchState {
10925  public:
MaxBipartiteMatchState(const MatchMatrix & graph)10926   explicit MaxBipartiteMatchState(const MatchMatrix& graph)
10927       : graph_(&graph),
10928         left_(graph_->LhsSize(), kUnused),
10929         right_(graph_->RhsSize(), kUnused) {
10930   }
10931 
10932   // Returns the edges of a maximal match, each in the form {left, right}.
Compute()10933   ElementMatcherPairs Compute() {
10934     // 'seen' is used for path finding { 0: unseen, 1: seen }.
10935     ::std::vector<char> seen;
10936     // Searches the residual flow graph for a path from each left node to
10937     // the sink in the residual flow graph, and if one is found, add flow
10938     // to the graph. It's okay to search through the left nodes once. The
10939     // edge from the implicit source node to each previously-visited left
10940     // node will have flow if that left node has any path to the sink
10941     // whatsoever. Subsequent augmentations can only add flow to the
10942     // network, and cannot take away that previous flow unit from the source.
10943     // Since the source-to-left edge can only carry one flow unit (or,
10944     // each element can be matched to only one matcher), there is no need
10945     // to visit the left nodes more than once looking for augmented paths.
10946     // The flow is known to be possible or impossible by looking at the
10947     // node once.
10948     for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
10949       // Reset the path-marking vector and try to find a path from
10950       // source to sink starting at the left_[ilhs] node.
10951       GTEST_CHECK_(left_[ilhs] == kUnused)
10952           << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
10953       // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
10954       seen.assign(graph_->RhsSize(), 0);
10955       TryAugment(ilhs, &seen);
10956     }
10957     ElementMatcherPairs result;
10958     for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
10959       size_t irhs = left_[ilhs];
10960       if (irhs == kUnused) continue;
10961       result.push_back(ElementMatcherPair(ilhs, irhs));
10962     }
10963     return result;
10964   }
10965 
10966  private:
10967   static const size_t kUnused = static_cast<size_t>(-1);
10968 
10969   // Perform a depth-first search from left node ilhs to the sink.  If a
10970   // path is found, flow is added to the network by linking the left and
10971   // right vector elements corresponding each segment of the path.
10972   // Returns true if a path to sink was found, which means that a unit of
10973   // flow was added to the network. The 'seen' vector elements correspond
10974   // to right nodes and are marked to eliminate cycles from the search.
10975   //
10976   // Left nodes will only be explored at most once because they
10977   // are accessible from at most one right node in the residual flow
10978   // graph.
10979   //
10980   // Note that left_[ilhs] is the only element of left_ that TryAugment will
10981   // potentially transition from kUnused to another value. Any other
10982   // left_ element holding kUnused before TryAugment will be holding it
10983   // when TryAugment returns.
10984   //
TryAugment(size_t ilhs,::std::vector<char> * seen)10985   bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
10986     for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
10987       if ((*seen)[irhs])
10988         continue;
10989       if (!graph_->HasEdge(ilhs, irhs))
10990         continue;
10991       // There's an available edge from ilhs to irhs.
10992       (*seen)[irhs] = 1;
10993       // Next a search is performed to determine whether
10994       // this edge is a dead end or leads to the sink.
10995       //
10996       // right_[irhs] == kUnused means that there is residual flow from
10997       // right node irhs to the sink, so we can use that to finish this
10998       // flow path and return success.
10999       //
11000       // Otherwise there is residual flow to some ilhs. We push flow
11001       // along that path and call ourselves recursively to see if this
11002       // ultimately leads to sink.
11003       if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
11004         // Add flow from left_[ilhs] to right_[irhs].
11005         left_[ilhs] = irhs;
11006         right_[irhs] = ilhs;
11007         return true;
11008       }
11009     }
11010     return false;
11011   }
11012 
11013   const MatchMatrix* graph_;  // not owned
11014   // Each element of the left_ vector represents a left hand side node
11015   // (i.e. an element) and each element of right_ is a right hand side
11016   // node (i.e. a matcher). The values in the left_ vector indicate
11017   // outflow from that node to a node on the the right_ side. The values
11018   // in the right_ indicate inflow, and specify which left_ node is
11019   // feeding that right_ node, if any. For example, left_[3] == 1 means
11020   // there's a flow from element #3 to matcher #1. Such a flow would also
11021   // be redundantly represented in the right_ vector as right_[1] == 3.
11022   // Elements of left_ and right_ are either kUnused or mutually
11023   // referent. Mutually referent means that left_[right_[i]] = i and
11024   // right_[left_[i]] = i.
11025   ::std::vector<size_t> left_;
11026   ::std::vector<size_t> right_;
11027 
11028   GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
11029 };
11030 
11031 const size_t MaxBipartiteMatchState::kUnused;
11032 
11033 GTEST_API_ ElementMatcherPairs
FindMaxBipartiteMatching(const MatchMatrix & g)11034 FindMaxBipartiteMatching(const MatchMatrix& g) {
11035   return MaxBipartiteMatchState(g).Compute();
11036 }
11037 
LogElementMatcherPairVec(const ElementMatcherPairs & pairs,::std::ostream * stream)11038 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
11039                                      ::std::ostream* stream) {
11040   typedef ElementMatcherPairs::const_iterator Iter;
11041   ::std::ostream& os = *stream;
11042   os << "{";
11043   const char *sep = "";
11044   for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
11045     os << sep << "\n  ("
11046        << "element #" << it->first << ", "
11047        << "matcher #" << it->second << ")";
11048     sep = ",";
11049   }
11050   os << "\n}";
11051 }
11052 
11053 // Tries to find a pairing, and explains the result.
FindPairing(const MatchMatrix & matrix,MatchResultListener * listener)11054 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
11055                             MatchResultListener* listener) {
11056   ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
11057 
11058   size_t max_flow = matches.size();
11059   bool result = (max_flow == matrix.RhsSize());
11060 
11061   if (!result) {
11062     if (listener->IsInterested()) {
11063       *listener << "where no permutation of the elements can "
11064                    "satisfy all matchers, and the closest match is "
11065                 << max_flow << " of " << matrix.RhsSize()
11066                 << " matchers with the pairings:\n";
11067       LogElementMatcherPairVec(matches, listener->stream());
11068     }
11069     return false;
11070   }
11071 
11072   if (matches.size() > 1) {
11073     if (listener->IsInterested()) {
11074       const char *sep = "where:\n";
11075       for (size_t mi = 0; mi < matches.size(); ++mi) {
11076         *listener << sep << " - element #" << matches[mi].first
11077                   << " is matched by matcher #" << matches[mi].second;
11078         sep = ",\n";
11079       }
11080     }
11081   }
11082   return true;
11083 }
11084 
NextGraph()11085 bool MatchMatrix::NextGraph() {
11086   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
11087     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
11088       char& b = matched_[SpaceIndex(ilhs, irhs)];
11089       if (!b) {
11090         b = 1;
11091         return true;
11092       }
11093       b = 0;
11094     }
11095   }
11096   return false;
11097 }
11098 
Randomize()11099 void MatchMatrix::Randomize() {
11100   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
11101     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
11102       char& b = matched_[SpaceIndex(ilhs, irhs)];
11103       b = static_cast<char>(rand() & 1);  // NOLINT
11104     }
11105   }
11106 }
11107 
DebugString() const11108 string MatchMatrix::DebugString() const {
11109   ::std::stringstream ss;
11110   const char *sep = "";
11111   for (size_t i = 0; i < LhsSize(); ++i) {
11112     ss << sep;
11113     for (size_t j = 0; j < RhsSize(); ++j) {
11114       ss << HasEdge(i, j);
11115     }
11116     sep = ";";
11117   }
11118   return ss.str();
11119 }
11120 
DescribeToImpl(::std::ostream * os) const11121 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
11122     ::std::ostream* os) const {
11123   if (matcher_describers_.empty()) {
11124     *os << "is empty";
11125     return;
11126   }
11127   if (matcher_describers_.size() == 1) {
11128     *os << "has " << Elements(1) << " and that element ";
11129     matcher_describers_[0]->DescribeTo(os);
11130     return;
11131   }
11132   *os << "has " << Elements(matcher_describers_.size())
11133       << " and there exists some permutation of elements such that:\n";
11134   const char* sep = "";
11135   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
11136     *os << sep << " - element #" << i << " ";
11137     matcher_describers_[i]->DescribeTo(os);
11138     sep = ", and\n";
11139   }
11140 }
11141 
DescribeNegationToImpl(::std::ostream * os) const11142 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
11143     ::std::ostream* os) const {
11144   if (matcher_describers_.empty()) {
11145     *os << "isn't empty";
11146     return;
11147   }
11148   if (matcher_describers_.size() == 1) {
11149     *os << "doesn't have " << Elements(1)
11150         << ", or has " << Elements(1) << " that ";
11151     matcher_describers_[0]->DescribeNegationTo(os);
11152     return;
11153   }
11154   *os << "doesn't have " << Elements(matcher_describers_.size())
11155       << ", or there exists no permutation of elements such that:\n";
11156   const char* sep = "";
11157   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
11158     *os << sep << " - element #" << i << " ";
11159     matcher_describers_[i]->DescribeTo(os);
11160     sep = ", and\n";
11161   }
11162 }
11163 
11164 // Checks that all matchers match at least one element, and that all
11165 // elements match at least one matcher. This enables faster matching
11166 // and better error reporting.
11167 // Returns false, writing an explanation to 'listener', if and only
11168 // if the success criteria are not met.
11169 bool UnorderedElementsAreMatcherImplBase::
VerifyAllElementsAndMatchersAreMatched(const::std::vector<string> & element_printouts,const MatchMatrix & matrix,MatchResultListener * listener) const11170 VerifyAllElementsAndMatchersAreMatched(
11171     const ::std::vector<string>& element_printouts,
11172     const MatchMatrix& matrix,
11173     MatchResultListener* listener) const {
11174   bool result = true;
11175   ::std::vector<char> element_matched(matrix.LhsSize(), 0);
11176   ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
11177 
11178   for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
11179     for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
11180       char matched = matrix.HasEdge(ilhs, irhs);
11181       element_matched[ilhs] |= matched;
11182       matcher_matched[irhs] |= matched;
11183     }
11184   }
11185 
11186   {
11187     const char* sep =
11188         "where the following matchers don't match any elements:\n";
11189     for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
11190       if (matcher_matched[mi])
11191         continue;
11192       result = false;
11193       if (listener->IsInterested()) {
11194         *listener << sep << "matcher #" << mi << ": ";
11195         matcher_describers_[mi]->DescribeTo(listener->stream());
11196         sep = ",\n";
11197       }
11198     }
11199   }
11200 
11201   {
11202     const char* sep =
11203         "where the following elements don't match any matchers:\n";
11204     const char* outer_sep = "";
11205     if (!result) {
11206       outer_sep = "\nand ";
11207     }
11208     for (size_t ei = 0; ei < element_matched.size(); ++ei) {
11209       if (element_matched[ei])
11210         continue;
11211       result = false;
11212       if (listener->IsInterested()) {
11213         *listener << outer_sep << sep << "element #" << ei << ": "
11214                   << element_printouts[ei];
11215         sep = ",\n";
11216         outer_sep = "";
11217       }
11218     }
11219   }
11220   return result;
11221 }
11222 
11223 }  // namespace internal
11224 }  // namespace testing
11225 // Copyright 2007, Google Inc.
11226 // All rights reserved.
11227 //
11228 // Redistribution and use in source and binary forms, with or without
11229 // modification, are permitted provided that the following conditions are
11230 // met:
11231 //
11232 //     * Redistributions of source code must retain the above copyright
11233 // notice, this list of conditions and the following disclaimer.
11234 //     * Redistributions in binary form must reproduce the above
11235 // copyright notice, this list of conditions and the following disclaimer
11236 // in the documentation and/or other materials provided with the
11237 // distribution.
11238 //     * Neither the name of Google Inc. nor the names of its
11239 // contributors may be used to endorse or promote products derived from
11240 // this software without specific prior written permission.
11241 //
11242 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11243 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11244 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11245 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11246 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11247 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11248 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11249 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11250 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11251 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11252 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11253 //
11254 // Author: wan@google.com (Zhanyong Wan)
11255 
11256 // Google Mock - a framework for writing C++ mock classes.
11257 //
11258 // This file implements the spec builder syntax (ON_CALL and
11259 // EXPECT_CALL).
11260 
11261 
11262 #include <stdlib.h>
11263 #include <iostream>  // NOLINT
11264 #include <map>
11265 #include <set>
11266 #include <string>
11267 
11268 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
11269 # include <unistd.h>  // NOLINT
11270 #endif
11271 
11272 namespace testing {
11273 namespace internal {
11274 
11275 // Protects the mock object registry (in class Mock), all function
11276 // mockers, and all expectations.
11277 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
11278 
11279 // Logs a message including file and line number information.
LogWithLocation(testing::internal::LogSeverity severity,const char * file,int line,const string & message)11280 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
11281                                 const char* file, int line,
11282                                 const string& message) {
11283   ::std::ostringstream s;
11284   s << file << ":" << line << ": " << message << ::std::endl;
11285   Log(severity, s.str(), 0);
11286 }
11287 
11288 // Constructs an ExpectationBase object.
ExpectationBase(const char * a_file,int a_line,const string & a_source_text)11289 ExpectationBase::ExpectationBase(const char* a_file,
11290                                  int a_line,
11291                                  const string& a_source_text)
11292     : file_(a_file),
11293       line_(a_line),
11294       source_text_(a_source_text),
11295       cardinality_specified_(false),
11296       cardinality_(Exactly(1)),
11297       call_count_(0),
11298       retired_(false),
11299       extra_matcher_specified_(false),
11300       repeated_action_specified_(false),
11301       retires_on_saturation_(false),
11302       last_clause_(kNone),
11303       action_count_checked_(false) {}
11304 
11305 // Destructs an ExpectationBase object.
~ExpectationBase()11306 ExpectationBase::~ExpectationBase() {}
11307 
11308 // Explicitly specifies the cardinality of this expectation.  Used by
11309 // the subclasses to implement the .Times() clause.
SpecifyCardinality(const Cardinality & a_cardinality)11310 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
11311   cardinality_specified_ = true;
11312   cardinality_ = a_cardinality;
11313 }
11314 
11315 // Retires all pre-requisites of this expectation.
RetireAllPreRequisites()11316 void ExpectationBase::RetireAllPreRequisites()
11317     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11318   if (is_retired()) {
11319     // We can take this short-cut as we never retire an expectation
11320     // until we have retired all its pre-requisites.
11321     return;
11322   }
11323 
11324   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
11325        it != immediate_prerequisites_.end(); ++it) {
11326     ExpectationBase* const prerequisite = it->expectation_base().get();
11327     if (!prerequisite->is_retired()) {
11328       prerequisite->RetireAllPreRequisites();
11329       prerequisite->Retire();
11330     }
11331   }
11332 }
11333 
11334 // Returns true iff all pre-requisites of this expectation have been
11335 // satisfied.
AllPrerequisitesAreSatisfied() const11336 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
11337     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11338   g_gmock_mutex.AssertHeld();
11339   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
11340        it != immediate_prerequisites_.end(); ++it) {
11341     if (!(it->expectation_base()->IsSatisfied()) ||
11342         !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
11343       return false;
11344   }
11345   return true;
11346 }
11347 
11348 // Adds unsatisfied pre-requisites of this expectation to 'result'.
FindUnsatisfiedPrerequisites(ExpectationSet * result) const11349 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
11350     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11351   g_gmock_mutex.AssertHeld();
11352   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
11353        it != immediate_prerequisites_.end(); ++it) {
11354     if (it->expectation_base()->IsSatisfied()) {
11355       // If *it is satisfied and has a call count of 0, some of its
11356       // pre-requisites may not be satisfied yet.
11357       if (it->expectation_base()->call_count_ == 0) {
11358         it->expectation_base()->FindUnsatisfiedPrerequisites(result);
11359       }
11360     } else {
11361       // Now that we know *it is unsatisfied, we are not so interested
11362       // in whether its pre-requisites are satisfied.  Therefore we
11363       // don't recursively call FindUnsatisfiedPrerequisites() here.
11364       *result += *it;
11365     }
11366   }
11367 }
11368 
11369 // Describes how many times a function call matching this
11370 // expectation has occurred.
DescribeCallCountTo(::std::ostream * os) const11371 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
11372     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11373   g_gmock_mutex.AssertHeld();
11374 
11375   // Describes how many times the function is expected to be called.
11376   *os << "         Expected: to be ";
11377   cardinality().DescribeTo(os);
11378   *os << "\n           Actual: ";
11379   Cardinality::DescribeActualCallCountTo(call_count(), os);
11380 
11381   // Describes the state of the expectation (e.g. is it satisfied?
11382   // is it active?).
11383   *os << " - " << (IsOverSaturated() ? "over-saturated" :
11384                    IsSaturated() ? "saturated" :
11385                    IsSatisfied() ? "satisfied" : "unsatisfied")
11386       << " and "
11387       << (is_retired() ? "retired" : "active");
11388 }
11389 
11390 // Checks the action count (i.e. the number of WillOnce() and
11391 // WillRepeatedly() clauses) against the cardinality if this hasn't
11392 // been done before.  Prints a warning if there are too many or too
11393 // few actions.
CheckActionCountIfNotDone() const11394 void ExpectationBase::CheckActionCountIfNotDone() const
11395     GTEST_LOCK_EXCLUDED_(mutex_) {
11396   bool should_check = false;
11397   {
11398     MutexLock l(&mutex_);
11399     if (!action_count_checked_) {
11400       action_count_checked_ = true;
11401       should_check = true;
11402     }
11403   }
11404 
11405   if (should_check) {
11406     if (!cardinality_specified_) {
11407       // The cardinality was inferred - no need to check the action
11408       // count against it.
11409       return;
11410     }
11411 
11412     // The cardinality was explicitly specified.
11413     const int action_count = static_cast<int>(untyped_actions_.size());
11414     const int upper_bound = cardinality().ConservativeUpperBound();
11415     const int lower_bound = cardinality().ConservativeLowerBound();
11416     bool too_many;  // True if there are too many actions, or false
11417     // if there are too few.
11418     if (action_count > upper_bound ||
11419         (action_count == upper_bound && repeated_action_specified_)) {
11420       too_many = true;
11421     } else if (0 < action_count && action_count < lower_bound &&
11422                !repeated_action_specified_) {
11423       too_many = false;
11424     } else {
11425       return;
11426     }
11427 
11428     ::std::stringstream ss;
11429     DescribeLocationTo(&ss);
11430     ss << "Too " << (too_many ? "many" : "few")
11431        << " actions specified in " << source_text() << "...\n"
11432        << "Expected to be ";
11433     cardinality().DescribeTo(&ss);
11434     ss << ", but has " << (too_many ? "" : "only ")
11435        << action_count << " WillOnce()"
11436        << (action_count == 1 ? "" : "s");
11437     if (repeated_action_specified_) {
11438       ss << " and a WillRepeatedly()";
11439     }
11440     ss << ".";
11441     Log(kWarning, ss.str(), -1);  // -1 means "don't print stack trace".
11442   }
11443 }
11444 
11445 // Implements the .Times() clause.
UntypedTimes(const Cardinality & a_cardinality)11446 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
11447   if (last_clause_ == kTimes) {
11448     ExpectSpecProperty(false,
11449                        ".Times() cannot appear "
11450                        "more than once in an EXPECT_CALL().");
11451   } else {
11452     ExpectSpecProperty(last_clause_ < kTimes,
11453                        ".Times() cannot appear after "
11454                        ".InSequence(), .WillOnce(), .WillRepeatedly(), "
11455                        "or .RetiresOnSaturation().");
11456   }
11457   last_clause_ = kTimes;
11458 
11459   SpecifyCardinality(a_cardinality);
11460 }
11461 
11462 // Points to the implicit sequence introduced by a living InSequence
11463 // object (if any) in the current thread or NULL.
11464 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
11465 
11466 // Reports an uninteresting call (whose description is in msg) in the
11467 // manner specified by 'reaction'.
ReportUninterestingCall(CallReaction reaction,const string & msg)11468 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
11469   // Include a stack trace only if --gmock_verbose=info is specified.
11470   const int stack_frames_to_skip =
11471       GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
11472   switch (reaction) {
11473     case kAllow:
11474       Log(kInfo, msg, stack_frames_to_skip);
11475       break;
11476     case kWarn:
11477       Log(kWarning,
11478           msg +
11479           "\nNOTE: You can safely ignore the above warning unless this "
11480           "call should not happen.  Do not suppress it by blindly adding "
11481           "an EXPECT_CALL() if you don't mean to enforce the call.  "
11482           "See http://code.google.com/p/googlemock/wiki/CookBook#"
11483           "Knowing_When_to_Expect for details.\n",
11484           stack_frames_to_skip);
11485       break;
11486     default:  // FAIL
11487       Expect(false, NULL, -1, msg);
11488   }
11489 }
11490 
UntypedFunctionMockerBase()11491 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
11492     : mock_obj_(NULL), name_("") {}
11493 
~UntypedFunctionMockerBase()11494 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
11495 
11496 // Sets the mock object this mock method belongs to, and registers
11497 // this information in the global mock registry.  Will be called
11498 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
11499 // method.
RegisterOwner(const void * mock_obj)11500 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
11501     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11502   {
11503     MutexLock l(&g_gmock_mutex);
11504     mock_obj_ = mock_obj;
11505   }
11506   Mock::Register(mock_obj, this);
11507 }
11508 
11509 // Sets the mock object this mock method belongs to, and sets the name
11510 // of the mock function.  Will be called upon each invocation of this
11511 // mock function.
SetOwnerAndName(const void * mock_obj,const char * name)11512 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
11513                                                 const char* name)
11514     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11515   // We protect name_ under g_gmock_mutex in case this mock function
11516   // is called from two threads concurrently.
11517   MutexLock l(&g_gmock_mutex);
11518   mock_obj_ = mock_obj;
11519   name_ = name;
11520 }
11521 
11522 // Returns the name of the function being mocked.  Must be called
11523 // after RegisterOwner() or SetOwnerAndName() has been called.
MockObject() const11524 const void* UntypedFunctionMockerBase::MockObject() const
11525     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11526   const void* mock_obj;
11527   {
11528     // We protect mock_obj_ under g_gmock_mutex in case this mock
11529     // function is called from two threads concurrently.
11530     MutexLock l(&g_gmock_mutex);
11531     Assert(mock_obj_ != NULL, __FILE__, __LINE__,
11532            "MockObject() must not be called before RegisterOwner() or "
11533            "SetOwnerAndName() has been called.");
11534     mock_obj = mock_obj_;
11535   }
11536   return mock_obj;
11537 }
11538 
11539 // Returns the name of this mock method.  Must be called after
11540 // SetOwnerAndName() has been called.
Name() const11541 const char* UntypedFunctionMockerBase::Name() const
11542     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11543   const char* name;
11544   {
11545     // We protect name_ under g_gmock_mutex in case this mock
11546     // function is called from two threads concurrently.
11547     MutexLock l(&g_gmock_mutex);
11548     Assert(name_ != NULL, __FILE__, __LINE__,
11549            "Name() must not be called before SetOwnerAndName() has "
11550            "been called.");
11551     name = name_;
11552   }
11553   return name;
11554 }
11555 
11556 // Calculates the result of invoking this mock function with the given
11557 // arguments, prints it, and returns it.  The caller is responsible
11558 // for deleting the result.
11559 UntypedActionResultHolderBase*
UntypedInvokeWith(const void * const untyped_args)11560 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
11561     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11562   if (untyped_expectations_.size() == 0) {
11563     // No expectation is set on this mock method - we have an
11564     // uninteresting call.
11565 
11566     // We must get Google Mock's reaction on uninteresting calls
11567     // made on this mock object BEFORE performing the action,
11568     // because the action may DELETE the mock object and make the
11569     // following expression meaningless.
11570     const CallReaction reaction =
11571         Mock::GetReactionOnUninterestingCalls(MockObject());
11572 
11573     // True iff we need to print this call's arguments and return
11574     // value.  This definition must be kept in sync with
11575     // the behavior of ReportUninterestingCall().
11576     const bool need_to_report_uninteresting_call =
11577         // If the user allows this uninteresting call, we print it
11578         // only when he wants informational messages.
11579         reaction == kAllow ? LogIsVisible(kInfo) :
11580         // If the user wants this to be a warning, we print it only
11581         // when he wants to see warnings.
11582         reaction == kWarn ? LogIsVisible(kWarning) :
11583         // Otherwise, the user wants this to be an error, and we
11584         // should always print detailed information in the error.
11585         true;
11586 
11587     if (!need_to_report_uninteresting_call) {
11588       // Perform the action without printing the call information.
11589       return this->UntypedPerformDefaultAction(untyped_args, "");
11590     }
11591 
11592     // Warns about the uninteresting call.
11593     ::std::stringstream ss;
11594     this->UntypedDescribeUninterestingCall(untyped_args, &ss);
11595 
11596     // Calculates the function result.
11597     UntypedActionResultHolderBase* const result =
11598         this->UntypedPerformDefaultAction(untyped_args, ss.str());
11599 
11600     // Prints the function result.
11601     if (result != NULL)
11602       result->PrintAsActionResult(&ss);
11603 
11604     ReportUninterestingCall(reaction, ss.str());
11605     return result;
11606   }
11607 
11608   bool is_excessive = false;
11609   ::std::stringstream ss;
11610   ::std::stringstream why;
11611   ::std::stringstream loc;
11612   const void* untyped_action = NULL;
11613 
11614   // The UntypedFindMatchingExpectation() function acquires and
11615   // releases g_gmock_mutex.
11616   const ExpectationBase* const untyped_expectation =
11617       this->UntypedFindMatchingExpectation(
11618           untyped_args, &untyped_action, &is_excessive,
11619           &ss, &why);
11620   const bool found = untyped_expectation != NULL;
11621 
11622   // True iff we need to print the call's arguments and return value.
11623   // This definition must be kept in sync with the uses of Expect()
11624   // and Log() in this function.
11625   const bool need_to_report_call =
11626       !found || is_excessive || LogIsVisible(kInfo);
11627   if (!need_to_report_call) {
11628     // Perform the action without printing the call information.
11629     return
11630         untyped_action == NULL ?
11631         this->UntypedPerformDefaultAction(untyped_args, "") :
11632         this->UntypedPerformAction(untyped_action, untyped_args);
11633   }
11634 
11635   ss << "    Function call: " << Name();
11636   this->UntypedPrintArgs(untyped_args, &ss);
11637 
11638   // In case the action deletes a piece of the expectation, we
11639   // generate the message beforehand.
11640   if (found && !is_excessive) {
11641     untyped_expectation->DescribeLocationTo(&loc);
11642   }
11643 
11644   UntypedActionResultHolderBase* const result =
11645       untyped_action == NULL ?
11646       this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
11647       this->UntypedPerformAction(untyped_action, untyped_args);
11648   if (result != NULL)
11649     result->PrintAsActionResult(&ss);
11650   ss << "\n" << why.str();
11651 
11652   if (!found) {
11653     // No expectation matches this call - reports a failure.
11654     Expect(false, NULL, -1, ss.str());
11655   } else if (is_excessive) {
11656     // We had an upper-bound violation and the failure message is in ss.
11657     Expect(false, untyped_expectation->file(),
11658            untyped_expectation->line(), ss.str());
11659   } else {
11660     // We had an expected call and the matching expectation is
11661     // described in ss.
11662     Log(kInfo, loc.str() + ss.str(), 2);
11663   }
11664 
11665   return result;
11666 }
11667 
11668 // Returns an Expectation object that references and co-owns exp,
11669 // which must be an expectation on this mock function.
GetHandleOf(ExpectationBase * exp)11670 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
11671   for (UntypedExpectations::const_iterator it =
11672            untyped_expectations_.begin();
11673        it != untyped_expectations_.end(); ++it) {
11674     if (it->get() == exp) {
11675       return Expectation(*it);
11676     }
11677   }
11678 
11679   Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
11680   return Expectation();
11681   // The above statement is just to make the code compile, and will
11682   // never be executed.
11683 }
11684 
11685 // Verifies that all expectations on this mock function have been
11686 // satisfied.  Reports one or more Google Test non-fatal failures
11687 // and returns false if not.
VerifyAndClearExpectationsLocked()11688 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
11689     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11690   g_gmock_mutex.AssertHeld();
11691   bool expectations_met = true;
11692   for (UntypedExpectations::const_iterator it =
11693            untyped_expectations_.begin();
11694        it != untyped_expectations_.end(); ++it) {
11695     ExpectationBase* const untyped_expectation = it->get();
11696     if (untyped_expectation->IsOverSaturated()) {
11697       // There was an upper-bound violation.  Since the error was
11698       // already reported when it occurred, there is no need to do
11699       // anything here.
11700       expectations_met = false;
11701     } else if (!untyped_expectation->IsSatisfied()) {
11702       expectations_met = false;
11703       ::std::stringstream ss;
11704       ss  << "Actual function call count doesn't match "
11705           << untyped_expectation->source_text() << "...\n";
11706       // No need to show the source file location of the expectation
11707       // in the description, as the Expect() call that follows already
11708       // takes care of it.
11709       untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
11710       untyped_expectation->DescribeCallCountTo(&ss);
11711       Expect(false, untyped_expectation->file(),
11712              untyped_expectation->line(), ss.str());
11713     }
11714   }
11715 
11716   // Deleting our expectations may trigger other mock objects to be deleted, for
11717   // example if an action contains a reference counted smart pointer to that
11718   // mock object, and that is the last reference. So if we delete our
11719   // expectations within the context of the global mutex we may deadlock when
11720   // this method is called again. Instead, make a copy of the set of
11721   // expectations to delete, clear our set within the mutex, and then clear the
11722   // copied set outside of it.
11723   UntypedExpectations expectations_to_delete;
11724   untyped_expectations_.swap(expectations_to_delete);
11725 
11726   g_gmock_mutex.Unlock();
11727   expectations_to_delete.clear();
11728   g_gmock_mutex.Lock();
11729 
11730   return expectations_met;
11731 }
11732 
11733 }  // namespace internal
11734 
11735 // Class Mock.
11736 
11737 namespace {
11738 
11739 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
11740 
11741 // The current state of a mock object.  Such information is needed for
11742 // detecting leaked mock objects and explicitly verifying a mock's
11743 // expectations.
11744 struct MockObjectState {
MockObjectStatetesting::__anon77204b490c11::MockObjectState11745   MockObjectState()
11746       : first_used_file(NULL), first_used_line(-1), leakable(false) {}
11747 
11748   // Where in the source file an ON_CALL or EXPECT_CALL is first
11749   // invoked on this mock object.
11750   const char* first_used_file;
11751   int first_used_line;
11752   ::std::string first_used_test_case;
11753   ::std::string first_used_test;
11754   bool leakable;  // true iff it's OK to leak the object.
11755   FunctionMockers function_mockers;  // All registered methods of the object.
11756 };
11757 
11758 // A global registry holding the state of all mock objects that are
11759 // alive.  A mock object is added to this registry the first time
11760 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It
11761 // is removed from the registry in the mock object's destructor.
11762 class MockObjectRegistry {
11763  public:
11764   // Maps a mock object (identified by its address) to its state.
11765   typedef std::map<const void*, MockObjectState> StateMap;
11766 
11767   // This destructor will be called when a program exits, after all
11768   // tests in it have been run.  By then, there should be no mock
11769   // object alive.  Therefore we report any living object as test
11770   // failure, unless the user explicitly asked us to ignore it.
~MockObjectRegistry()11771   ~MockObjectRegistry() {
11772     // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
11773     // a macro.
11774 
11775     if (!GMOCK_FLAG(catch_leaked_mocks))
11776       return;
11777 
11778     int leaked_count = 0;
11779     for (StateMap::const_iterator it = states_.begin(); it != states_.end();
11780          ++it) {
11781       if (it->second.leakable)  // The user said it's fine to leak this object.
11782         continue;
11783 
11784       // TODO(wan@google.com): Print the type of the leaked object.
11785       // This can help the user identify the leaked object.
11786       std::cout << "\n";
11787       const MockObjectState& state = it->second;
11788       std::cout << internal::FormatFileLocation(state.first_used_file,
11789                                                 state.first_used_line);
11790       std::cout << " ERROR: this mock object";
11791       if (state.first_used_test != "") {
11792         std::cout << " (used in test " << state.first_used_test_case << "."
11793              << state.first_used_test << ")";
11794       }
11795       std::cout << " should be deleted but never is. Its address is @"
11796            << it->first << ".";
11797       leaked_count++;
11798     }
11799     if (leaked_count > 0) {
11800       std::cout << "\nERROR: " << leaked_count
11801            << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
11802            << " found at program exit.\n";
11803       std::cout.flush();
11804       ::std::cerr.flush();
11805       // RUN_ALL_TESTS() has already returned when this destructor is
11806       // called.  Therefore we cannot use the normal Google Test
11807       // failure reporting mechanism.
11808       _exit(1);  // We cannot call exit() as it is not reentrant and
11809                  // may already have been called.
11810     }
11811   }
11812 
states()11813   StateMap& states() { return states_; }
11814 
11815  private:
11816   StateMap states_;
11817 };
11818 
11819 // Protected by g_gmock_mutex.
11820 MockObjectRegistry g_mock_object_registry;
11821 
11822 // Maps a mock object to the reaction Google Mock should have when an
11823 // uninteresting method is called.  Protected by g_gmock_mutex.
11824 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
11825 
11826 // Sets the reaction Google Mock should have when an uninteresting
11827 // method of the given mock object is called.
SetReactionOnUninterestingCalls(const void * mock_obj,internal::CallReaction reaction)11828 void SetReactionOnUninterestingCalls(const void* mock_obj,
11829                                      internal::CallReaction reaction)
11830     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11831   internal::MutexLock l(&internal::g_gmock_mutex);
11832   g_uninteresting_call_reaction[mock_obj] = reaction;
11833 }
11834 
11835 }  // namespace
11836 
11837 // Tells Google Mock to allow uninteresting calls on the given mock
11838 // object.
AllowUninterestingCalls(const void * mock_obj)11839 void Mock::AllowUninterestingCalls(const void* mock_obj)
11840     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11841   SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
11842 }
11843 
11844 // Tells Google Mock to warn the user about uninteresting calls on the
11845 // given mock object.
WarnUninterestingCalls(const void * mock_obj)11846 void Mock::WarnUninterestingCalls(const void* mock_obj)
11847     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11848   SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
11849 }
11850 
11851 // Tells Google Mock to fail uninteresting calls on the given mock
11852 // object.
FailUninterestingCalls(const void * mock_obj)11853 void Mock::FailUninterestingCalls(const void* mock_obj)
11854     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11855   SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
11856 }
11857 
11858 // Tells Google Mock the given mock object is being destroyed and its
11859 // entry in the call-reaction table should be removed.
UnregisterCallReaction(const void * mock_obj)11860 void Mock::UnregisterCallReaction(const void* mock_obj)
11861     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11862   internal::MutexLock l(&internal::g_gmock_mutex);
11863   g_uninteresting_call_reaction.erase(mock_obj);
11864 }
11865 
11866 // Returns the reaction Google Mock will have on uninteresting calls
11867 // made on the given mock object.
GetReactionOnUninterestingCalls(const void * mock_obj)11868 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
11869     const void* mock_obj)
11870         GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11871   internal::MutexLock l(&internal::g_gmock_mutex);
11872   return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
11873       internal::kDefault : g_uninteresting_call_reaction[mock_obj];
11874 }
11875 
11876 // Tells Google Mock to ignore mock_obj when checking for leaked mock
11877 // objects.
AllowLeak(const void * mock_obj)11878 void Mock::AllowLeak(const void* mock_obj)
11879     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11880   internal::MutexLock l(&internal::g_gmock_mutex);
11881   g_mock_object_registry.states()[mock_obj].leakable = true;
11882 }
11883 
11884 // Verifies and clears all expectations on the given mock object.  If
11885 // the expectations aren't satisfied, generates one or more Google
11886 // Test non-fatal failures and returns false.
VerifyAndClearExpectations(void * mock_obj)11887 bool Mock::VerifyAndClearExpectations(void* mock_obj)
11888     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11889   internal::MutexLock l(&internal::g_gmock_mutex);
11890   return VerifyAndClearExpectationsLocked(mock_obj);
11891 }
11892 
11893 // Verifies all expectations on the given mock object and clears its
11894 // default actions and expectations.  Returns true iff the
11895 // verification was successful.
VerifyAndClear(void * mock_obj)11896 bool Mock::VerifyAndClear(void* mock_obj)
11897     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11898   internal::MutexLock l(&internal::g_gmock_mutex);
11899   ClearDefaultActionsLocked(mock_obj);
11900   return VerifyAndClearExpectationsLocked(mock_obj);
11901 }
11902 
11903 // Verifies and clears all expectations on the given mock object.  If
11904 // the expectations aren't satisfied, generates one or more Google
11905 // Test non-fatal failures and returns false.
VerifyAndClearExpectationsLocked(void * mock_obj)11906 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
11907     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11908   internal::g_gmock_mutex.AssertHeld();
11909   if (g_mock_object_registry.states().count(mock_obj) == 0) {
11910     // No EXPECT_CALL() was set on the given mock object.
11911     return true;
11912   }
11913 
11914   // Verifies and clears the expectations on each mock method in the
11915   // given mock object.
11916   bool expectations_met = true;
11917   FunctionMockers& mockers =
11918       g_mock_object_registry.states()[mock_obj].function_mockers;
11919   for (FunctionMockers::const_iterator it = mockers.begin();
11920        it != mockers.end(); ++it) {
11921     if (!(*it)->VerifyAndClearExpectationsLocked()) {
11922       expectations_met = false;
11923     }
11924   }
11925 
11926   // We don't clear the content of mockers, as they may still be
11927   // needed by ClearDefaultActionsLocked().
11928   return expectations_met;
11929 }
11930 
11931 // Registers a mock object and a mock method it owns.
Register(const void * mock_obj,internal::UntypedFunctionMockerBase * mocker)11932 void Mock::Register(const void* mock_obj,
11933                     internal::UntypedFunctionMockerBase* mocker)
11934     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11935   internal::MutexLock l(&internal::g_gmock_mutex);
11936   g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
11937 }
11938 
11939 // Tells Google Mock where in the source code mock_obj is used in an
11940 // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
11941 // information helps the user identify which object it is.
RegisterUseByOnCallOrExpectCall(const void * mock_obj,const char * file,int line)11942 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
11943                                            const char* file, int line)
11944     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11945   internal::MutexLock l(&internal::g_gmock_mutex);
11946   MockObjectState& state = g_mock_object_registry.states()[mock_obj];
11947   if (state.first_used_file == NULL) {
11948     state.first_used_file = file;
11949     state.first_used_line = line;
11950     const TestInfo* const test_info =
11951         UnitTest::GetInstance()->current_test_info();
11952     if (test_info != NULL) {
11953       // TODO(wan@google.com): record the test case name when the
11954       // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
11955       // TearDownTestCase().
11956       state.first_used_test_case = test_info->test_case_name();
11957       state.first_used_test = test_info->name();
11958     }
11959   }
11960 }
11961 
11962 // Unregisters a mock method; removes the owning mock object from the
11963 // registry when the last mock method associated with it has been
11964 // unregistered.  This is called only in the destructor of
11965 // FunctionMockerBase.
UnregisterLocked(internal::UntypedFunctionMockerBase * mocker)11966 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
11967     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11968   internal::g_gmock_mutex.AssertHeld();
11969   for (MockObjectRegistry::StateMap::iterator it =
11970            g_mock_object_registry.states().begin();
11971        it != g_mock_object_registry.states().end(); ++it) {
11972     FunctionMockers& mockers = it->second.function_mockers;
11973     if (mockers.erase(mocker) > 0) {
11974       // mocker was in mockers and has been just removed.
11975       if (mockers.empty()) {
11976         g_mock_object_registry.states().erase(it);
11977       }
11978       return;
11979     }
11980   }
11981 }
11982 
11983 // Clears all ON_CALL()s set on the given mock object.
ClearDefaultActionsLocked(void * mock_obj)11984 void Mock::ClearDefaultActionsLocked(void* mock_obj)
11985     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11986   internal::g_gmock_mutex.AssertHeld();
11987 
11988   if (g_mock_object_registry.states().count(mock_obj) == 0) {
11989     // No ON_CALL() was set on the given mock object.
11990     return;
11991   }
11992 
11993   // Clears the default actions for each mock method in the given mock
11994   // object.
11995   FunctionMockers& mockers =
11996       g_mock_object_registry.states()[mock_obj].function_mockers;
11997   for (FunctionMockers::const_iterator it = mockers.begin();
11998        it != mockers.end(); ++it) {
11999     (*it)->ClearDefaultActionsLocked();
12000   }
12001 
12002   // We don't clear the content of mockers, as they may still be
12003   // needed by VerifyAndClearExpectationsLocked().
12004 }
12005 
Expectation()12006 Expectation::Expectation() {}
12007 
Expectation(const internal::linked_ptr<internal::ExpectationBase> & an_expectation_base)12008 Expectation::Expectation(
12009     const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
12010     : expectation_base_(an_expectation_base) {}
12011 
~Expectation()12012 Expectation::~Expectation() {}
12013 
12014 // Adds an expectation to a sequence.
AddExpectation(const Expectation & expectation) const12015 void Sequence::AddExpectation(const Expectation& expectation) const {
12016   if (*last_expectation_ != expectation) {
12017     if (last_expectation_->expectation_base() != NULL) {
12018       expectation.expectation_base()->immediate_prerequisites_
12019           += *last_expectation_;
12020     }
12021     *last_expectation_ = expectation;
12022   }
12023 }
12024 
12025 // Creates the implicit sequence if there isn't one.
InSequence()12026 InSequence::InSequence() {
12027   if (internal::g_gmock_implicit_sequence.get() == NULL) {
12028     internal::g_gmock_implicit_sequence.set(new Sequence);
12029     sequence_created_ = true;
12030   } else {
12031     sequence_created_ = false;
12032   }
12033 }
12034 
12035 // Deletes the implicit sequence if it was created by the constructor
12036 // of this object.
~InSequence()12037 InSequence::~InSequence() {
12038   if (sequence_created_) {
12039     delete internal::g_gmock_implicit_sequence.get();
12040     internal::g_gmock_implicit_sequence.set(NULL);
12041   }
12042 }
12043 
12044 }  // namespace testing
12045 // Copyright 2008, Google Inc.
12046 // All rights reserved.
12047 //
12048 // Redistribution and use in source and binary forms, with or without
12049 // modification, are permitted provided that the following conditions are
12050 // met:
12051 //
12052 //     * Redistributions of source code must retain the above copyright
12053 // notice, this list of conditions and the following disclaimer.
12054 //     * Redistributions in binary form must reproduce the above
12055 // copyright notice, this list of conditions and the following disclaimer
12056 // in the documentation and/or other materials provided with the
12057 // distribution.
12058 //     * Neither the name of Google Inc. nor the names of its
12059 // contributors may be used to endorse or promote products derived from
12060 // this software without specific prior written permission.
12061 //
12062 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12063 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12064 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12065 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12066 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12067 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12068 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12069 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12070 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12071 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12072 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12073 //
12074 // Author: wan@google.com (Zhanyong Wan)
12075 
12076 
12077 namespace testing {
12078 
12079 // TODO(wan@google.com): support using environment variables to
12080 // control the flag values, like what Google Test does.
12081 
12082 GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
12083                    "true iff Google Mock should report leaked mock objects "
12084                    "as failures.");
12085 
12086 GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
12087                      "Controls how verbose Google Mock's output is."
12088                      "  Valid values:\n"
12089                      "  info    - prints all messages.\n"
12090                      "  warning - prints warnings and errors.\n"
12091                      "  error   - prints errors only.");
12092 
12093 namespace internal {
12094 
12095 // Parses a string as a command line flag.  The string should have the
12096 // format "--gmock_flag=value".  When def_optional is true, the
12097 // "=value" part can be omitted.
12098 //
12099 // Returns the value of the flag, or NULL if the parsing failed.
ParseGoogleMockFlagValue(const char * str,const char * flag,bool def_optional)12100 static const char* ParseGoogleMockFlagValue(const char* str,
12101                                             const char* flag,
12102                                             bool def_optional) {
12103   // str and flag must not be NULL.
12104   if (str == NULL || flag == NULL) return NULL;
12105 
12106   // The flag must start with "--gmock_".
12107   const std::string flag_str = std::string("--gmock_") + flag;
12108   const size_t flag_len = flag_str.length();
12109   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
12110 
12111   // Skips the flag name.
12112   const char* flag_end = str + flag_len;
12113 
12114   // When def_optional is true, it's OK to not have a "=value" part.
12115   if (def_optional && (flag_end[0] == '\0')) {
12116     return flag_end;
12117   }
12118 
12119   // If def_optional is true and there are more characters after the
12120   // flag name, or if def_optional is false, there must be a '=' after
12121   // the flag name.
12122   if (flag_end[0] != '=') return NULL;
12123 
12124   // Returns the string after "=".
12125   return flag_end + 1;
12126 }
12127 
12128 // Parses a string for a Google Mock bool flag, in the form of
12129 // "--gmock_flag=value".
12130 //
12131 // On success, stores the value of the flag in *value, and returns
12132 // true.  On failure, returns false without changing *value.
ParseGoogleMockBoolFlag(const char * str,const char * flag,bool * value)12133 static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
12134                                     bool* value) {
12135   // Gets the value of the flag as a string.
12136   const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
12137 
12138   // Aborts if the parsing failed.
12139   if (value_str == NULL) return false;
12140 
12141   // Converts the string value to a bool.
12142   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
12143   return true;
12144 }
12145 
12146 // Parses a string for a Google Mock string flag, in the form of
12147 // "--gmock_flag=value".
12148 //
12149 // On success, stores the value of the flag in *value, and returns
12150 // true.  On failure, returns false without changing *value.
12151 template <typename String>
ParseGoogleMockStringFlag(const char * str,const char * flag,String * value)12152 static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
12153                                       String* value) {
12154   // Gets the value of the flag as a string.
12155   const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
12156 
12157   // Aborts if the parsing failed.
12158   if (value_str == NULL) return false;
12159 
12160   // Sets *value to the value of the flag.
12161   *value = value_str;
12162   return true;
12163 }
12164 
12165 // The internal implementation of InitGoogleMock().
12166 //
12167 // The type parameter CharType can be instantiated to either char or
12168 // wchar_t.
12169 template <typename CharType>
InitGoogleMockImpl(int * argc,CharType ** argv)12170 void InitGoogleMockImpl(int* argc, CharType** argv) {
12171   // Makes sure Google Test is initialized.  InitGoogleTest() is
12172   // idempotent, so it's fine if the user has already called it.
12173   InitGoogleTest(argc, argv);
12174   if (*argc <= 0) return;
12175 
12176   for (int i = 1; i != *argc; i++) {
12177     const std::string arg_string = StreamableToString(argv[i]);
12178     const char* const arg = arg_string.c_str();
12179 
12180     // Do we see a Google Mock flag?
12181     if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
12182                                 &GMOCK_FLAG(catch_leaked_mocks)) ||
12183         ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
12184       // Yes.  Shift the remainder of the argv list left by one.  Note
12185       // that argv has (*argc + 1) elements, the last one always being
12186       // NULL.  The following loop moves the trailing NULL element as
12187       // well.
12188       for (int j = i; j != *argc; j++) {
12189         argv[j] = argv[j + 1];
12190       }
12191 
12192       // Decrements the argument count.
12193       (*argc)--;
12194 
12195       // We also need to decrement the iterator as we just removed
12196       // an element.
12197       i--;
12198     }
12199   }
12200 }
12201 
12202 }  // namespace internal
12203 
12204 // Initializes Google Mock.  This must be called before running the
12205 // tests.  In particular, it parses a command line for the flags that
12206 // Google Mock recognizes.  Whenever a Google Mock flag is seen, it is
12207 // removed from argv, and *argc is decremented.
12208 //
12209 // No value is returned.  Instead, the Google Mock flag variables are
12210 // updated.
12211 //
12212 // Since Google Test is needed for Google Mock to work, this function
12213 // also initializes Google Test and parses its flags, if that hasn't
12214 // been done.
InitGoogleMock(int * argc,char ** argv)12215 GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
12216   internal::InitGoogleMockImpl(argc, argv);
12217 }
12218 
12219 // This overloaded version can be used in Windows programs compiled in
12220 // UNICODE mode.
InitGoogleMock(int * argc,wchar_t ** argv)12221 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
12222   internal::InitGoogleMockImpl(argc, argv);
12223 }
12224 
12225 }  // namespace testing
12226