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