Home | History | Annotate | Download | only in src
      1 // Copyright 2005, 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 // Utility functions and classes used by the Google C++ testing framework.
     31 //
     32 // Author: wan (at) google.com (Zhanyong Wan)
     33 //
     34 // This file contains purely Google Test's internal implementation.  Please
     35 // DO NOT #INCLUDE IT IN A USER PROGRAM.
     36 
     37 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
     38 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
     39 
     40 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
     41 // part of Google Test's implementation; otherwise it's undefined.
     42 #if !GTEST_IMPLEMENTATION_
     43 // A user is trying to include this from his code - just say no.
     44 #error "gtest-internal-inl.h is part of Google Test's internal implementation."
     45 #error "It must not be included except by Google Test itself."
     46 #endif  // GTEST_IMPLEMENTATION_
     47 
     48 #ifndef _WIN32_WCE
     49 #include <errno.h>
     50 #endif  // !_WIN32_WCE
     51 #include <stddef.h>
     52 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
     53 #include <string.h>  // For memmove.
     54 
     55 #include <string>
     56 
     57 #include <gtest/internal/gtest-port.h>
     58 
     59 #if GTEST_OS_WINDOWS
     60 #include <windows.h>  // For DWORD.
     61 #endif  // GTEST_OS_WINDOWS
     62 
     63 #include <gtest/gtest.h>
     64 #include <gtest/gtest-spi.h>
     65 
     66 namespace testing {
     67 
     68 // Declares the flags.
     69 //
     70 // We don't want the users to modify this flag in the code, but want
     71 // Google Test's own unit tests to be able to access it. Therefore we
     72 // declare it here as opposed to in gtest.h.
     73 GTEST_DECLARE_bool_(death_test_use_fork);
     74 
     75 namespace internal {
     76 
     77 // The value of GetTestTypeId() as seen from within the Google Test
     78 // library.  This is solely for testing GetTestTypeId().
     79 extern const TypeId kTestTypeIdInGoogleTest;
     80 
     81 // Names of the flags (needed for parsing Google Test flags).
     82 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
     83 const char kBreakOnFailureFlag[] = "break_on_failure";
     84 const char kCatchExceptionsFlag[] = "catch_exceptions";
     85 const char kColorFlag[] = "color";
     86 const char kFilterFlag[] = "filter";
     87 const char kListTestsFlag[] = "list_tests";
     88 const char kOutputFlag[] = "output";
     89 const char kPrintTimeFlag[] = "print_time";
     90 const char kRandomSeedFlag[] = "random_seed";
     91 const char kRepeatFlag[] = "repeat";
     92 const char kShuffleFlag[] = "shuffle";
     93 const char kThrowOnFailureFlag[] = "throw_on_failure";
     94 
     95 // A valid random seed must be in [1, kMaxRandomSeed].
     96 const int kMaxRandomSeed = 99999;
     97 
     98 // Returns the current time in milliseconds.
     99 TimeInMillis GetTimeInMillis();
    100 
    101 // Returns a random seed in range [1, kMaxRandomSeed] based on the
    102 // given --gtest_random_seed flag value.
    103 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
    104   const unsigned int raw_seed = (random_seed_flag == 0) ?
    105       static_cast<unsigned int>(GetTimeInMillis()) :
    106       static_cast<unsigned int>(random_seed_flag);
    107 
    108   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
    109   // it's easy to type.
    110   const int normalized_seed =
    111       static_cast<int>((raw_seed - 1U) %
    112                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
    113   return normalized_seed;
    114 }
    115 
    116 // Returns the first valid random seed after 'seed'.  The behavior is
    117 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
    118 // considered to be 1.
    119 inline int GetNextRandomSeed(int seed) {
    120   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
    121       << "Invalid random seed " << seed << " - must be in [1, "
    122       << kMaxRandomSeed << "].";
    123   const int next_seed = seed + 1;
    124   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
    125 }
    126 
    127 // This class saves the values of all Google Test flags in its c'tor, and
    128 // restores them in its d'tor.
    129 class GTestFlagSaver {
    130  public:
    131   // The c'tor.
    132   GTestFlagSaver() {
    133     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
    134     break_on_failure_ = GTEST_FLAG(break_on_failure);
    135     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
    136     color_ = GTEST_FLAG(color);
    137     death_test_style_ = GTEST_FLAG(death_test_style);
    138     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
    139     filter_ = GTEST_FLAG(filter);
    140     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
    141     list_tests_ = GTEST_FLAG(list_tests);
    142     output_ = GTEST_FLAG(output);
    143     print_time_ = GTEST_FLAG(print_time);
    144     random_seed_ = GTEST_FLAG(random_seed);
    145     repeat_ = GTEST_FLAG(repeat);
    146     shuffle_ = GTEST_FLAG(shuffle);
    147     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
    148   }
    149 
    150   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
    151   ~GTestFlagSaver() {
    152     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
    153     GTEST_FLAG(break_on_failure) = break_on_failure_;
    154     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
    155     GTEST_FLAG(color) = color_;
    156     GTEST_FLAG(death_test_style) = death_test_style_;
    157     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
    158     GTEST_FLAG(filter) = filter_;
    159     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
    160     GTEST_FLAG(list_tests) = list_tests_;
    161     GTEST_FLAG(output) = output_;
    162     GTEST_FLAG(print_time) = print_time_;
    163     GTEST_FLAG(random_seed) = random_seed_;
    164     GTEST_FLAG(repeat) = repeat_;
    165     GTEST_FLAG(shuffle) = shuffle_;
    166     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
    167   }
    168  private:
    169   // Fields for saving the original values of flags.
    170   bool also_run_disabled_tests_;
    171   bool break_on_failure_;
    172   bool catch_exceptions_;
    173   String color_;
    174   String death_test_style_;
    175   bool death_test_use_fork_;
    176   String filter_;
    177   String internal_run_death_test_;
    178   bool list_tests_;
    179   String output_;
    180   bool print_time_;
    181   bool pretty_;
    182   internal::Int32 random_seed_;
    183   internal::Int32 repeat_;
    184   bool shuffle_;
    185   bool throw_on_failure_;
    186 } GTEST_ATTRIBUTE_UNUSED_;
    187 
    188 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
    189 // code_point parameter is of type UInt32 because wchar_t may not be
    190 // wide enough to contain a code point.
    191 // The output buffer str must containt at least 32 characters.
    192 // The function returns the address of the output buffer.
    193 // If the code_point is not a valid Unicode code point
    194 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
    195 // as '(Invalid Unicode 0xXXXXXXXX)'.
    196 char* CodePointToUtf8(UInt32 code_point, char* str);
    197 
    198 // Converts a wide string to a narrow string in UTF-8 encoding.
    199 // The wide string is assumed to have the following encoding:
    200 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
    201 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
    202 // Parameter str points to a null-terminated wide string.
    203 // Parameter num_chars may additionally limit the number
    204 // of wchar_t characters processed. -1 is used when the entire string
    205 // should be processed.
    206 // If the string contains code points that are not valid Unicode code points
    207 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
    208 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
    209 // and contains invalid UTF-16 surrogate pairs, values in those pairs
    210 // will be encoded as individual Unicode characters from Basic Normal Plane.
    211 String WideStringToUtf8(const wchar_t* str, int num_chars);
    212 
    213 // Returns the number of active threads, or 0 when there is an error.
    214 size_t GetThreadCount();
    215 
    216 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
    217 // if the variable is present. If a file already exists at this location, this
    218 // function will write over it. If the variable is present, but the file cannot
    219 // be created, prints an error and exits.
    220 void WriteToShardStatusFileIfNeeded();
    221 
    222 // Checks whether sharding is enabled by examining the relevant
    223 // environment variable values. If the variables are present,
    224 // but inconsistent (e.g., shard_index >= total_shards), prints
    225 // an error and exits. If in_subprocess_for_death_test, sharding is
    226 // disabled because it must only be applied to the original test
    227 // process. Otherwise, we could filter out death tests we intended to execute.
    228 bool ShouldShard(const char* total_shards_str, const char* shard_index_str,
    229                  bool in_subprocess_for_death_test);
    230 
    231 // Parses the environment variable var as an Int32. If it is unset,
    232 // returns default_val. If it is not an Int32, prints an error and
    233 // and aborts.
    234 Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
    235 
    236 // Given the total number of shards, the shard index, and the test id,
    237 // returns true iff the test should be run on this shard. The test id is
    238 // some arbitrary but unique non-negative integer assigned to each test
    239 // method. Assumes that 0 <= shard_index < total_shards.
    240 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id);
    241 
    242 // Vector is an ordered container that supports random access to the
    243 // elements.
    244 //
    245 // We cannot use std::vector, as Visual C++ 7.1's implementation of
    246 // STL has problems compiling when exceptions are disabled.  There is
    247 // a hack to work around the problems, but we've seen cases where the
    248 // hack fails to work.
    249 //
    250 // The element type must support copy constructor and operator=.
    251 template <typename E>  // E is the element type.
    252 class Vector {
    253  public:
    254   // Creates an empty Vector.
    255   Vector() : elements_(NULL), capacity_(0), size_(0) {}
    256 
    257   // D'tor.
    258   virtual ~Vector() { Clear(); }
    259 
    260   // Clears the Vector.
    261   void Clear() {
    262     if (elements_ != NULL) {
    263       for (int i = 0; i < size_; i++) {
    264         delete elements_[i];
    265       }
    266 
    267       free(elements_);
    268       elements_ = NULL;
    269       capacity_ = size_ = 0;
    270     }
    271   }
    272 
    273   // Gets the number of elements.
    274   int size() const { return size_; }
    275 
    276   // Adds an element to the end of the Vector.  A copy of the element
    277   // is created using the copy constructor, and then stored in the
    278   // Vector.  Changes made to the element in the Vector doesn't affect
    279   // the source object, and vice versa.
    280   void PushBack(const E& element) { Insert(element, size_); }
    281 
    282   // Adds an element to the beginning of this Vector.
    283   void PushFront(const E& element) { Insert(element, 0); }
    284 
    285   // Removes an element from the beginning of this Vector.  If the
    286   // result argument is not NULL, the removed element is stored in the
    287   // memory it points to.  Otherwise the element is thrown away.
    288   // Returns true iff the vector wasn't empty before the operation.
    289   bool PopFront(E* result) {
    290     if (size_ == 0)
    291       return false;
    292 
    293     if (result != NULL)
    294       *result = GetElement(0);
    295 
    296     Erase(0);
    297     return true;
    298   }
    299 
    300   // Inserts an element at the given index.  It's the caller's
    301   // responsibility to ensure that the given index is in the range [0,
    302   // size()].
    303   void Insert(const E& element, int index) {
    304     GrowIfNeeded();
    305     MoveElements(index, size_ - index, index + 1);
    306     elements_[index] = new E(element);
    307     size_++;
    308   }
    309 
    310   // Erases the element at the specified index, or aborts the program if the
    311   // index is not in range [0, size()).
    312   void Erase(int index) {
    313     GTEST_CHECK_(0 <= index && index < size_)
    314         << "Invalid Vector index " << index << ": must be in range [0, "
    315         << (size_ - 1) << "].";
    316 
    317     delete elements_[index];
    318     MoveElements(index + 1, size_ - index - 1, index);
    319     size_--;
    320   }
    321 
    322   // Returns the number of elements that satisfy a given predicate.
    323   // The parameter 'predicate' is a Boolean function or functor that
    324   // accepts a 'const E &', where E is the element type.
    325   template <typename P>  // P is the type of the predicate function/functor
    326   int CountIf(P predicate) const {
    327     int count = 0;
    328     for (int i = 0; i < size_; i++) {
    329       if (predicate(*(elements_[i]))) {
    330         count++;
    331       }
    332     }
    333 
    334     return count;
    335   }
    336 
    337   // Applies a function/functor to each element in the Vector.  The
    338   // parameter 'functor' is a function/functor that accepts a 'const
    339   // E &', where E is the element type.  This method does not change
    340   // the elements.
    341   template <typename F>  // F is the type of the function/functor
    342   void ForEach(F functor) const {
    343     for (int i = 0; i < size_; i++) {
    344       functor(*(elements_[i]));
    345     }
    346   }
    347 
    348   // Returns the first node whose element satisfies a given predicate,
    349   // or NULL if none is found.  The parameter 'predicate' is a
    350   // function/functor that accepts a 'const E &', where E is the
    351   // element type.  This method does not change the elements.
    352   template <typename P>  // P is the type of the predicate function/functor.
    353   const E* FindIf(P predicate) const {
    354     for (int i = 0; i < size_; i++) {
    355       if (predicate(*elements_[i])) {
    356         return elements_[i];
    357       }
    358     }
    359     return NULL;
    360   }
    361 
    362   template <typename P>
    363   E* FindIf(P predicate) {
    364     for (int i = 0; i < size_; i++) {
    365       if (predicate(*elements_[i])) {
    366         return elements_[i];
    367       }
    368     }
    369     return NULL;
    370   }
    371 
    372   // Returns the i-th element of the Vector, or aborts the program if i
    373   // is not in range [0, size()).
    374   const E& GetElement(int i) const {
    375     GTEST_CHECK_(0 <= i && i < size_)
    376         << "Invalid Vector index " << i << ": must be in range [0, "
    377         << (size_ - 1) << "].";
    378 
    379     return *(elements_[i]);
    380   }
    381 
    382   // Returns a mutable reference to the i-th element of the Vector, or
    383   // aborts the program if i is not in range [0, size()).
    384   E& GetMutableElement(int i) {
    385     GTEST_CHECK_(0 <= i && i < size_)
    386         << "Invalid Vector index " << i << ": must be in range [0, "
    387         << (size_ - 1) << "].";
    388 
    389     return *(elements_[i]);
    390   }
    391 
    392   // Returns the i-th element of the Vector, or default_value if i is not
    393   // in range [0, size()).
    394   E GetElementOr(int i, E default_value) const {
    395     return (i < 0 || i >= size_) ? default_value : *(elements_[i]);
    396   }
    397 
    398   // Swaps the i-th and j-th elements of the Vector.  Crashes if i or
    399   // j is invalid.
    400   void Swap(int i, int j) {
    401     GTEST_CHECK_(0 <= i && i < size_)
    402         << "Invalid first swap element " << i << ": must be in range [0, "
    403         << (size_ - 1) << "].";
    404     GTEST_CHECK_(0 <= j && j < size_)
    405         << "Invalid second swap element " << j << ": must be in range [0, "
    406         << (size_ - 1) << "].";
    407 
    408     E* const temp = elements_[i];
    409     elements_[i] = elements_[j];
    410     elements_[j] = temp;
    411   }
    412 
    413   // Performs an in-place shuffle of a range of this Vector's nodes.
    414   // 'begin' and 'end' are element indices as an STL-style range;
    415   // i.e. [begin, end) are shuffled, where 'end' == size() means to
    416   // shuffle to the end of the Vector.
    417   void ShuffleRange(internal::Random* random, int begin, int end) {
    418     GTEST_CHECK_(0 <= begin && begin <= size_)
    419         << "Invalid shuffle range start " << begin << ": must be in range [0, "
    420         << size_ << "].";
    421     GTEST_CHECK_(begin <= end && end <= size_)
    422         << "Invalid shuffle range finish " << end << ": must be in range ["
    423         << begin << ", " << size_ << "].";
    424 
    425     // Fisher-Yates shuffle, from
    426     // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
    427     for (int range_width = end - begin; range_width >= 2; range_width--) {
    428       const int last_in_range = begin + range_width - 1;
    429       const int selected = begin + random->Generate(range_width);
    430       Swap(selected, last_in_range);
    431     }
    432   }
    433 
    434   // Performs an in-place shuffle of this Vector's nodes.
    435   void Shuffle(internal::Random* random) {
    436     ShuffleRange(random, 0, size());
    437   }
    438 
    439   // Returns a copy of this Vector.
    440   Vector* Clone() const {
    441     Vector* const clone = new Vector;
    442     clone->Reserve(size_);
    443     for (int i = 0; i < size_; i++) {
    444       clone->PushBack(GetElement(i));
    445     }
    446     return clone;
    447   }
    448 
    449  private:
    450   // Makes sure this Vector's capacity is at least the given value.
    451   void Reserve(int new_capacity) {
    452     if (new_capacity <= capacity_)
    453       return;
    454 
    455     capacity_ = new_capacity;
    456     elements_ = static_cast<E**>(
    457         realloc(elements_, capacity_*sizeof(elements_[0])));
    458   }
    459 
    460   // Grows the buffer if it is not big enough to hold one more element.
    461   void GrowIfNeeded() {
    462     if (size_ < capacity_)
    463       return;
    464 
    465     // Exponential bump-up is necessary to ensure that inserting N
    466     // elements is O(N) instead of O(N^2).  The factor 3/2 means that
    467     // no more than 1/3 of the slots are wasted.
    468     const int new_capacity = 3*(capacity_/2 + 1);
    469     GTEST_CHECK_(new_capacity > capacity_)  // Does the new capacity overflow?
    470         << "Cannot grow a Vector with " << capacity_ << " elements already.";
    471     Reserve(new_capacity);
    472   }
    473 
    474   // Moves the give consecutive elements to a new index in the Vector.
    475   void MoveElements(int source, int count, int dest) {
    476     memmove(elements_ + dest, elements_ + source, count*sizeof(elements_[0]));
    477   }
    478 
    479   E** elements_;
    480   int capacity_;  // The number of elements allocated for elements_.
    481   int size_;      // The number of elements; in the range [0, capacity_].
    482 
    483   // We disallow copying Vector.
    484   GTEST_DISALLOW_COPY_AND_ASSIGN_(Vector);
    485 };  // class Vector
    486 
    487 // A function for deleting an object.  Handy for being used as a
    488 // functor.
    489 template <typename T>
    490 static void Delete(T * x) {
    491   delete x;
    492 }
    493 
    494 // A predicate that checks the key of a TestProperty against a known key.
    495 //
    496 // TestPropertyKeyIs is copyable.
    497 class TestPropertyKeyIs {
    498  public:
    499   // Constructor.
    500   //
    501   // TestPropertyKeyIs has NO default constructor.
    502   explicit TestPropertyKeyIs(const char* key)
    503       : key_(key) {}
    504 
    505   // Returns true iff the test name of test property matches on key_.
    506   bool operator()(const TestProperty& test_property) const {
    507     return String(test_property.key()).Compare(key_) == 0;
    508   }
    509 
    510  private:
    511   String key_;
    512 };
    513 
    514 class TestInfoImpl {
    515  public:
    516   TestInfoImpl(TestInfo* parent, const char* test_case_name,
    517                const char* name, const char* test_case_comment,
    518                const char* comment, TypeId fixture_class_id,
    519                internal::TestFactoryBase* factory);
    520   ~TestInfoImpl();
    521 
    522   // Returns true if this test should run.
    523   bool should_run() const { return should_run_; }
    524 
    525   // Sets the should_run member.
    526   void set_should_run(bool should) { should_run_ = should; }
    527 
    528   // Returns true if this test is disabled. Disabled tests are not run.
    529   bool is_disabled() const { return is_disabled_; }
    530 
    531   // Sets the is_disabled member.
    532   void set_is_disabled(bool is) { is_disabled_ = is; }
    533 
    534   // Returns true if this test matches the filter specified by the user.
    535   bool matches_filter() const { return matches_filter_; }
    536 
    537   // Sets the matches_filter member.
    538   void set_matches_filter(bool matches) { matches_filter_ = matches; }
    539 
    540   // Returns the test case name.
    541   const char* test_case_name() const { return test_case_name_.c_str(); }
    542 
    543   // Returns the test name.
    544   const char* name() const { return name_.c_str(); }
    545 
    546   // Returns the test case comment.
    547   const char* test_case_comment() const { return test_case_comment_.c_str(); }
    548 
    549   // Returns the test comment.
    550   const char* comment() const { return comment_.c_str(); }
    551 
    552   // Returns the ID of the test fixture class.
    553   TypeId fixture_class_id() const { return fixture_class_id_; }
    554 
    555   // Returns the test result.
    556   TestResult* result() { return &result_; }
    557   const TestResult* result() const { return &result_; }
    558 
    559   // Creates the test object, runs it, records its result, and then
    560   // deletes it.
    561   void Run();
    562 
    563   // Clears the test result.
    564   void ClearResult() { result_.Clear(); }
    565 
    566   // Clears the test result in the given TestInfo object.
    567   static void ClearTestResult(TestInfo * test_info) {
    568     test_info->impl()->ClearResult();
    569   }
    570 
    571  private:
    572   // These fields are immutable properties of the test.
    573   TestInfo* const parent_;          // The owner of this object
    574   const String test_case_name_;     // Test case name
    575   const String name_;               // Test name
    576   const String test_case_comment_;  // Test case comment
    577   const String comment_;            // Test comment
    578   const TypeId fixture_class_id_;   // ID of the test fixture class
    579   bool should_run_;                 // True iff this test should run
    580   bool is_disabled_;                // True iff this test is disabled
    581   bool matches_filter_;             // True if this test matches the
    582                                     // user-specified filter.
    583   internal::TestFactoryBase* const factory_;  // The factory that creates
    584                                               // the test object
    585 
    586   // This field is mutable and needs to be reset before running the
    587   // test for the second time.
    588   TestResult result_;
    589 
    590   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl);
    591 };
    592 
    593 // Class UnitTestOptions.
    594 //
    595 // This class contains functions for processing options the user
    596 // specifies when running the tests.  It has only static members.
    597 //
    598 // In most cases, the user can specify an option using either an
    599 // environment variable or a command line flag.  E.g. you can set the
    600 // test filter using either GTEST_FILTER or --gtest_filter.  If both
    601 // the variable and the flag are present, the latter overrides the
    602 // former.
    603 class UnitTestOptions {
    604  public:
    605   // Functions for processing the gtest_output flag.
    606 
    607   // Returns the output format, or "" for normal printed output.
    608   static String GetOutputFormat();
    609 
    610   // Returns the absolute path of the requested output file, or the
    611   // default (test_detail.xml in the original working directory) if
    612   // none was explicitly specified.
    613   static String GetAbsolutePathToOutputFile();
    614 
    615   // Functions for processing the gtest_filter flag.
    616 
    617   // Returns true iff the wildcard pattern matches the string.  The
    618   // first ':' or '\0' character in pattern marks the end of it.
    619   //
    620   // This recursive algorithm isn't very efficient, but is clear and
    621   // works well enough for matching test names, which are short.
    622   static bool PatternMatchesString(const char *pattern, const char *str);
    623 
    624   // Returns true iff the user-specified filter matches the test case
    625   // name and the test name.
    626   static bool FilterMatchesTest(const String &test_case_name,
    627                                 const String &test_name);
    628 
    629 #if GTEST_OS_WINDOWS
    630   // Function for supporting the gtest_catch_exception flag.
    631 
    632   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
    633   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
    634   // This function is useful as an __except condition.
    635   static int GTestShouldProcessSEH(DWORD exception_code);
    636 #endif  // GTEST_OS_WINDOWS
    637 
    638   // Returns true if "name" matches the ':' separated list of glob-style
    639   // filters in "filter".
    640   static bool MatchesFilter(const String& name, const char* filter);
    641 };
    642 
    643 // Returns the current application's name, removing directory path if that
    644 // is present.  Used by UnitTestOptions::GetOutputFile.
    645 FilePath GetCurrentExecutableName();
    646 
    647 // The role interface for getting the OS stack trace as a string.
    648 class OsStackTraceGetterInterface {
    649  public:
    650   OsStackTraceGetterInterface() {}
    651   virtual ~OsStackTraceGetterInterface() {}
    652 
    653   // Returns the current OS stack trace as a String.  Parameters:
    654   //
    655   //   max_depth  - the maximum number of stack frames to be included
    656   //                in the trace.
    657   //   skip_count - the number of top frames to be skipped; doesn't count
    658   //                against max_depth.
    659   virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
    660 
    661   // UponLeavingGTest() should be called immediately before Google Test calls
    662   // user code. It saves some information about the current stack that
    663   // CurrentStackTrace() will use to find and hide Google Test stack frames.
    664   virtual void UponLeavingGTest() = 0;
    665 
    666  private:
    667   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
    668 };
    669 
    670 // A working implementation of the OsStackTraceGetterInterface interface.
    671 class OsStackTraceGetter : public OsStackTraceGetterInterface {
    672  public:
    673   OsStackTraceGetter() : caller_frame_(NULL) {}
    674   virtual String CurrentStackTrace(int max_depth, int skip_count);
    675   virtual void UponLeavingGTest();
    676 
    677   // This string is inserted in place of stack frames that are part of
    678   // Google Test's implementation.
    679   static const char* const kElidedFramesMarker;
    680 
    681  private:
    682   Mutex mutex_;  // protects all internal state
    683 
    684   // We save the stack frame below the frame that calls user code.
    685   // We do this because the address of the frame immediately below
    686   // the user code changes between the call to UponLeavingGTest()
    687   // and any calls to CurrentStackTrace() from within the user code.
    688   void* caller_frame_;
    689 
    690   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
    691 };
    692 
    693 // Information about a Google Test trace point.
    694 struct TraceInfo {
    695   const char* file;
    696   int line;
    697   String message;
    698 };
    699 
    700 // This is the default global test part result reporter used in UnitTestImpl.
    701 // This class should only be used by UnitTestImpl.
    702 class DefaultGlobalTestPartResultReporter
    703   : public TestPartResultReporterInterface {
    704  public:
    705   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
    706   // Implements the TestPartResultReporterInterface. Reports the test part
    707   // result in the current test.
    708   virtual void ReportTestPartResult(const TestPartResult& result);
    709 
    710  private:
    711   UnitTestImpl* const unit_test_;
    712 
    713   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
    714 };
    715 
    716 // This is the default per thread test part result reporter used in
    717 // UnitTestImpl. This class should only be used by UnitTestImpl.
    718 class DefaultPerThreadTestPartResultReporter
    719     : public TestPartResultReporterInterface {
    720  public:
    721   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
    722   // Implements the TestPartResultReporterInterface. The implementation just
    723   // delegates to the current global test part result reporter of *unit_test_.
    724   virtual void ReportTestPartResult(const TestPartResult& result);
    725 
    726  private:
    727   UnitTestImpl* const unit_test_;
    728 
    729   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
    730 };
    731 
    732 // The private implementation of the UnitTest class.  We don't protect
    733 // the methods under a mutex, as this class is not accessible by a
    734 // user and the UnitTest class that delegates work to this class does
    735 // proper locking.
    736 class UnitTestImpl {
    737  public:
    738   explicit UnitTestImpl(UnitTest* parent);
    739   virtual ~UnitTestImpl();
    740 
    741   // There are two different ways to register your own TestPartResultReporter.
    742   // You can register your own repoter to listen either only for test results
    743   // from the current thread or for results from all threads.
    744   // By default, each per-thread test result repoter just passes a new
    745   // TestPartResult to the global test result reporter, which registers the
    746   // test part result for the currently running test.
    747 
    748   // Returns the global test part result reporter.
    749   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
    750 
    751   // Sets the global test part result reporter.
    752   void SetGlobalTestPartResultReporter(
    753       TestPartResultReporterInterface* reporter);
    754 
    755   // Returns the test part result reporter for the current thread.
    756   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
    757 
    758   // Sets the test part result reporter for the current thread.
    759   void SetTestPartResultReporterForCurrentThread(
    760       TestPartResultReporterInterface* reporter);
    761 
    762   // Gets the number of successful test cases.
    763   int successful_test_case_count() const;
    764 
    765   // Gets the number of failed test cases.
    766   int failed_test_case_count() const;
    767 
    768   // Gets the number of all test cases.
    769   int total_test_case_count() const;
    770 
    771   // Gets the number of all test cases that contain at least one test
    772   // that should run.
    773   int test_case_to_run_count() const;
    774 
    775   // Gets the number of successful tests.
    776   int successful_test_count() const;
    777 
    778   // Gets the number of failed tests.
    779   int failed_test_count() const;
    780 
    781   // Gets the number of disabled tests.
    782   int disabled_test_count() const;
    783 
    784   // Gets the number of all tests.
    785   int total_test_count() const;
    786 
    787   // Gets the number of tests that should run.
    788   int test_to_run_count() const;
    789 
    790   // Gets the elapsed time, in milliseconds.
    791   TimeInMillis elapsed_time() const { return elapsed_time_; }
    792 
    793   // Returns true iff the unit test passed (i.e. all test cases passed).
    794   bool Passed() const { return !Failed(); }
    795 
    796   // Returns true iff the unit test failed (i.e. some test case failed
    797   // or something outside of all tests failed).
    798   bool Failed() const {
    799     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
    800   }
    801 
    802   // Gets the i-th test case among all the test cases. i can range from 0 to
    803   // total_test_case_count() - 1. If i is not in that range, returns NULL.
    804   const TestCase* GetTestCase(int i) const {
    805     const int index = test_case_indices_.GetElementOr(i, -1);
    806     return index < 0 ? NULL : test_cases_.GetElement(i);
    807   }
    808 
    809   // Gets the i-th test case among all the test cases. i can range from 0 to
    810   // total_test_case_count() - 1. If i is not in that range, returns NULL.
    811   TestCase* GetMutableTestCase(int i) {
    812     const int index = test_case_indices_.GetElementOr(i, -1);
    813     return index < 0 ? NULL : test_cases_.GetElement(index);
    814   }
    815 
    816   // Provides access to the event listener list.
    817   TestEventListeners* listeners() { return &listeners_; }
    818 
    819   // Returns the TestResult for the test that's currently running, or
    820   // the TestResult for the ad hoc test if no test is running.
    821   TestResult* current_test_result();
    822 
    823   // Returns the TestResult for the ad hoc test.
    824   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
    825 
    826   // Sets the OS stack trace getter.
    827   //
    828   // Does nothing if the input and the current OS stack trace getter
    829   // are the same; otherwise, deletes the old getter and makes the
    830   // input the current getter.
    831   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
    832 
    833   // Returns the current OS stack trace getter if it is not NULL;
    834   // otherwise, creates an OsStackTraceGetter, makes it the current
    835   // getter, and returns it.
    836   OsStackTraceGetterInterface* os_stack_trace_getter();
    837 
    838   // Returns the current OS stack trace as a String.
    839   //
    840   // The maximum number of stack frames to be included is specified by
    841   // the gtest_stack_trace_depth flag.  The skip_count parameter
    842   // specifies the number of top frames to be skipped, which doesn't
    843   // count against the number of frames to be included.
    844   //
    845   // For example, if Foo() calls Bar(), which in turn calls
    846   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
    847   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
    848   String CurrentOsStackTraceExceptTop(int skip_count);
    849 
    850   // Finds and returns a TestCase with the given name.  If one doesn't
    851   // exist, creates one and returns it.
    852   //
    853   // Arguments:
    854   //
    855   //   test_case_name: name of the test case
    856   //   set_up_tc:      pointer to the function that sets up the test case
    857   //   tear_down_tc:   pointer to the function that tears down the test case
    858   TestCase* GetTestCase(const char* test_case_name,
    859                         const char* comment,
    860                         Test::SetUpTestCaseFunc set_up_tc,
    861                         Test::TearDownTestCaseFunc tear_down_tc);
    862 
    863   // Adds a TestInfo to the unit test.
    864   //
    865   // Arguments:
    866   //
    867   //   set_up_tc:    pointer to the function that sets up the test case
    868   //   tear_down_tc: pointer to the function that tears down the test case
    869   //   test_info:    the TestInfo object
    870   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
    871                    Test::TearDownTestCaseFunc tear_down_tc,
    872                    TestInfo * test_info) {
    873     // In order to support thread-safe death tests, we need to
    874     // remember the original working directory when the test program
    875     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
    876     // the user may have changed the current directory before calling
    877     // RUN_ALL_TESTS().  Therefore we capture the current directory in
    878     // AddTestInfo(), which is called to register a TEST or TEST_F
    879     // before main() is reached.
    880     if (original_working_dir_.IsEmpty()) {
    881       original_working_dir_.Set(FilePath::GetCurrentDir());
    882       GTEST_CHECK_(!original_working_dir_.IsEmpty())
    883           << "Failed to get the current working directory.";
    884     }
    885 
    886     GetTestCase(test_info->test_case_name(),
    887                 test_info->test_case_comment(),
    888                 set_up_tc,
    889                 tear_down_tc)->AddTestInfo(test_info);
    890   }
    891 
    892 #if GTEST_HAS_PARAM_TEST
    893   // Returns ParameterizedTestCaseRegistry object used to keep track of
    894   // value-parameterized tests and instantiate and register them.
    895   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
    896     return parameterized_test_registry_;
    897   }
    898 #endif  // GTEST_HAS_PARAM_TEST
    899 
    900   // Sets the TestCase object for the test that's currently running.
    901   void set_current_test_case(TestCase* current_test_case) {
    902     current_test_case_ = current_test_case;
    903   }
    904 
    905   // Sets the TestInfo object for the test that's currently running.  If
    906   // current_test_info is NULL, the assertion results will be stored in
    907   // ad_hoc_test_result_.
    908   void set_current_test_info(TestInfo* current_test_info) {
    909     current_test_info_ = current_test_info;
    910   }
    911 
    912   // Registers all parameterized tests defined using TEST_P and
    913   // INSTANTIATE_TEST_P, creating regular tests for each test/parameter
    914   // combination. This method can be called more then once; it has
    915   // guards protecting from registering the tests more then once.
    916   // If value-parameterized tests are disabled, RegisterParameterizedTests
    917   // is present but does nothing.
    918   void RegisterParameterizedTests();
    919 
    920   // Runs all tests in this UnitTest object, prints the result, and
    921   // returns 0 if all tests are successful, or 1 otherwise.  If any
    922   // exception is thrown during a test on Windows, this test is
    923   // considered to be failed, but the rest of the tests will still be
    924   // run.  (We disable exceptions on Linux and Mac OS X, so the issue
    925   // doesn't apply there.)
    926   int RunAllTests();
    927 
    928   // Clears the results of all tests, including the ad hoc test.
    929   void ClearResult() {
    930     test_cases_.ForEach(TestCase::ClearTestCaseResult);
    931     ad_hoc_test_result_.Clear();
    932   }
    933 
    934   enum ReactionToSharding {
    935     HONOR_SHARDING_PROTOCOL,
    936     IGNORE_SHARDING_PROTOCOL
    937   };
    938 
    939   // Matches the full name of each test against the user-specified
    940   // filter to decide whether the test should run, then records the
    941   // result in each TestCase and TestInfo object.
    942   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
    943   // based on sharding variables in the environment.
    944   // Returns the number of tests that should run.
    945   int FilterTests(ReactionToSharding shard_tests);
    946 
    947   // Prints the names of the tests matching the user-specified filter flag.
    948   void ListTestsMatchingFilter();
    949 
    950   const TestCase* current_test_case() const { return current_test_case_; }
    951   TestInfo* current_test_info() { return current_test_info_; }
    952   const TestInfo* current_test_info() const { return current_test_info_; }
    953 
    954   // Returns the vector of environments that need to be set-up/torn-down
    955   // before/after the tests are run.
    956   internal::Vector<Environment*>* environments() { return &environments_; }
    957   internal::Vector<Environment*>* environments_in_reverse_order() {
    958     return &environments_in_reverse_order_;
    959   }
    960 
    961   // Getters for the per-thread Google Test trace stack.
    962   internal::Vector<TraceInfo>* gtest_trace_stack() {
    963     return gtest_trace_stack_.pointer();
    964   }
    965   const internal::Vector<TraceInfo>* gtest_trace_stack() const {
    966     return gtest_trace_stack_.pointer();
    967   }
    968 
    969 #if GTEST_HAS_DEATH_TEST
    970   void InitDeathTestSubprocessControlInfo() {
    971     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
    972   }
    973   // Returns a pointer to the parsed --gtest_internal_run_death_test
    974   // flag, or NULL if that flag was not specified.
    975   // This information is useful only in a death test child process.
    976   // Must not be called before a call to InitGoogleTest.
    977   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
    978     return internal_run_death_test_flag_.get();
    979   }
    980 
    981   // Returns a pointer to the current death test factory.
    982   internal::DeathTestFactory* death_test_factory() {
    983     return death_test_factory_.get();
    984   }
    985 
    986   void SuppressTestEventsIfInSubprocess();
    987 
    988   friend class ReplaceDeathTestFactory;
    989 #endif  // GTEST_HAS_DEATH_TEST
    990 
    991   // Initializes the event listener performing XML output as specified by
    992   // UnitTestOptions. Must not be called before InitGoogleTest.
    993   void ConfigureXmlOutput();
    994 
    995   // Performs initialization dependent upon flag values obtained in
    996   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
    997   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
    998   // this function is also called from RunAllTests.  Since this function can be
    999   // called more than once, it has to be idempotent.
   1000   void PostFlagParsingInit();
   1001 
   1002   // Gets the random seed used at the start of the current test iteration.
   1003   int random_seed() const { return random_seed_; }
   1004 
   1005   // Gets the random number generator.
   1006   internal::Random* random() { return &random_; }
   1007 
   1008   // Shuffles all test cases, and the tests within each test case,
   1009   // making sure that death tests are still run first.
   1010   void ShuffleTests();
   1011 
   1012   // Restores the test cases and tests to their order before the first shuffle.
   1013   void UnshuffleTests();
   1014 
   1015  private:
   1016   friend class ::testing::UnitTest;
   1017 
   1018   // The UnitTest object that owns this implementation object.
   1019   UnitTest* const parent_;
   1020 
   1021   // The working directory when the first TEST() or TEST_F() was
   1022   // executed.
   1023   internal::FilePath original_working_dir_;
   1024 
   1025   // The default test part result reporters.
   1026   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
   1027   DefaultPerThreadTestPartResultReporter
   1028       default_per_thread_test_part_result_reporter_;
   1029 
   1030   // Points to (but doesn't own) the global test part result reporter.
   1031   TestPartResultReporterInterface* global_test_part_result_repoter_;
   1032 
   1033   // Protects read and write access to global_test_part_result_reporter_.
   1034   internal::Mutex global_test_part_result_reporter_mutex_;
   1035 
   1036   // Points to (but doesn't own) the per-thread test part result reporter.
   1037   internal::ThreadLocal<TestPartResultReporterInterface*>
   1038       per_thread_test_part_result_reporter_;
   1039 
   1040   // The vector of environments that need to be set-up/torn-down
   1041   // before/after the tests are run.  environments_in_reverse_order_
   1042   // simply mirrors environments_ in reverse order.
   1043   internal::Vector<Environment*> environments_;
   1044   internal::Vector<Environment*> environments_in_reverse_order_;
   1045 
   1046   // The vector of TestCases in their original order.  It owns the
   1047   // elements in the vector.
   1048   internal::Vector<TestCase*> test_cases_;
   1049 
   1050   // Provides a level of indirection for the test case list to allow
   1051   // easy shuffling and restoring the test case order.  The i-th
   1052   // element of this vector is the index of the i-th test case in the
   1053   // shuffled order.
   1054   internal::Vector<int> test_case_indices_;
   1055 
   1056 #if GTEST_HAS_PARAM_TEST
   1057   // ParameterizedTestRegistry object used to register value-parameterized
   1058   // tests.
   1059   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
   1060 
   1061   // Indicates whether RegisterParameterizedTests() has been called already.
   1062   bool parameterized_tests_registered_;
   1063 #endif  // GTEST_HAS_PARAM_TEST
   1064 
   1065   // Index of the last death test case registered.  Initially -1.
   1066   int last_death_test_case_;
   1067 
   1068   // This points to the TestCase for the currently running test.  It
   1069   // changes as Google Test goes through one test case after another.
   1070   // When no test is running, this is set to NULL and Google Test
   1071   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
   1072   TestCase* current_test_case_;
   1073 
   1074   // This points to the TestInfo for the currently running test.  It
   1075   // changes as Google Test goes through one test after another.  When
   1076   // no test is running, this is set to NULL and Google Test stores
   1077   // assertion results in ad_hoc_test_result_.  Initially NULL.
   1078   TestInfo* current_test_info_;
   1079 
   1080   // Normally, a user only writes assertions inside a TEST or TEST_F,
   1081   // or inside a function called by a TEST or TEST_F.  Since Google
   1082   // Test keeps track of which test is current running, it can
   1083   // associate such an assertion with the test it belongs to.
   1084   //
   1085   // If an assertion is encountered when no TEST or TEST_F is running,
   1086   // Google Test attributes the assertion result to an imaginary "ad hoc"
   1087   // test, and records the result in ad_hoc_test_result_.
   1088   TestResult ad_hoc_test_result_;
   1089 
   1090   // The list of event listeners that can be used to track events inside
   1091   // Google Test.
   1092   TestEventListeners listeners_;
   1093 
   1094   // The OS stack trace getter.  Will be deleted when the UnitTest
   1095   // object is destructed.  By default, an OsStackTraceGetter is used,
   1096   // but the user can set this field to use a custom getter if that is
   1097   // desired.
   1098   OsStackTraceGetterInterface* os_stack_trace_getter_;
   1099 
   1100   // True iff PostFlagParsingInit() has been called.
   1101   bool post_flag_parse_init_performed_;
   1102 
   1103   // The random number seed used at the beginning of the test run.
   1104   int random_seed_;
   1105 
   1106   // Our random number generator.
   1107   internal::Random random_;
   1108 
   1109   // How long the test took to run, in milliseconds.
   1110   TimeInMillis elapsed_time_;
   1111 
   1112 #if GTEST_HAS_DEATH_TEST
   1113   // The decomposed components of the gtest_internal_run_death_test flag,
   1114   // parsed when RUN_ALL_TESTS is called.
   1115   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
   1116   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
   1117 #endif  // GTEST_HAS_DEATH_TEST
   1118 
   1119   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
   1120   internal::ThreadLocal<internal::Vector<TraceInfo> > gtest_trace_stack_;
   1121 
   1122   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
   1123 };  // class UnitTestImpl
   1124 
   1125 // Convenience function for accessing the global UnitTest
   1126 // implementation object.
   1127 inline UnitTestImpl* GetUnitTestImpl() {
   1128   return UnitTest::GetInstance()->impl();
   1129 }
   1130 
   1131 // Internal helper functions for implementing the simple regular
   1132 // expression matcher.
   1133 bool IsInSet(char ch, const char* str);
   1134 bool IsDigit(char ch);
   1135 bool IsPunct(char ch);
   1136 bool IsRepeat(char ch);
   1137 bool IsWhiteSpace(char ch);
   1138 bool IsWordChar(char ch);
   1139 bool IsValidEscape(char ch);
   1140 bool AtomMatchesChar(bool escaped, char pattern, char ch);
   1141 bool ValidateRegex(const char* regex);
   1142 bool MatchRegexAtHead(const char* regex, const char* str);
   1143 bool MatchRepetitionAndRegexAtHead(
   1144     bool escaped, char ch, char repeat, const char* regex, const char* str);
   1145 bool MatchRegexAnywhere(const char* regex, const char* str);
   1146 
   1147 // Parses the command line for Google Test flags, without initializing
   1148 // other parts of Google Test.
   1149 void ParseGoogleTestFlagsOnly(int* argc, char** argv);
   1150 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
   1151 
   1152 #if GTEST_HAS_DEATH_TEST
   1153 
   1154 // Returns the message describing the last system error, regardless of the
   1155 // platform.
   1156 String GetLastErrnoDescription();
   1157 
   1158 #if GTEST_OS_WINDOWS
   1159 // Provides leak-safe Windows kernel handle ownership.
   1160 class AutoHandle {
   1161  public:
   1162   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
   1163   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
   1164 
   1165   ~AutoHandle() { Reset(); }
   1166 
   1167   HANDLE Get() const { return handle_; }
   1168   void Reset() { Reset(INVALID_HANDLE_VALUE); }
   1169   void Reset(HANDLE handle) {
   1170     if (handle != handle_) {
   1171       if (handle_ != INVALID_HANDLE_VALUE)
   1172         ::CloseHandle(handle_);
   1173       handle_ = handle;
   1174     }
   1175   }
   1176 
   1177  private:
   1178   HANDLE handle_;
   1179 
   1180   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
   1181 };
   1182 #endif  // GTEST_OS_WINDOWS
   1183 
   1184 // Attempts to parse a string into a positive integer pointed to by the
   1185 // number parameter.  Returns true if that is possible.
   1186 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
   1187 // it here.
   1188 template <typename Integer>
   1189 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
   1190   // Fail fast if the given string does not begin with a digit;
   1191   // this bypasses strtoXXX's "optional leading whitespace and plus
   1192   // or minus sign" semantics, which are undesirable here.
   1193   if (str.empty() || !isdigit(str[0])) {
   1194     return false;
   1195   }
   1196   errno = 0;
   1197 
   1198   char* end;
   1199   // BiggestConvertible is the largest integer type that system-provided
   1200   // string-to-number conversion routines can return.
   1201 #if GTEST_OS_WINDOWS && !defined(__GNUC__)
   1202   // MSVC and C++ Builder define __int64 instead of the standard long long.
   1203   typedef unsigned __int64 BiggestConvertible;
   1204   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
   1205 #else
   1206   typedef unsigned long long BiggestConvertible;  // NOLINT
   1207   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
   1208 #endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
   1209   const bool parse_success = *end == '\0' && errno == 0;
   1210 
   1211   // TODO(vladl (at) google.com): Convert this to compile time assertion when it is
   1212   // available.
   1213   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
   1214 
   1215   const Integer result = static_cast<Integer>(parsed);
   1216   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
   1217     *number = result;
   1218     return true;
   1219   }
   1220   return false;
   1221 }
   1222 #endif  // GTEST_HAS_DEATH_TEST
   1223 
   1224 // TestResult contains some private methods that should be hidden from
   1225 // Google Test user but are required for testing. This class allow our tests
   1226 // to access them.
   1227 class TestResultAccessor {
   1228  public:
   1229   static void RecordProperty(TestResult* test_result,
   1230                              const TestProperty& property) {
   1231     test_result->RecordProperty(property);
   1232   }
   1233 
   1234   static void ClearTestPartResults(TestResult* test_result) {
   1235     test_result->ClearTestPartResults();
   1236   }
   1237 
   1238   static const Vector<testing::TestPartResult>& test_part_results(
   1239       const TestResult& test_result) {
   1240     return test_result.test_part_results();
   1241   }
   1242 };
   1243 
   1244 }  // namespace internal
   1245 }  // namespace testing
   1246 
   1247 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
   1248