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