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