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