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