Home | History | Annotate | Download | only in internal
      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 // Authors: wan (at) google.com (Zhanyong Wan)
     31 //
     32 // Low-level types and utilities for porting Google Test to various
     33 // platforms.  All macros ending with _ and symbols defined in an
     34 // internal namespace are subject to change without notice.  Code
     35 // outside Google Test MUST NOT USE THEM DIRECTLY.  Macros that don't
     36 // end with _ are part of Google Test's public API and can be used by
     37 // code outside Google Test.
     38 //
     39 // This file is fundamental to Google Test.  All other Google Test source
     40 // files are expected to #include this.  Therefore, it cannot #include
     41 // any other Google Test header.
     42 
     43 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
     44 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
     45 
     46 // Environment-describing macros
     47 // -----------------------------
     48 //
     49 // Google Test can be used in many different environments.  Macros in
     50 // this section tell Google Test what kind of environment it is being
     51 // used in, such that Google Test can provide environment-specific
     52 // features and implementations.
     53 //
     54 // Google Test tries to automatically detect the properties of its
     55 // environment, so users usually don't need to worry about these
     56 // macros.  However, the automatic detection is not perfect.
     57 // Sometimes it's necessary for a user to define some of the following
     58 // macros in the build script to override Google Test's decisions.
     59 //
     60 // If the user doesn't define a macro in the list, Google Test will
     61 // provide a default definition.  After this header is #included, all
     62 // macros in this list will be defined to either 1 or 0.
     63 //
     64 // Notes to maintainers:
     65 //   - Each macro here is a user-tweakable knob; do not grow the list
     66 //     lightly.
     67 //   - Use #if to key off these macros.  Don't use #ifdef or "#if
     68 //     defined(...)", which will not work as these macros are ALWAYS
     69 //     defined.
     70 //
     71 //   GTEST_HAS_CLONE          - Define it to 1/0 to indicate that clone(2)
     72 //                              is/isn't available.
     73 //   GTEST_HAS_EXCEPTIONS     - Define it to 1/0 to indicate that exceptions
     74 //                              are enabled.
     75 //   GTEST_HAS_GLOBAL_STRING  - Define it to 1/0 to indicate that ::string
     76 //                              is/isn't available (some systems define
     77 //                              ::string, which is different to std::string).
     78 //   GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
     79 //                              is/isn't available (some systems define
     80 //                              ::wstring, which is different to std::wstring).
     81 //   GTEST_HAS_POSIX_RE       - Define it to 1/0 to indicate that POSIX regular
     82 //                              expressions are/aren't available.
     83 //   GTEST_HAS_PTHREAD        - Define it to 1/0 to indicate that <pthread.h>
     84 //                              is/isn't available.
     85 //   GTEST_HAS_RTTI           - Define it to 1/0 to indicate that RTTI is/isn't
     86 //                              enabled.
     87 //   GTEST_HAS_STD_WSTRING    - Define it to 1/0 to indicate that
     88 //                              std::wstring does/doesn't work (Google Test can
     89 //                              be used where std::wstring is unavailable).
     90 //   GTEST_HAS_TR1_TUPLE      - Define it to 1/0 to indicate tr1::tuple
     91 //                              is/isn't available.
     92 //   GTEST_HAS_SEH            - Define it to 1/0 to indicate whether the
     93 //                              compiler supports Microsoft's "Structured
     94 //                              Exception Handling".
     95 //   GTEST_HAS_STREAM_REDIRECTION
     96 //                            - Define it to 1/0 to indicate whether the
     97 //                              platform supports I/O stream redirection using
     98 //                              dup() and dup2().
     99 //   GTEST_USE_OWN_TR1_TUPLE  - Define it to 1/0 to indicate whether Google
    100 //                              Test's own tr1 tuple implementation should be
    101 //                              used.  Unused when the user sets
    102 //                              GTEST_HAS_TR1_TUPLE to 0.
    103 //   GTEST_LANG_CXX11         - Define it to 1/0 to indicate that Google Test
    104 //                              is building in C++11/C++98 mode.
    105 //   GTEST_LINKED_AS_SHARED_LIBRARY
    106 //                            - Define to 1 when compiling tests that use
    107 //                              Google Test as a shared library (known as
    108 //                              DLL on Windows).
    109 //   GTEST_CREATE_SHARED_LIBRARY
    110 //                            - Define to 1 when compiling Google Test itself
    111 //                              as a shared library.
    112 
    113 // Platform-indicating macros
    114 // --------------------------
    115 //
    116 // Macros indicating the platform on which Google Test is being used
    117 // (a macro is defined to 1 if compiled on the given platform;
    118 // otherwise UNDEFINED -- it's never defined to 0.).  Google Test
    119 // defines these macros automatically.  Code outside Google Test MUST
    120 // NOT define them.
    121 //
    122 //   GTEST_OS_AIX      - IBM AIX
    123 //   GTEST_OS_CYGWIN   - Cygwin
    124 //   GTEST_OS_FREEBSD  - FreeBSD
    125 //   GTEST_OS_HPUX     - HP-UX
    126 //   GTEST_OS_LINUX    - Linux
    127 //     GTEST_OS_LINUX_ANDROID - Google Android
    128 //   GTEST_OS_MAC      - Mac OS X
    129 //     GTEST_OS_IOS    - iOS
    130 //   GTEST_OS_NACL     - Google Native Client (NaCl)
    131 //   GTEST_OS_OPENBSD  - OpenBSD
    132 //   GTEST_OS_QNX      - QNX
    133 //   GTEST_OS_SOLARIS  - Sun Solaris
    134 //   GTEST_OS_SYMBIAN  - Symbian
    135 //   GTEST_OS_WINDOWS  - Windows (Desktop, MinGW, or Mobile)
    136 //     GTEST_OS_WINDOWS_DESKTOP  - Windows Desktop
    137 //     GTEST_OS_WINDOWS_MINGW    - MinGW
    138 //     GTEST_OS_WINDOWS_MOBILE   - Windows Mobile
    139 //     GTEST_OS_WINDOWS_PHONE    - Windows Phone
    140 //     GTEST_OS_WINDOWS_RT       - Windows Store App/WinRT
    141 //   GTEST_OS_ZOS      - z/OS
    142 //
    143 // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
    144 // most stable support.  Since core members of the Google Test project
    145 // don't have access to other platforms, support for them may be less
    146 // stable.  If you notice any problems on your platform, please notify
    147 // googletestframework (at) googlegroups.com (patches for fixing them are
    148 // even more welcome!).
    149 //
    150 // It is possible that none of the GTEST_OS_* macros are defined.
    151 
    152 // Feature-indicating macros
    153 // -------------------------
    154 //
    155 // Macros indicating which Google Test features are available (a macro
    156 // is defined to 1 if the corresponding feature is supported;
    157 // otherwise UNDEFINED -- it's never defined to 0.).  Google Test
    158 // defines these macros automatically.  Code outside Google Test MUST
    159 // NOT define them.
    160 //
    161 // These macros are public so that portable tests can be written.
    162 // Such tests typically surround code using a feature with an #if
    163 // which controls that code.  For example:
    164 //
    165 // #if GTEST_HAS_DEATH_TEST
    166 //   EXPECT_DEATH(DoSomethingDeadly());
    167 // #endif
    168 //
    169 //   GTEST_HAS_COMBINE      - the Combine() function (for value-parameterized
    170 //                            tests)
    171 //   GTEST_HAS_DEATH_TEST   - death tests
    172 //   GTEST_HAS_PARAM_TEST   - value-parameterized tests
    173 //   GTEST_HAS_TYPED_TEST   - typed tests
    174 //   GTEST_HAS_TYPED_TEST_P - type-parameterized tests
    175 //   GTEST_IS_THREADSAFE    - Google Test is thread-safe.
    176 //   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used. Do not confuse with
    177 //                            GTEST_HAS_POSIX_RE (see above) which users can
    178 //                            define themselves.
    179 //   GTEST_USES_SIMPLE_RE   - our own simple regex is used;
    180 //                            the above two are mutually exclusive.
    181 //   GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
    182 
    183 // Misc public macros
    184 // ------------------
    185 //
    186 //   GTEST_FLAG(flag_name)  - references the variable corresponding to
    187 //                            the given Google Test flag.
    188 
    189 // Internal utilities
    190 // ------------------
    191 //
    192 // The following macros and utilities are for Google Test's INTERNAL
    193 // use only.  Code outside Google Test MUST NOT USE THEM DIRECTLY.
    194 //
    195 // Macros for basic C++ coding:
    196 //   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
    197 //   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a
    198 //                              variable don't have to be used.
    199 //   GTEST_DISALLOW_ASSIGN_   - disables operator=.
    200 //   GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
    201 //   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.
    202 //   GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
    203 //                                        suppressed (constant conditional).
    204 //   GTEST_INTENTIONAL_CONST_COND_POP_  - finish code section where MSVC C4127
    205 //                                        is suppressed.
    206 //
    207 // C++11 feature wrappers:
    208 //
    209 //   testing::internal::move  - portability wrapper for std::move.
    210 //
    211 // Synchronization:
    212 //   Mutex, MutexLock, ThreadLocal, GetThreadCount()
    213 //                            - synchronization primitives.
    214 //
    215 // Template meta programming:
    216 //   is_pointer     - as in TR1; needed on Symbian and IBM XL C/C++ only.
    217 //   IteratorTraits - partial implementation of std::iterator_traits, which
    218 //                    is not available in libCstd when compiled with Sun C++.
    219 //
    220 // Smart pointers:
    221 //   scoped_ptr     - as in TR2.
    222 //
    223 // Regular expressions:
    224 //   RE             - a simple regular expression class using the POSIX
    225 //                    Extended Regular Expression syntax on UNIX-like
    226 //                    platforms, or a reduced regular exception syntax on
    227 //                    other platforms, including Windows.
    228 //
    229 // Logging:
    230 //   GTEST_LOG_()   - logs messages at the specified severity level.
    231 //   LogToStderr()  - directs all log messages to stderr.
    232 //   FlushInfoLog() - flushes informational log messages.
    233 //
    234 // Stdout and stderr capturing:
    235 //   CaptureStdout()     - starts capturing stdout.
    236 //   GetCapturedStdout() - stops capturing stdout and returns the captured
    237 //                         string.
    238 //   CaptureStderr()     - starts capturing stderr.
    239 //   GetCapturedStderr() - stops capturing stderr and returns the captured
    240 //                         string.
    241 //
    242 // Integer types:
    243 //   TypeWithSize   - maps an integer to a int type.
    244 //   Int32, UInt32, Int64, UInt64, TimeInMillis
    245 //                  - integers of known sizes.
    246 //   BiggestInt     - the biggest signed integer type.
    247 //
    248 // Command-line utilities:
    249 //   GTEST_DECLARE_*()  - declares a flag.
    250 //   GTEST_DEFINE_*()   - defines a flag.
    251 //   GetInjectableArgvs() - returns the command line as a vector of strings.
    252 //
    253 // Environment variable utilities:
    254 //   GetEnv()             - gets the value of an environment variable.
    255 //   BoolFromGTestEnv()   - parses a bool environment variable.
    256 //   Int32FromGTestEnv()  - parses an Int32 environment variable.
    257 //   StringFromGTestEnv() - parses a string environment variable.
    258 
    259 #include <ctype.h>   // for isspace, etc
    260 #include <stddef.h>  // for ptrdiff_t
    261 #include <stdlib.h>
    262 #include <stdio.h>
    263 #include <string.h>
    264 #ifndef _WIN32_WCE
    265 # include <sys/types.h>
    266 # include <sys/stat.h>
    267 #endif  // !_WIN32_WCE
    268 
    269 #if defined __APPLE__
    270 # include <AvailabilityMacros.h>
    271 # include <TargetConditionals.h>
    272 #endif
    273 
    274 #include <algorithm>  // NOLINT
    275 #include <iostream>  // NOLINT
    276 #include <sstream>  // NOLINT
    277 #include <string>  // NOLINT
    278 #include <utility>
    279 #include <vector>  // NOLINT
    280 
    281 #include "gtest/internal/gtest-port-arch.h"
    282 #include "gtest/internal/custom/gtest-port.h"
    283 
    284 #if !defined(GTEST_DEV_EMAIL_)
    285 # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
    286 # define GTEST_FLAG_PREFIX_ "gtest_"
    287 # define GTEST_FLAG_PREFIX_DASH_ "gtest-"
    288 # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
    289 # define GTEST_NAME_ "Google Test"
    290 # define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/"
    291 #endif  // !defined(GTEST_DEV_EMAIL_)
    292 
    293 #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
    294 # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
    295 #endif  // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
    296 
    297 // Determines the version of gcc that is used to compile this.
    298 #ifdef __GNUC__
    299 // 40302 means version 4.3.2.
    300 # define GTEST_GCC_VER_ \
    301     (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
    302 #endif  // __GNUC__
    303 
    304 // Macros for disabling Microsoft Visual C++ warnings.
    305 //
    306 //   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
    307 //   /* code that triggers warnings C4800 and C4385 */
    308 //   GTEST_DISABLE_MSC_WARNINGS_POP_()
    309 #if _MSC_VER >= 1500
    310 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
    311     __pragma(warning(push))                        \
    312     __pragma(warning(disable: warnings))
    313 # define GTEST_DISABLE_MSC_WARNINGS_POP_()          \
    314     __pragma(warning(pop))
    315 #else
    316 // Older versions of MSVC don't have __pragma.
    317 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
    318 # define GTEST_DISABLE_MSC_WARNINGS_POP_()
    319 #endif
    320 
    321 #ifndef GTEST_LANG_CXX11
    322 // gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when
    323 // -std={c,gnu}++{0x,11} is passed.  The C++11 standard specifies a
    324 // value for __cplusplus, and recent versions of clang, gcc, and
    325 // probably other compilers set that too in C++11 mode.
    326 # if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L
    327 // Compiling in at least C++11 mode.
    328 #  define GTEST_LANG_CXX11 1
    329 # else
    330 #  define GTEST_LANG_CXX11 0
    331 # endif
    332 #endif
    333 
    334 // Distinct from C++11 language support, some environments don't provide
    335 // proper C++11 library support. Notably, it's possible to build in
    336 // C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++
    337 // with no C++11 support.
    338 //
    339 // libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__
    340 // 20110325, but maintenance releases in the 4.4 and 4.5 series followed
    341 // this date, so check for those versions by their date stamps.
    342 // https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning
    343 #if GTEST_LANG_CXX11 && \
    344     (!defined(__GLIBCXX__) || ( \
    345         __GLIBCXX__ >= 20110325ul &&  /* GCC >= 4.6.0 */ \
    346         /* Blacklist of patch releases of older branches: */ \
    347         __GLIBCXX__ != 20110416ul &&  /* GCC 4.4.6 */ \
    348         __GLIBCXX__ != 20120313ul &&  /* GCC 4.4.7 */ \
    349         __GLIBCXX__ != 20110428ul &&  /* GCC 4.5.3 */ \
    350         __GLIBCXX__ != 20120702ul))   /* GCC 4.5.4 */
    351 # define GTEST_STDLIB_CXX11 1
    352 #endif
    353 
    354 // Only use C++11 library features if the library provides them.
    355 #if GTEST_STDLIB_CXX11
    356 # define GTEST_HAS_STD_BEGIN_AND_END_ 1
    357 # define GTEST_HAS_STD_FORWARD_LIST_ 1
    358 # define GTEST_HAS_STD_FUNCTION_ 1
    359 # define GTEST_HAS_STD_INITIALIZER_LIST_ 1
    360 # define GTEST_HAS_STD_MOVE_ 1
    361 # define GTEST_HAS_STD_UNIQUE_PTR_ 1
    362 # define GTEST_HAS_STD_SHARED_PTR_ 1
    363 #endif
    364 
    365 // C++11 specifies that <tuple> provides std::tuple.
    366 // Some platforms still might not have it, however.
    367 #if GTEST_LANG_CXX11
    368 # define GTEST_HAS_STD_TUPLE_ 1
    369 # if defined(__clang__)
    370 // Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include
    371 #  if defined(__has_include) && !__has_include(<tuple>)
    372 #   undef GTEST_HAS_STD_TUPLE_
    373 #  endif
    374 # elif defined(_MSC_VER)
    375 // Inspired by boost/config/stdlib/dinkumware.hpp
    376 #  if defined(_CPPLIB_VER) && _CPPLIB_VER < 520
    377 #   undef GTEST_HAS_STD_TUPLE_
    378 #  endif
    379 # elif defined(__GLIBCXX__)
    380 // Inspired by boost/config/stdlib/libstdcpp3.hpp,
    381 // http://gcc.gnu.org/gcc-4.2/changes.html and
    382 // http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x
    383 #  if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
    384 #   undef GTEST_HAS_STD_TUPLE_
    385 #  endif
    386 # endif
    387 #endif
    388 
    389 // Brings in definitions for functions used in the testing::internal::posix
    390 // namespace (read, write, close, chdir, isatty, stat). We do not currently
    391 // use them on Windows Mobile.
    392 #if GTEST_OS_WINDOWS
    393 # if !GTEST_OS_WINDOWS_MOBILE
    394 #  include <direct.h>
    395 #  include <io.h>
    396 # endif
    397 // In order to avoid having to include <windows.h>, use forward declaration
    398 // assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
    399 // This assumption is verified by
    400 // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
    401 struct _RTL_CRITICAL_SECTION;
    402 #else
    403 // This assumes that non-Windows OSes provide unistd.h. For OSes where this
    404 // is not the case, we need to include headers that provide the functions
    405 // mentioned above.
    406 # include <unistd.h>
    407 # include <strings.h>
    408 #endif  // GTEST_OS_WINDOWS
    409 
    410 #if GTEST_OS_LINUX_ANDROID
    411 // Used to define __ANDROID_API__ matching the target NDK API level.
    412 #  include <android/api-level.h>  // NOLINT
    413 #endif
    414 
    415 // Defines this to true iff Google Test can use POSIX regular expressions.
    416 #ifndef GTEST_HAS_POSIX_RE
    417 # if GTEST_OS_LINUX_ANDROID
    418 // On Android, <regex.h> is only available starting with Gingerbread.
    419 #  define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
    420 # else
    421 #  define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS)
    422 # endif
    423 #endif
    424 
    425 #if GTEST_USES_PCRE
    426 // The appropriate headers have already been included.
    427 
    428 #elif GTEST_HAS_POSIX_RE
    429 
    430 // On some platforms, <regex.h> needs someone to define size_t, and
    431 // won't compile otherwise.  We can #include it here as we already
    432 // included <stdlib.h>, which is guaranteed to define size_t through
    433 // <stddef.h>.
    434 # include <regex.h>  // NOLINT
    435 
    436 # define GTEST_USES_POSIX_RE 1
    437 
    438 #elif GTEST_OS_WINDOWS
    439 
    440 // <regex.h> is not available on Windows.  Use our own simple regex
    441 // implementation instead.
    442 # define GTEST_USES_SIMPLE_RE 1
    443 
    444 #else
    445 
    446 // <regex.h> may not be available on this platform.  Use our own
    447 // simple regex implementation instead.
    448 # define GTEST_USES_SIMPLE_RE 1
    449 
    450 #endif  // GTEST_USES_PCRE
    451 
    452 #ifndef GTEST_HAS_EXCEPTIONS
    453 // The user didn't tell us whether exceptions are enabled, so we need
    454 // to figure it out.
    455 # if defined(_MSC_VER) || defined(__BORLANDC__)
    456 // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
    457 // macro to enable exceptions, so we'll do the same.
    458 // Assumes that exceptions are enabled by default.
    459 #  ifndef _HAS_EXCEPTIONS
    460 #   define _HAS_EXCEPTIONS 1
    461 #  endif  // _HAS_EXCEPTIONS
    462 #  define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
    463 # elif defined(__clang__)
    464 // clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714,
    465 // but iff cleanups are enabled after that. In Obj-C++ files, there can be
    466 // cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions
    467 // are disabled. clang has __has_feature(cxx_exceptions) which checks for C++
    468 // exceptions starting at clang r206352, but which checked for cleanups prior to
    469 // that. To reliably check for C++ exception availability with clang, check for
    470 // __EXCEPTIONS && __has_feature(cxx_exceptions).
    471 #  define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
    472 # elif defined(__GNUC__) && __EXCEPTIONS
    473 // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
    474 #  define GTEST_HAS_EXCEPTIONS 1
    475 # elif defined(__SUNPRO_CC)
    476 // Sun Pro CC supports exceptions.  However, there is no compile-time way of
    477 // detecting whether they are enabled or not.  Therefore, we assume that
    478 // they are enabled unless the user tells us otherwise.
    479 #  define GTEST_HAS_EXCEPTIONS 1
    480 # elif defined(__IBMCPP__) && __EXCEPTIONS
    481 // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
    482 #  define GTEST_HAS_EXCEPTIONS 1
    483 # elif defined(__HP_aCC)
    484 // Exception handling is in effect by default in HP aCC compiler. It has to
    485 // be turned of by +noeh compiler option if desired.
    486 #  define GTEST_HAS_EXCEPTIONS 1
    487 # else
    488 // For other compilers, we assume exceptions are disabled to be
    489 // conservative.
    490 #  define GTEST_HAS_EXCEPTIONS 0
    491 # endif  // defined(_MSC_VER) || defined(__BORLANDC__)
    492 #endif  // GTEST_HAS_EXCEPTIONS
    493 
    494 #if !defined(GTEST_HAS_STD_STRING)
    495 // Even though we don't use this macro any longer, we keep it in case
    496 // some clients still depend on it.
    497 # define GTEST_HAS_STD_STRING 1
    498 #elif !GTEST_HAS_STD_STRING
    499 // The user told us that ::std::string isn't available.
    500 # error "Google Test cannot be used where ::std::string isn't available."
    501 #endif  // !defined(GTEST_HAS_STD_STRING)
    502 
    503 #ifndef GTEST_HAS_GLOBAL_STRING
    504 // The user didn't tell us whether ::string is available, so we need
    505 // to figure it out.
    506 
    507 # define GTEST_HAS_GLOBAL_STRING 0
    508 
    509 #endif  // GTEST_HAS_GLOBAL_STRING
    510 
    511 #ifndef GTEST_HAS_STD_WSTRING
    512 // The user didn't tell us whether ::std::wstring is available, so we need
    513 // to figure it out.
    514 // TODO(wan (at) google.com): uses autoconf to detect whether ::std::wstring
    515 //   is available.
    516 
    517 // Cygwin 1.7 and below doesn't support ::std::wstring.
    518 // Solaris' libc++ doesn't support it either.  Android has
    519 // no support for it at least as recent as Froyo (2.2).
    520 # define GTEST_HAS_STD_WSTRING \
    521     (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS))
    522 
    523 #endif  // GTEST_HAS_STD_WSTRING
    524 
    525 #ifndef GTEST_HAS_GLOBAL_WSTRING
    526 // The user didn't tell us whether ::wstring is available, so we need
    527 // to figure it out.
    528 # define GTEST_HAS_GLOBAL_WSTRING \
    529     (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
    530 #endif  // GTEST_HAS_GLOBAL_WSTRING
    531 
    532 // Determines whether RTTI is available.
    533 #ifndef GTEST_HAS_RTTI
    534 // The user didn't tell us whether RTTI is enabled, so we need to
    535 // figure it out.
    536 
    537 # ifdef _MSC_VER
    538 
    539 #  ifdef _CPPRTTI  // MSVC defines this macro iff RTTI is enabled.
    540 #   define GTEST_HAS_RTTI 1
    541 #  else
    542 #   define GTEST_HAS_RTTI 0
    543 #  endif
    544 
    545 // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
    546 # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
    547 
    548 #  ifdef __GXX_RTTI
    549 // When building against STLport with the Android NDK and with
    550 // -frtti -fno-exceptions, the build fails at link time with undefined
    551 // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
    552 // so disable RTTI when detected.
    553 #   if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
    554        !defined(__EXCEPTIONS)
    555 #    define GTEST_HAS_RTTI 0
    556 #   else
    557 #    define GTEST_HAS_RTTI 1
    558 #   endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
    559 #  else
    560 #   define GTEST_HAS_RTTI 0
    561 #  endif  // __GXX_RTTI
    562 
    563 // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
    564 // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
    565 // first version with C++ support.
    566 # elif defined(__clang__)
    567 
    568 #  define GTEST_HAS_RTTI __has_feature(cxx_rtti)
    569 
    570 // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
    571 // both the typeid and dynamic_cast features are present.
    572 # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
    573 
    574 #  ifdef __RTTI_ALL__
    575 #   define GTEST_HAS_RTTI 1
    576 #  else
    577 #   define GTEST_HAS_RTTI 0
    578 #  endif
    579 
    580 # else
    581 
    582 // For all other compilers, we assume RTTI is enabled.
    583 #  define GTEST_HAS_RTTI 1
    584 
    585 # endif  // _MSC_VER
    586 
    587 #endif  // GTEST_HAS_RTTI
    588 
    589 // It's this header's responsibility to #include <typeinfo> when RTTI
    590 // is enabled.
    591 #if GTEST_HAS_RTTI
    592 # include <typeinfo>
    593 #endif
    594 
    595 // Determines whether Google Test can use the pthreads library.
    596 #ifndef GTEST_HAS_PTHREAD
    597 // The user didn't tell us explicitly, so we make reasonable assumptions about
    598 // which platforms have pthreads support.
    599 //
    600 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
    601 // to your compiler flags.
    602 # define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \
    603     || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL)
    604 #endif  // GTEST_HAS_PTHREAD
    605 
    606 #if GTEST_HAS_PTHREAD
    607 // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
    608 // true.
    609 # include <pthread.h>  // NOLINT
    610 
    611 // For timespec and nanosleep, used below.
    612 # include <time.h>  // NOLINT
    613 #endif
    614 
    615 // Determines if hash_map/hash_set are available.
    616 // Only used for testing against those containers.
    617 #if !defined(GTEST_HAS_HASH_MAP_)
    618 # if _MSC_VER
    619 #  define GTEST_HAS_HASH_MAP_ 1  // Indicates that hash_map is available.
    620 #  define GTEST_HAS_HASH_SET_ 1  // Indicates that hash_set is available.
    621 # endif  // _MSC_VER
    622 #endif  // !defined(GTEST_HAS_HASH_MAP_)
    623 
    624 // Determines whether Google Test can use tr1/tuple.  You can define
    625 // this macro to 0 to prevent Google Test from using tuple (any
    626 // feature depending on tuple with be disabled in this mode).
    627 #ifndef GTEST_HAS_TR1_TUPLE
    628 # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR)
    629 // STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>.
    630 #  define GTEST_HAS_TR1_TUPLE 0
    631 # else
    632 // The user didn't tell us not to do it, so we assume it's OK.
    633 #  define GTEST_HAS_TR1_TUPLE 1
    634 # endif
    635 #endif  // GTEST_HAS_TR1_TUPLE
    636 
    637 // Determines whether Google Test's own tr1 tuple implementation
    638 // should be used.
    639 #ifndef GTEST_USE_OWN_TR1_TUPLE
    640 // The user didn't tell us, so we need to figure it out.
    641 
    642 // We use our own TR1 tuple if we aren't sure the user has an
    643 // implementation of it already.  At this time, libstdc++ 4.0.0+ and
    644 // MSVC 2010 are the only mainstream standard libraries that come
    645 // with a TR1 tuple implementation.  NVIDIA's CUDA NVCC compiler
    646 // pretends to be GCC by defining __GNUC__ and friends, but cannot
    647 // compile GCC's tuple implementation.  MSVC 2008 (9.0) provides TR1
    648 // tuple in a 323 MB Feature Pack download, which we cannot assume the
    649 // user has.  QNX's QCC compiler is a modified GCC but it doesn't
    650 // support TR1 tuple.  libc++ only provides std::tuple, in C++11 mode,
    651 // and it can be used with some compilers that define __GNUC__.
    652 # if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
    653       && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
    654 #  define GTEST_ENV_HAS_TR1_TUPLE_ 1
    655 # endif
    656 
    657 // C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
    658 // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
    659 // can build with clang but need to use gcc4.2's libstdc++).
    660 # if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
    661 #  define GTEST_ENV_HAS_STD_TUPLE_ 1
    662 # endif
    663 
    664 # if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
    665 #  define GTEST_USE_OWN_TR1_TUPLE 0
    666 # else
    667 #  define GTEST_USE_OWN_TR1_TUPLE 1
    668 # endif
    669 
    670 #endif  // GTEST_USE_OWN_TR1_TUPLE
    671 
    672 // To avoid conditional compilation everywhere, we make it
    673 // gtest-port.h's responsibility to #include the header implementing
    674 // tuple.
    675 #if GTEST_HAS_STD_TUPLE_
    676 # include <tuple>  // IWYU pragma: export
    677 # define GTEST_TUPLE_NAMESPACE_ ::std
    678 #endif  // GTEST_HAS_STD_TUPLE_
    679 
    680 // We include tr1::tuple even if std::tuple is available to define printers for
    681 // them.
    682 #if GTEST_HAS_TR1_TUPLE
    683 # ifndef GTEST_TUPLE_NAMESPACE_
    684 #  define GTEST_TUPLE_NAMESPACE_ ::std::tr1
    685 # endif  // GTEST_TUPLE_NAMESPACE_
    686 
    687 # if GTEST_USE_OWN_TR1_TUPLE
    688 #  include "gtest/internal/gtest-tuple.h"  // IWYU pragma: export  // NOLINT
    689 # elif GTEST_ENV_HAS_STD_TUPLE_
    690 #  include <tuple>
    691 // C++11 puts its tuple into the ::std namespace rather than
    692 // ::std::tr1.  gtest expects tuple to live in ::std::tr1, so put it there.
    693 // This causes undefined behavior, but supported compilers react in
    694 // the way we intend.
    695 namespace std {
    696 namespace tr1 {
    697 using ::std::get;
    698 using ::std::make_tuple;
    699 using ::std::tuple;
    700 using ::std::tuple_element;
    701 using ::std::tuple_size;
    702 }
    703 }
    704 
    705 # elif GTEST_OS_SYMBIAN
    706 
    707 // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
    708 // use STLport's tuple implementation, which unfortunately doesn't
    709 // work as the copy of STLport distributed with Symbian is incomplete.
    710 // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
    711 // use its own tuple implementation.
    712 #  ifdef BOOST_HAS_TR1_TUPLE
    713 #   undef BOOST_HAS_TR1_TUPLE
    714 #  endif  // BOOST_HAS_TR1_TUPLE
    715 
    716 // This prevents <boost/tr1/detail/config.hpp>, which defines
    717 // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
    718 #  define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
    719 #  include <tuple>  // IWYU pragma: export  // NOLINT
    720 
    721 # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
    722 // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header.  This does
    723 // not conform to the TR1 spec, which requires the header to be <tuple>.
    724 
    725 #  if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
    726 // Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
    727 // which is #included by <tr1/tuple>, to not compile when RTTI is
    728 // disabled.  _TR1_FUNCTIONAL is the header guard for
    729 // <tr1/functional>.  Hence the following #define is a hack to prevent
    730 // <tr1/functional> from being included.
    731 #   define _TR1_FUNCTIONAL 1
    732 #   include <tr1/tuple>
    733 #   undef _TR1_FUNCTIONAL  // Allows the user to #include
    734                         // <tr1/functional> if he chooses to.
    735 #  else
    736 #   include <tr1/tuple>  // NOLINT
    737 #  endif  // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
    738 
    739 # else
    740 // If the compiler is not GCC 4.0+, we assume the user is using a
    741 // spec-conforming TR1 implementation.
    742 #  include <tuple>  // IWYU pragma: export  // NOLINT
    743 # endif  // GTEST_USE_OWN_TR1_TUPLE
    744 
    745 #endif  // GTEST_HAS_TR1_TUPLE
    746 
    747 // Determines whether clone(2) is supported.
    748 // Usually it will only be available on Linux, excluding
    749 // Linux on the Itanium architecture.
    750 // Also see http://linux.die.net/man/2/clone.
    751 #ifndef GTEST_HAS_CLONE
    752 // The user didn't tell us, so we need to figure it out.
    753 
    754 # if GTEST_OS_LINUX && !defined(__ia64__)
    755 #  if GTEST_OS_LINUX_ANDROID
    756 // On Android, clone() is only available on ARM starting with Gingerbread.
    757 #    if defined(__arm__) && __ANDROID_API__ >= 9
    758 #     define GTEST_HAS_CLONE 1
    759 #    else
    760 #     define GTEST_HAS_CLONE 0
    761 #    endif
    762 #  else
    763 #   define GTEST_HAS_CLONE 1
    764 #  endif
    765 # else
    766 #  define GTEST_HAS_CLONE 0
    767 # endif  // GTEST_OS_LINUX && !defined(__ia64__)
    768 
    769 #endif  // GTEST_HAS_CLONE
    770 
    771 // Determines whether to support stream redirection. This is used to test
    772 // output correctness and to implement death tests.
    773 #ifndef GTEST_HAS_STREAM_REDIRECTION
    774 // By default, we assume that stream redirection is supported on all
    775 // platforms except known mobile ones.
    776 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \
    777     GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
    778 #  define GTEST_HAS_STREAM_REDIRECTION 0
    779 # else
    780 #  define GTEST_HAS_STREAM_REDIRECTION 1
    781 # endif  // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
    782 #endif  // GTEST_HAS_STREAM_REDIRECTION
    783 
    784 // Determines whether to support death tests.
    785 // Google Test does not support death tests for VC 7.1 and earlier as
    786 // abort() in a VC 7.1 application compiled as GUI in debug config
    787 // pops up a dialog window that cannot be suppressed programmatically.
    788 #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
    789      (GTEST_OS_MAC && !GTEST_OS_IOS) || \
    790      (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
    791      GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
    792      GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD)
    793 # define GTEST_HAS_DEATH_TEST 1
    794 #endif
    795 
    796 // We don't support MSVC 7.1 with exceptions disabled now.  Therefore
    797 // all the compilers we care about are adequate for supporting
    798 // value-parameterized tests.
    799 #define GTEST_HAS_PARAM_TEST 1
    800 
    801 // Determines whether to support type-driven tests.
    802 
    803 // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
    804 // Sun Pro CC, IBM Visual Age, and HP aCC support.
    805 #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
    806     defined(__IBMCPP__) || defined(__HP_aCC)
    807 # define GTEST_HAS_TYPED_TEST 1
    808 # define GTEST_HAS_TYPED_TEST_P 1
    809 #endif
    810 
    811 // Determines whether to support Combine(). This only makes sense when
    812 // value-parameterized tests are enabled.  The implementation doesn't
    813 // work on Sun Studio since it doesn't understand templated conversion
    814 // operators.
    815 #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
    816 # define GTEST_HAS_COMBINE 1
    817 #endif
    818 
    819 // Determines whether the system compiler uses UTF-16 for encoding wide strings.
    820 #define GTEST_WIDE_STRING_USES_UTF16_ \
    821     (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
    822 
    823 // Determines whether test results can be streamed to a socket.
    824 #if GTEST_OS_LINUX
    825 # define GTEST_CAN_STREAM_RESULTS_ 1
    826 #endif
    827 
    828 // Defines some utility macros.
    829 
    830 // The GNU compiler emits a warning if nested "if" statements are followed by
    831 // an "else" statement and braces are not used to explicitly disambiguate the
    832 // "else" binding.  This leads to problems with code like:
    833 //
    834 //   if (gate)
    835 //     ASSERT_*(condition) << "Some message";
    836 //
    837 // The "switch (0) case 0:" idiom is used to suppress this.
    838 #ifdef __INTEL_COMPILER
    839 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
    840 #else
    841 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default:  // NOLINT
    842 #endif
    843 
    844 // Use this annotation at the end of a struct/class definition to
    845 // prevent the compiler from optimizing away instances that are never
    846 // used.  This is useful when all interesting logic happens inside the
    847 // c'tor and / or d'tor.  Example:
    848 //
    849 //   struct Foo {
    850 //     Foo() { ... }
    851 //   } GTEST_ATTRIBUTE_UNUSED_;
    852 //
    853 // Also use it after a variable or parameter declaration to tell the
    854 // compiler the variable/parameter does not have to be used.
    855 #if defined(__GNUC__) && !defined(COMPILER_ICC)
    856 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
    857 #elif defined(__clang__)
    858 # if __has_attribute(unused)
    859 #  define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
    860 # endif
    861 #endif
    862 #ifndef GTEST_ATTRIBUTE_UNUSED_
    863 # define GTEST_ATTRIBUTE_UNUSED_
    864 #endif
    865 
    866 // A macro to disallow operator=
    867 // This should be used in the private: declarations for a class.
    868 #define GTEST_DISALLOW_ASSIGN_(type)\
    869   void operator=(type const &)
    870 
    871 // A macro to disallow copy constructor and operator=
    872 // This should be used in the private: declarations for a class.
    873 #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
    874   type(type const &);\
    875   GTEST_DISALLOW_ASSIGN_(type)
    876 
    877 // Tell the compiler to warn about unused return values for functions declared
    878 // with this macro.  The macro should be used on function declarations
    879 // following the argument list:
    880 //
    881 //   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
    882 #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
    883 # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
    884 #else
    885 # define GTEST_MUST_USE_RESULT_
    886 #endif  // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
    887 
    888 // MS C++ compiler emits warning when a conditional expression is compile time
    889 // constant. In some contexts this warning is false positive and needs to be
    890 // suppressed. Use the following two macros in such cases:
    891 //
    892 // GTEST_INTENTIONAL_CONST_COND_PUSH_()
    893 // while (true) {
    894 // GTEST_INTENTIONAL_CONST_COND_POP_()
    895 // }
    896 # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
    897     GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
    898 # define GTEST_INTENTIONAL_CONST_COND_POP_() \
    899     GTEST_DISABLE_MSC_WARNINGS_POP_()
    900 
    901 // Determine whether the compiler supports Microsoft's Structured Exception
    902 // Handling.  This is supported by several Windows compilers but generally
    903 // does not exist on any other system.
    904 #ifndef GTEST_HAS_SEH
    905 // The user didn't tell us, so we need to figure it out.
    906 
    907 # if defined(_MSC_VER) || defined(__BORLANDC__)
    908 // These two compilers are known to support SEH.
    909 #  define GTEST_HAS_SEH 1
    910 # else
    911 // Assume no SEH.
    912 #  define GTEST_HAS_SEH 0
    913 # endif
    914 
    915 #define GTEST_IS_THREADSAFE \
    916     (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \
    917      || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \
    918      || GTEST_HAS_PTHREAD)
    919 
    920 #endif  // GTEST_HAS_SEH
    921 
    922 #ifdef _MSC_VER
    923 
    924 # if GTEST_LINKED_AS_SHARED_LIBRARY
    925 #  define GTEST_API_ __declspec(dllimport)
    926 # elif GTEST_CREATE_SHARED_LIBRARY
    927 #  define GTEST_API_ __declspec(dllexport)
    928 # endif
    929 
    930 #endif  // _MSC_VER
    931 
    932 #ifndef GTEST_API_
    933 # define GTEST_API_
    934 #endif
    935 
    936 #ifdef __GNUC__
    937 // Ask the compiler to never inline a given function.
    938 # define GTEST_NO_INLINE_ __attribute__((noinline))
    939 #else
    940 # define GTEST_NO_INLINE_
    941 #endif
    942 
    943 // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
    944 #if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
    945 # define GTEST_HAS_CXXABI_H_ 1
    946 #else
    947 # define GTEST_HAS_CXXABI_H_ 0
    948 #endif
    949 
    950 // A function level attribute to disable checking for use of uninitialized
    951 // memory when built with MemorySanitizer.
    952 #if defined(__clang__)
    953 # if __has_feature(memory_sanitizer)
    954 #  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
    955        __attribute__((no_sanitize_memory))
    956 # else
    957 #  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
    958 # endif  // __has_feature(memory_sanitizer)
    959 #else
    960 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
    961 #endif  // __clang__
    962 
    963 // A function level attribute to disable AddressSanitizer instrumentation.
    964 #if defined(__clang__)
    965 # if __has_feature(address_sanitizer)
    966 #  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
    967        __attribute__((no_sanitize_address))
    968 # else
    969 #  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
    970 # endif  // __has_feature(address_sanitizer)
    971 #else
    972 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
    973 #endif  // __clang__
    974 
    975 // A function level attribute to disable ThreadSanitizer instrumentation.
    976 #if defined(__clang__)
    977 # if __has_feature(thread_sanitizer)
    978 #  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
    979        __attribute__((no_sanitize_thread))
    980 # else
    981 #  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
    982 # endif  // __has_feature(thread_sanitizer)
    983 #else
    984 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
    985 #endif  // __clang__
    986 
    987 namespace testing {
    988 
    989 class Message;
    990 
    991 #if defined(GTEST_TUPLE_NAMESPACE_)
    992 // Import tuple and friends into the ::testing namespace.
    993 // It is part of our interface, having them in ::testing allows us to change
    994 // their types as needed.
    995 using GTEST_TUPLE_NAMESPACE_::get;
    996 using GTEST_TUPLE_NAMESPACE_::make_tuple;
    997 using GTEST_TUPLE_NAMESPACE_::tuple;
    998 using GTEST_TUPLE_NAMESPACE_::tuple_size;
    999 using GTEST_TUPLE_NAMESPACE_::tuple_element;
   1000 #endif  // defined(GTEST_TUPLE_NAMESPACE_)
   1001 
   1002 namespace internal {
   1003 
   1004 // A secret type that Google Test users don't know about.  It has no
   1005 // definition on purpose.  Therefore it's impossible to create a
   1006 // Secret object, which is what we want.
   1007 class Secret;
   1008 
   1009 // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
   1010 // expression is true. For example, you could use it to verify the
   1011 // size of a static array:
   1012 //
   1013 //   GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
   1014 //                         names_incorrect_size);
   1015 //
   1016 // or to make sure a struct is smaller than a certain size:
   1017 //
   1018 //   GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
   1019 //
   1020 // The second argument to the macro is the name of the variable. If
   1021 // the expression is false, most compilers will issue a warning/error
   1022 // containing the name of the variable.
   1023 
   1024 #if GTEST_LANG_CXX11
   1025 # define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
   1026 #else  // !GTEST_LANG_CXX11
   1027 template <bool>
   1028   struct CompileAssert {
   1029 };
   1030 
   1031 # define GTEST_COMPILE_ASSERT_(expr, msg) \
   1032   typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
   1033       msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
   1034 #endif  // !GTEST_LANG_CXX11
   1035 
   1036 // Implementation details of GTEST_COMPILE_ASSERT_:
   1037 //
   1038 // (In C++11, we simply use static_assert instead of the following)
   1039 //
   1040 // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
   1041 //   elements (and thus is invalid) when the expression is false.
   1042 //
   1043 // - The simpler definition
   1044 //
   1045 //    #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
   1046 //
   1047 //   does not work, as gcc supports variable-length arrays whose sizes
   1048 //   are determined at run-time (this is gcc's extension and not part
   1049 //   of the C++ standard).  As a result, gcc fails to reject the
   1050 //   following code with the simple definition:
   1051 //
   1052 //     int foo;
   1053 //     GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
   1054 //                                      // not a compile-time constant.
   1055 //
   1056 // - By using the type CompileAssert<(bool(expr))>, we ensures that
   1057 //   expr is a compile-time constant.  (Template arguments must be
   1058 //   determined at compile-time.)
   1059 //
   1060 // - The outter parentheses in CompileAssert<(bool(expr))> are necessary
   1061 //   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
   1062 //
   1063 //     CompileAssert<bool(expr)>
   1064 //
   1065 //   instead, these compilers will refuse to compile
   1066 //
   1067 //     GTEST_COMPILE_ASSERT_(5 > 0, some_message);
   1068 //
   1069 //   (They seem to think the ">" in "5 > 0" marks the end of the
   1070 //   template argument list.)
   1071 //
   1072 // - The array size is (bool(expr) ? 1 : -1), instead of simply
   1073 //
   1074 //     ((expr) ? 1 : -1).
   1075 //
   1076 //   This is to avoid running into a bug in MS VC 7.1, which
   1077 //   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
   1078 
   1079 // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
   1080 //
   1081 // This template is declared, but intentionally undefined.
   1082 template <typename T1, typename T2>
   1083 struct StaticAssertTypeEqHelper;
   1084 
   1085 template <typename T>
   1086 struct StaticAssertTypeEqHelper<T, T> {
   1087   enum { value = true };
   1088 };
   1089 
   1090 // Evaluates to the number of elements in 'array'.
   1091 #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
   1092 
   1093 #if GTEST_HAS_GLOBAL_STRING
   1094 typedef ::string string;
   1095 #else
   1096 typedef ::std::string string;
   1097 #endif  // GTEST_HAS_GLOBAL_STRING
   1098 
   1099 #if GTEST_HAS_GLOBAL_WSTRING
   1100 typedef ::wstring wstring;
   1101 #elif GTEST_HAS_STD_WSTRING
   1102 typedef ::std::wstring wstring;
   1103 #endif  // GTEST_HAS_GLOBAL_WSTRING
   1104 
   1105 // A helper for suppressing warnings on constant condition.  It just
   1106 // returns 'condition'.
   1107 GTEST_API_ bool IsTrue(bool condition);
   1108 
   1109 // Defines scoped_ptr.
   1110 
   1111 // This implementation of scoped_ptr is PARTIAL - it only contains
   1112 // enough stuff to satisfy Google Test's need.
   1113 template <typename T>
   1114 class scoped_ptr {
   1115  public:
   1116   typedef T element_type;
   1117 
   1118   explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
   1119   ~scoped_ptr() { reset(); }
   1120 
   1121   T& operator*() const { return *ptr_; }
   1122   T* operator->() const { return ptr_; }
   1123   T* get() const { return ptr_; }
   1124 
   1125   T* release() {
   1126     T* const ptr = ptr_;
   1127     ptr_ = NULL;
   1128     return ptr;
   1129   }
   1130 
   1131   void reset(T* p = NULL) {
   1132     if (p != ptr_) {
   1133       if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
   1134         delete ptr_;
   1135       }
   1136       ptr_ = p;
   1137     }
   1138   }
   1139 
   1140   friend void swap(scoped_ptr& a, scoped_ptr& b) {
   1141     using std::swap;
   1142     swap(a.ptr_, b.ptr_);
   1143   }
   1144 
   1145  private:
   1146   T* ptr_;
   1147 
   1148   GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
   1149 };
   1150 
   1151 // Defines RE.
   1152 
   1153 // A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
   1154 // Regular Expression syntax.
   1155 class GTEST_API_ RE {
   1156  public:
   1157   // A copy constructor is required by the Standard to initialize object
   1158   // references from r-values.
   1159   RE(const RE& other) { Init(other.pattern()); }
   1160 
   1161   // Constructs an RE from a string.
   1162   RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
   1163 
   1164 #if GTEST_HAS_GLOBAL_STRING
   1165 
   1166   RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
   1167 
   1168 #endif  // GTEST_HAS_GLOBAL_STRING
   1169 
   1170   RE(const char* regex) { Init(regex); }  // NOLINT
   1171   ~RE();
   1172 
   1173   // Returns the string representation of the regex.
   1174   const char* pattern() const { return pattern_; }
   1175 
   1176   // FullMatch(str, re) returns true iff regular expression re matches
   1177   // the entire str.
   1178   // PartialMatch(str, re) returns true iff regular expression re
   1179   // matches a substring of str (including str itself).
   1180   //
   1181   // TODO(wan (at) google.com): make FullMatch() and PartialMatch() work
   1182   // when str contains NUL characters.
   1183   static bool FullMatch(const ::std::string& str, const RE& re) {
   1184     return FullMatch(str.c_str(), re);
   1185   }
   1186   static bool PartialMatch(const ::std::string& str, const RE& re) {
   1187     return PartialMatch(str.c_str(), re);
   1188   }
   1189 
   1190 #if GTEST_HAS_GLOBAL_STRING
   1191 
   1192   static bool FullMatch(const ::string& str, const RE& re) {
   1193     return FullMatch(str.c_str(), re);
   1194   }
   1195   static bool PartialMatch(const ::string& str, const RE& re) {
   1196     return PartialMatch(str.c_str(), re);
   1197   }
   1198 
   1199 #endif  // GTEST_HAS_GLOBAL_STRING
   1200 
   1201   static bool FullMatch(const char* str, const RE& re);
   1202   static bool PartialMatch(const char* str, const RE& re);
   1203 
   1204  private:
   1205   void Init(const char* regex);
   1206 
   1207   // We use a const char* instead of an std::string, as Google Test used to be
   1208   // used where std::string is not available.  TODO(wan (at) google.com): change to
   1209   // std::string.
   1210   const char* pattern_;
   1211   bool is_valid_;
   1212 
   1213 #if GTEST_USES_POSIX_RE
   1214 
   1215   regex_t full_regex_;     // For FullMatch().
   1216   regex_t partial_regex_;  // For PartialMatch().
   1217 
   1218 #else  // GTEST_USES_SIMPLE_RE
   1219 
   1220   const char* full_pattern_;  // For FullMatch();
   1221 
   1222 #endif
   1223 
   1224   GTEST_DISALLOW_ASSIGN_(RE);
   1225 };
   1226 
   1227 // Formats a source file path and a line number as they would appear
   1228 // in an error message from the compiler used to compile this code.
   1229 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
   1230 
   1231 // Formats a file location for compiler-independent XML output.
   1232 // Although this function is not platform dependent, we put it next to
   1233 // FormatFileLocation in order to contrast the two functions.
   1234 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
   1235                                                                int line);
   1236 
   1237 // Defines logging utilities:
   1238 //   GTEST_LOG_(severity) - logs messages at the specified severity level. The
   1239 //                          message itself is streamed into the macro.
   1240 //   LogToStderr()  - directs all log messages to stderr.
   1241 //   FlushInfoLog() - flushes informational log messages.
   1242 
   1243 enum GTestLogSeverity {
   1244   GTEST_INFO,
   1245   GTEST_WARNING,
   1246   GTEST_ERROR,
   1247   GTEST_FATAL
   1248 };
   1249 
   1250 // Formats log entry severity, provides a stream object for streaming the
   1251 // log message, and terminates the message with a newline when going out of
   1252 // scope.
   1253 class GTEST_API_ GTestLog {
   1254  public:
   1255   GTestLog(GTestLogSeverity severity, const char* file, int line);
   1256 
   1257   // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
   1258   ~GTestLog();
   1259 
   1260   ::std::ostream& GetStream() { return ::std::cerr; }
   1261 
   1262  private:
   1263   const GTestLogSeverity severity_;
   1264 
   1265   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
   1266 };
   1267 
   1268 #if !defined(GTEST_LOG_)
   1269 
   1270 # define GTEST_LOG_(severity) \
   1271     ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
   1272                                   __FILE__, __LINE__).GetStream()
   1273 
   1274 inline void LogToStderr() {}
   1275 inline void FlushInfoLog() { fflush(NULL); }
   1276 
   1277 #endif  // !defined(GTEST_LOG_)
   1278 
   1279 #if !defined(GTEST_CHECK_)
   1280 // INTERNAL IMPLEMENTATION - DO NOT USE.
   1281 //
   1282 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
   1283 // is not satisfied.
   1284 //  Synopsys:
   1285 //    GTEST_CHECK_(boolean_condition);
   1286 //     or
   1287 //    GTEST_CHECK_(boolean_condition) << "Additional message";
   1288 //
   1289 //    This checks the condition and if the condition is not satisfied
   1290 //    it prints message about the condition violation, including the
   1291 //    condition itself, plus additional message streamed into it, if any,
   1292 //    and then it aborts the program. It aborts the program irrespective of
   1293 //    whether it is built in the debug mode or not.
   1294 # define GTEST_CHECK_(condition) \
   1295     GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
   1296     if (::testing::internal::IsTrue(condition)) \
   1297       ; \
   1298     else \
   1299       GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
   1300 #endif  // !defined(GTEST_CHECK_)
   1301 
   1302 // An all-mode assert to verify that the given POSIX-style function
   1303 // call returns 0 (indicating success).  Known limitation: this
   1304 // doesn't expand to a balanced 'if' statement, so enclose the macro
   1305 // in {} if you need to use it as the only statement in an 'if'
   1306 // branch.
   1307 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
   1308   if (const int gtest_error = (posix_call)) \
   1309     GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
   1310                       << gtest_error
   1311 
   1312 #if GTEST_HAS_STD_MOVE_
   1313 using std::move;
   1314 #else  // GTEST_HAS_STD_MOVE_
   1315 template <typename T>
   1316 const T& move(const T& t) {
   1317   return t;
   1318 }
   1319 #endif  // GTEST_HAS_STD_MOVE_
   1320 
   1321 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
   1322 //
   1323 // Use ImplicitCast_ as a safe version of static_cast for upcasting in
   1324 // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
   1325 // const Foo*).  When you use ImplicitCast_, the compiler checks that
   1326 // the cast is safe.  Such explicit ImplicitCast_s are necessary in
   1327 // surprisingly many situations where C++ demands an exact type match
   1328 // instead of an argument type convertable to a target type.
   1329 //
   1330 // The syntax for using ImplicitCast_ is the same as for static_cast:
   1331 //
   1332 //   ImplicitCast_<ToType>(expr)
   1333 //
   1334 // ImplicitCast_ would have been part of the C++ standard library,
   1335 // but the proposal was submitted too late.  It will probably make
   1336 // its way into the language in the future.
   1337 //
   1338 // This relatively ugly name is intentional. It prevents clashes with
   1339 // similar functions users may have (e.g., implicit_cast). The internal
   1340 // namespace alone is not enough because the function can be found by ADL.
   1341 template<typename To>
   1342 inline To ImplicitCast_(To x) { return x; }
   1343 
   1344 // When you upcast (that is, cast a pointer from type Foo to type
   1345 // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
   1346 // always succeed.  When you downcast (that is, cast a pointer from
   1347 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
   1348 // how do you know the pointer is really of type SubclassOfFoo?  It
   1349 // could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
   1350 // when you downcast, you should use this macro.  In debug mode, we
   1351 // use dynamic_cast<> to double-check the downcast is legal (we die
   1352 // if it's not).  In normal mode, we do the efficient static_cast<>
   1353 // instead.  Thus, it's important to test in debug mode to make sure
   1354 // the cast is legal!
   1355 //    This is the only place in the code we should use dynamic_cast<>.
   1356 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
   1357 // do RTTI (eg code like this:
   1358 //    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
   1359 //    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
   1360 // You should design the code some other way not to need this.
   1361 //
   1362 // This relatively ugly name is intentional. It prevents clashes with
   1363 // similar functions users may have (e.g., down_cast). The internal
   1364 // namespace alone is not enough because the function can be found by ADL.
   1365 template<typename To, typename From>  // use like this: DownCast_<T*>(foo);
   1366 inline To DownCast_(From* f) {  // so we only accept pointers
   1367   // Ensures that To is a sub-type of From *.  This test is here only
   1368   // for compile-time type checking, and has no overhead in an
   1369   // optimized build at run-time, as it will be optimized away
   1370   // completely.
   1371   GTEST_INTENTIONAL_CONST_COND_PUSH_()
   1372   if (false) {
   1373   GTEST_INTENTIONAL_CONST_COND_POP_()
   1374     const To to = NULL;
   1375     ::testing::internal::ImplicitCast_<From*>(to);
   1376   }
   1377 
   1378 #if GTEST_HAS_RTTI
   1379   // RTTI: debug mode only!
   1380   GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL);
   1381 #endif
   1382   return static_cast<To>(f);
   1383 }
   1384 
   1385 // Downcasts the pointer of type Base to Derived.
   1386 // Derived must be a subclass of Base. The parameter MUST
   1387 // point to a class of type Derived, not any subclass of it.
   1388 // When RTTI is available, the function performs a runtime
   1389 // check to enforce this.
   1390 template <class Derived, class Base>
   1391 Derived* CheckedDowncastToActualType(Base* base) {
   1392 #if GTEST_HAS_RTTI
   1393   GTEST_CHECK_(typeid(*base) == typeid(Derived));
   1394 #endif
   1395 
   1396 #if GTEST_HAS_DOWNCAST_
   1397   return ::down_cast<Derived*>(base);
   1398 #elif GTEST_HAS_RTTI
   1399   return dynamic_cast<Derived*>(base);  // NOLINT
   1400 #else
   1401   return static_cast<Derived*>(base);  // Poor man's downcast.
   1402 #endif
   1403 }
   1404 
   1405 #if GTEST_HAS_STREAM_REDIRECTION
   1406 
   1407 // Defines the stderr capturer:
   1408 //   CaptureStdout     - starts capturing stdout.
   1409 //   GetCapturedStdout - stops capturing stdout and returns the captured string.
   1410 //   CaptureStderr     - starts capturing stderr.
   1411 //   GetCapturedStderr - stops capturing stderr and returns the captured string.
   1412 //
   1413 GTEST_API_ void CaptureStdout();
   1414 GTEST_API_ std::string GetCapturedStdout();
   1415 GTEST_API_ void CaptureStderr();
   1416 GTEST_API_ std::string GetCapturedStderr();
   1417 
   1418 #endif  // GTEST_HAS_STREAM_REDIRECTION
   1419 
   1420 // Returns a path to temporary directory.
   1421 GTEST_API_ std::string TempDir();
   1422 
   1423 // Returns the size (in bytes) of a file.
   1424 GTEST_API_ size_t GetFileSize(FILE* file);
   1425 
   1426 // Reads the entire content of a file as a string.
   1427 GTEST_API_ std::string ReadEntireFile(FILE* file);
   1428 
   1429 // All command line arguments.
   1430 GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs();
   1431 
   1432 #if GTEST_HAS_DEATH_TEST
   1433 
   1434 const ::std::vector<testing::internal::string>& GetInjectableArgvs();
   1435 void SetInjectableArgvs(const ::std::vector<testing::internal::string>*
   1436                              new_argvs);
   1437 
   1438 
   1439 #endif  // GTEST_HAS_DEATH_TEST
   1440 
   1441 // Defines synchronization primitives.
   1442 #if GTEST_IS_THREADSAFE
   1443 # if GTEST_HAS_PTHREAD
   1444 // Sleeps for (roughly) n milliseconds.  This function is only for testing
   1445 // Google Test's own constructs.  Don't use it in user tests, either
   1446 // directly or indirectly.
   1447 inline void SleepMilliseconds(int n) {
   1448   const timespec time = {
   1449     0,                  // 0 seconds.
   1450     n * 1000L * 1000L,  // And n ms.
   1451   };
   1452   nanosleep(&time, NULL);
   1453 }
   1454 # endif  // GTEST_HAS_PTHREAD
   1455 
   1456 # if GTEST_HAS_NOTIFICATION_
   1457 // Notification has already been imported into the namespace.
   1458 // Nothing to do here.
   1459 
   1460 # elif GTEST_HAS_PTHREAD
   1461 // Allows a controller thread to pause execution of newly created
   1462 // threads until notified.  Instances of this class must be created
   1463 // and destroyed in the controller thread.
   1464 //
   1465 // This class is only for testing Google Test's own constructs. Do not
   1466 // use it in user tests, either directly or indirectly.
   1467 class Notification {
   1468  public:
   1469   Notification() : notified_(false) {
   1470     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
   1471   }
   1472   ~Notification() {
   1473     pthread_mutex_destroy(&mutex_);
   1474   }
   1475 
   1476   // Notifies all threads created with this notification to start. Must
   1477   // be called from the controller thread.
   1478   void Notify() {
   1479     pthread_mutex_lock(&mutex_);
   1480     notified_ = true;
   1481     pthread_mutex_unlock(&mutex_);
   1482   }
   1483 
   1484   // Blocks until the controller thread notifies. Must be called from a test
   1485   // thread.
   1486   void WaitForNotification() {
   1487     for (;;) {
   1488       pthread_mutex_lock(&mutex_);
   1489       const bool notified = notified_;
   1490       pthread_mutex_unlock(&mutex_);
   1491       if (notified)
   1492         break;
   1493       SleepMilliseconds(10);
   1494     }
   1495   }
   1496 
   1497  private:
   1498   pthread_mutex_t mutex_;
   1499   bool notified_;
   1500 
   1501   GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
   1502 };
   1503 
   1504 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
   1505 
   1506 GTEST_API_ void SleepMilliseconds(int n);
   1507 
   1508 // Provides leak-safe Windows kernel handle ownership.
   1509 // Used in death tests and in threading support.
   1510 class GTEST_API_ AutoHandle {
   1511  public:
   1512   // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
   1513   // avoid including <windows.h> in this header file. Including <windows.h> is
   1514   // undesirable because it defines a lot of symbols and macros that tend to
   1515   // conflict with client code. This assumption is verified by
   1516   // WindowsTypesTest.HANDLEIsVoidStar.
   1517   typedef void* Handle;
   1518   AutoHandle();
   1519   explicit AutoHandle(Handle handle);
   1520 
   1521   ~AutoHandle();
   1522 
   1523   Handle Get() const;
   1524   void Reset();
   1525   void Reset(Handle handle);
   1526 
   1527  private:
   1528   // Returns true iff the handle is a valid handle object that can be closed.
   1529   bool IsCloseable() const;
   1530 
   1531   Handle handle_;
   1532 
   1533   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
   1534 };
   1535 
   1536 // Allows a controller thread to pause execution of newly created
   1537 // threads until notified.  Instances of this class must be created
   1538 // and destroyed in the controller thread.
   1539 //
   1540 // This class is only for testing Google Test's own constructs. Do not
   1541 // use it in user tests, either directly or indirectly.
   1542 class GTEST_API_ Notification {
   1543  public:
   1544   Notification();
   1545   void Notify();
   1546   void WaitForNotification();
   1547 
   1548  private:
   1549   AutoHandle event_;
   1550 
   1551   GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
   1552 };
   1553 # endif  // GTEST_HAS_NOTIFICATION_
   1554 
   1555 // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
   1556 // defined, but we don't want to use MinGW's pthreads implementation, which
   1557 // has conformance problems with some versions of the POSIX standard.
   1558 # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
   1559 
   1560 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
   1561 // Consequently, it cannot select a correct instantiation of ThreadWithParam
   1562 // in order to call its Run(). Introducing ThreadWithParamBase as a
   1563 // non-templated base class for ThreadWithParam allows us to bypass this
   1564 // problem.
   1565 class ThreadWithParamBase {
   1566  public:
   1567   virtual ~ThreadWithParamBase() {}
   1568   virtual void Run() = 0;
   1569 };
   1570 
   1571 // pthread_create() accepts a pointer to a function type with the C linkage.
   1572 // According to the Standard (7.5/1), function types with different linkages
   1573 // are different even if they are otherwise identical.  Some compilers (for
   1574 // example, SunStudio) treat them as different types.  Since class methods
   1575 // cannot be defined with C-linkage we need to define a free C-function to
   1576 // pass into pthread_create().
   1577 extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
   1578   static_cast<ThreadWithParamBase*>(thread)->Run();
   1579   return NULL;
   1580 }
   1581 
   1582 // Helper class for testing Google Test's multi-threading constructs.
   1583 // To use it, write:
   1584 //
   1585 //   void ThreadFunc(int param) { /* Do things with param */ }
   1586 //   Notification thread_can_start;
   1587 //   ...
   1588 //   // The thread_can_start parameter is optional; you can supply NULL.
   1589 //   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
   1590 //   thread_can_start.Notify();
   1591 //
   1592 // These classes are only for testing Google Test's own constructs. Do
   1593 // not use them in user tests, either directly or indirectly.
   1594 template <typename T>
   1595 class ThreadWithParam : public ThreadWithParamBase {
   1596  public:
   1597   typedef void UserThreadFunc(T);
   1598 
   1599   ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
   1600       : func_(func),
   1601         param_(param),
   1602         thread_can_start_(thread_can_start),
   1603         finished_(false) {
   1604     ThreadWithParamBase* const base = this;
   1605     // The thread can be created only after all fields except thread_
   1606     // have been initialized.
   1607     GTEST_CHECK_POSIX_SUCCESS_(
   1608         pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
   1609   }
   1610   ~ThreadWithParam() { Join(); }
   1611 
   1612   void Join() {
   1613     if (!finished_) {
   1614       GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
   1615       finished_ = true;
   1616     }
   1617   }
   1618 
   1619   virtual void Run() {
   1620     if (thread_can_start_ != NULL)
   1621       thread_can_start_->WaitForNotification();
   1622     func_(param_);
   1623   }
   1624 
   1625  private:
   1626   UserThreadFunc* const func_;  // User-supplied thread function.
   1627   const T param_;  // User-supplied parameter to the thread function.
   1628   // When non-NULL, used to block execution until the controller thread
   1629   // notifies.
   1630   Notification* const thread_can_start_;
   1631   bool finished_;  // true iff we know that the thread function has finished.
   1632   pthread_t thread_;  // The native thread object.
   1633 
   1634   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
   1635 };
   1636 # endif  // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
   1637          // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
   1638 
   1639 # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
   1640 // Mutex and ThreadLocal have already been imported into the namespace.
   1641 // Nothing to do here.
   1642 
   1643 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
   1644 
   1645 // Mutex implements mutex on Windows platforms.  It is used in conjunction
   1646 // with class MutexLock:
   1647 //
   1648 //   Mutex mutex;
   1649 //   ...
   1650 //   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the
   1651 //                            // end of the current scope.
   1652 //
   1653 // A static Mutex *must* be defined or declared using one of the following
   1654 // macros:
   1655 //   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
   1656 //   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
   1657 //
   1658 // (A non-static Mutex is defined/declared in the usual way).
   1659 class GTEST_API_ Mutex {
   1660  public:
   1661   enum MutexType { kStatic = 0, kDynamic = 1 };
   1662   // We rely on kStaticMutex being 0 as it is to what the linker initializes
   1663   // type_ in static mutexes.  critical_section_ will be initialized lazily
   1664   // in ThreadSafeLazyInit().
   1665   enum StaticConstructorSelector { kStaticMutex = 0 };
   1666 
   1667   // This constructor intentionally does nothing.  It relies on type_ being
   1668   // statically initialized to 0 (effectively setting it to kStatic) and on
   1669   // ThreadSafeLazyInit() to lazily initialize the rest of the members.
   1670   explicit Mutex(StaticConstructorSelector /*dummy*/) {}
   1671 
   1672   Mutex();
   1673   ~Mutex();
   1674 
   1675   void Lock();
   1676 
   1677   void Unlock();
   1678 
   1679   // Does nothing if the current thread holds the mutex. Otherwise, crashes
   1680   // with high probability.
   1681   void AssertHeld();
   1682 
   1683  private:
   1684   // Initializes owner_thread_id_ and critical_section_ in static mutexes.
   1685   void ThreadSafeLazyInit();
   1686 
   1687   // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx,
   1688   // we assume that 0 is an invalid value for thread IDs.
   1689   unsigned int owner_thread_id_;
   1690 
   1691   // For static mutexes, we rely on these members being initialized to zeros
   1692   // by the linker.
   1693   MutexType type_;
   1694   long critical_section_init_phase_;  // NOLINT
   1695   _RTL_CRITICAL_SECTION* critical_section_;
   1696 
   1697   GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
   1698 };
   1699 
   1700 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
   1701     extern ::testing::internal::Mutex mutex
   1702 
   1703 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
   1704     ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
   1705 
   1706 // We cannot name this class MutexLock because the ctor declaration would
   1707 // conflict with a macro named MutexLock, which is defined on some
   1708 // platforms. That macro is used as a defensive measure to prevent against
   1709 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
   1710 // "MutexLock l(&mu)".  Hence the typedef trick below.
   1711 class GTestMutexLock {
   1712  public:
   1713   explicit GTestMutexLock(Mutex* mutex)
   1714       : mutex_(mutex) { mutex_->Lock(); }
   1715 
   1716   ~GTestMutexLock() { mutex_->Unlock(); }
   1717 
   1718  private:
   1719   Mutex* const mutex_;
   1720 
   1721   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
   1722 };
   1723 
   1724 typedef GTestMutexLock MutexLock;
   1725 
   1726 // Base class for ValueHolder<T>.  Allows a caller to hold and delete a value
   1727 // without knowing its type.
   1728 class ThreadLocalValueHolderBase {
   1729  public:
   1730   virtual ~ThreadLocalValueHolderBase() {}
   1731 };
   1732 
   1733 // Provides a way for a thread to send notifications to a ThreadLocal
   1734 // regardless of its parameter type.
   1735 class ThreadLocalBase {
   1736  public:
   1737   // Creates a new ValueHolder<T> object holding a default value passed to
   1738   // this ThreadLocal<T>'s constructor and returns it.  It is the caller's
   1739   // responsibility not to call this when the ThreadLocal<T> instance already
   1740   // has a value on the current thread.
   1741   virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
   1742 
   1743  protected:
   1744   ThreadLocalBase() {}
   1745   virtual ~ThreadLocalBase() {}
   1746 
   1747  private:
   1748   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
   1749 };
   1750 
   1751 // Maps a thread to a set of ThreadLocals that have values instantiated on that
   1752 // thread and notifies them when the thread exits.  A ThreadLocal instance is
   1753 // expected to persist until all threads it has values on have terminated.
   1754 class GTEST_API_ ThreadLocalRegistry {
   1755  public:
   1756   // Registers thread_local_instance as having value on the current thread.
   1757   // Returns a value that can be used to identify the thread from other threads.
   1758   static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
   1759       const ThreadLocalBase* thread_local_instance);
   1760 
   1761   // Invoked when a ThreadLocal instance is destroyed.
   1762   static void OnThreadLocalDestroyed(
   1763       const ThreadLocalBase* thread_local_instance);
   1764 };
   1765 
   1766 class GTEST_API_ ThreadWithParamBase {
   1767  public:
   1768   void Join();
   1769 
   1770  protected:
   1771   class Runnable {
   1772    public:
   1773     virtual ~Runnable() {}
   1774     virtual void Run() = 0;
   1775   };
   1776 
   1777   ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
   1778   virtual ~ThreadWithParamBase();
   1779 
   1780  private:
   1781   AutoHandle thread_;
   1782 };
   1783 
   1784 // Helper class for testing Google Test's multi-threading constructs.
   1785 template <typename T>
   1786 class ThreadWithParam : public ThreadWithParamBase {
   1787  public:
   1788   typedef void UserThreadFunc(T);
   1789 
   1790   ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
   1791       : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
   1792   }
   1793   virtual ~ThreadWithParam() {}
   1794 
   1795  private:
   1796   class RunnableImpl : public Runnable {
   1797    public:
   1798     RunnableImpl(UserThreadFunc* func, T param)
   1799         : func_(func),
   1800           param_(param) {
   1801     }
   1802     virtual ~RunnableImpl() {}
   1803     virtual void Run() {
   1804       func_(param_);
   1805     }
   1806 
   1807    private:
   1808     UserThreadFunc* const func_;
   1809     const T param_;
   1810 
   1811     GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
   1812   };
   1813 
   1814   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
   1815 };
   1816 
   1817 // Implements thread-local storage on Windows systems.
   1818 //
   1819 //   // Thread 1
   1820 //   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.
   1821 //
   1822 //   // Thread 2
   1823 //   tl.set(150);  // Changes the value for thread 2 only.
   1824 //   EXPECT_EQ(150, tl.get());
   1825 //
   1826 //   // Thread 1
   1827 //   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.
   1828 //   tl.set(200);
   1829 //   EXPECT_EQ(200, tl.get());
   1830 //
   1831 // The template type argument T must have a public copy constructor.
   1832 // In addition, the default ThreadLocal constructor requires T to have
   1833 // a public default constructor.
   1834 //
   1835 // The users of a TheadLocal instance have to make sure that all but one
   1836 // threads (including the main one) using that instance have exited before
   1837 // destroying it. Otherwise, the per-thread objects managed for them by the
   1838 // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
   1839 //
   1840 // Google Test only uses global ThreadLocal objects.  That means they
   1841 // will die after main() has returned.  Therefore, no per-thread
   1842 // object managed by Google Test will be leaked as long as all threads
   1843 // using Google Test have exited when main() returns.
   1844 template <typename T>
   1845 class ThreadLocal : public ThreadLocalBase {
   1846  public:
   1847   ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
   1848   explicit ThreadLocal(const T& value)
   1849       : default_factory_(new InstanceValueHolderFactory(value)) {}
   1850 
   1851   ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
   1852 
   1853   T* pointer() { return GetOrCreateValue(); }
   1854   const T* pointer() const { return GetOrCreateValue(); }
   1855   const T& get() const { return *pointer(); }
   1856   void set(const T& value) { *pointer() = value; }
   1857 
   1858  private:
   1859   // Holds a value of T.  Can be deleted via its base class without the caller
   1860   // knowing the type of T.
   1861   class ValueHolder : public ThreadLocalValueHolderBase {
   1862    public:
   1863     ValueHolder() : value_() {}
   1864     explicit ValueHolder(const T& value) : value_(value) {}
   1865 
   1866     T* pointer() { return &value_; }
   1867 
   1868    private:
   1869     T value_;
   1870     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
   1871   };
   1872 
   1873 
   1874   T* GetOrCreateValue() const {
   1875     return static_cast<ValueHolder*>(
   1876         ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
   1877   }
   1878 
   1879   virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
   1880     return default_factory_->MakeNewHolder();
   1881   }
   1882 
   1883   class ValueHolderFactory {
   1884    public:
   1885     ValueHolderFactory() {}
   1886     virtual ~ValueHolderFactory() {}
   1887     virtual ValueHolder* MakeNewHolder() const = 0;
   1888 
   1889    private:
   1890     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
   1891   };
   1892 
   1893   class DefaultValueHolderFactory : public ValueHolderFactory {
   1894    public:
   1895     DefaultValueHolderFactory() {}
   1896     virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
   1897 
   1898    private:
   1899     GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
   1900   };
   1901 
   1902   class InstanceValueHolderFactory : public ValueHolderFactory {
   1903    public:
   1904     explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
   1905     virtual ValueHolder* MakeNewHolder() const {
   1906       return new ValueHolder(value_);
   1907     }
   1908 
   1909    private:
   1910     const T value_;  // The value for each thread.
   1911 
   1912     GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
   1913   };
   1914 
   1915   scoped_ptr<ValueHolderFactory> default_factory_;
   1916 
   1917   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
   1918 };
   1919 
   1920 # elif GTEST_HAS_PTHREAD
   1921 
   1922 // MutexBase and Mutex implement mutex on pthreads-based platforms.
   1923 class MutexBase {
   1924  public:
   1925   // Acquires this mutex.
   1926   void Lock() {
   1927     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
   1928     owner_ = pthread_self();
   1929     has_owner_ = true;
   1930   }
   1931 
   1932   // Releases this mutex.
   1933   void Unlock() {
   1934     // Since the lock is being released the owner_ field should no longer be
   1935     // considered valid. We don't protect writing to has_owner_ here, as it's
   1936     // the caller's responsibility to ensure that the current thread holds the
   1937     // mutex when this is called.
   1938     has_owner_ = false;
   1939     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
   1940   }
   1941 
   1942   // Does nothing if the current thread holds the mutex. Otherwise, crashes
   1943   // with high probability.
   1944   void AssertHeld() const {
   1945     GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
   1946         << "The current thread is not holding the mutex @" << this;
   1947   }
   1948 
   1949   // A static mutex may be used before main() is entered.  It may even
   1950   // be used before the dynamic initialization stage.  Therefore we
   1951   // must be able to initialize a static mutex object at link time.
   1952   // This means MutexBase has to be a POD and its member variables
   1953   // have to be public.
   1954  public:
   1955   pthread_mutex_t mutex_;  // The underlying pthread mutex.
   1956   // has_owner_ indicates whether the owner_ field below contains a valid thread
   1957   // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
   1958   // accesses to the owner_ field should be protected by a check of this field.
   1959   // An alternative might be to memset() owner_ to all zeros, but there's no
   1960   // guarantee that a zero'd pthread_t is necessarily invalid or even different
   1961   // from pthread_self().
   1962   bool has_owner_;
   1963   pthread_t owner_;  // The thread holding the mutex.
   1964 };
   1965 
   1966 // Forward-declares a static mutex.
   1967 #  define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
   1968      extern ::testing::internal::MutexBase mutex
   1969 
   1970 // Defines and statically (i.e. at link time) initializes a static mutex.
   1971 // The initialization list here does not explicitly initialize each field,
   1972 // instead relying on default initialization for the unspecified fields. In
   1973 // particular, the owner_ field (a pthread_t) is not explicitly initialized.
   1974 // This allows initialization to work whether pthread_t is a scalar or struct.
   1975 // The flag -Wmissing-field-initializers must not be specified for this to work.
   1976 #  define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
   1977      ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false }
   1978 
   1979 // The Mutex class can only be used for mutexes created at runtime. It
   1980 // shares its API with MutexBase otherwise.
   1981 class Mutex : public MutexBase {
   1982  public:
   1983   Mutex() {
   1984     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
   1985     has_owner_ = false;
   1986   }
   1987   ~Mutex() {
   1988     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
   1989   }
   1990 
   1991  private:
   1992   GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
   1993 };
   1994 
   1995 // We cannot name this class MutexLock because the ctor declaration would
   1996 // conflict with a macro named MutexLock, which is defined on some
   1997 // platforms. That macro is used as a defensive measure to prevent against
   1998 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
   1999 // "MutexLock l(&mu)".  Hence the typedef trick below.
   2000 class GTestMutexLock {
   2001  public:
   2002   explicit GTestMutexLock(MutexBase* mutex)
   2003       : mutex_(mutex) { mutex_->Lock(); }
   2004 
   2005   ~GTestMutexLock() { mutex_->Unlock(); }
   2006 
   2007  private:
   2008   MutexBase* const mutex_;
   2009 
   2010   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
   2011 };
   2012 
   2013 typedef GTestMutexLock MutexLock;
   2014 
   2015 // Helpers for ThreadLocal.
   2016 
   2017 // pthread_key_create() requires DeleteThreadLocalValue() to have
   2018 // C-linkage.  Therefore it cannot be templatized to access
   2019 // ThreadLocal<T>.  Hence the need for class
   2020 // ThreadLocalValueHolderBase.
   2021 class ThreadLocalValueHolderBase {
   2022  public:
   2023   virtual ~ThreadLocalValueHolderBase() {}
   2024 };
   2025 
   2026 // Called by pthread to delete thread-local data stored by
   2027 // pthread_setspecific().
   2028 extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
   2029   delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
   2030 }
   2031 
   2032 // Implements thread-local storage on pthreads-based systems.
   2033 template <typename T>
   2034 class ThreadLocal {
   2035  public:
   2036   ThreadLocal()
   2037       : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
   2038   explicit ThreadLocal(const T& value)
   2039       : key_(CreateKey()),
   2040         default_factory_(new InstanceValueHolderFactory(value)) {}
   2041 
   2042   ~ThreadLocal() {
   2043     // Destroys the managed object for the current thread, if any.
   2044     DeleteThreadLocalValue(pthread_getspecific(key_));
   2045 
   2046     // Releases resources associated with the key.  This will *not*
   2047     // delete managed objects for other threads.
   2048     GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
   2049   }
   2050 
   2051   T* pointer() { return GetOrCreateValue(); }
   2052   const T* pointer() const { return GetOrCreateValue(); }
   2053   const T& get() const { return *pointer(); }
   2054   void set(const T& value) { *pointer() = value; }
   2055 
   2056  private:
   2057   // Holds a value of type T.
   2058   class ValueHolder : public ThreadLocalValueHolderBase {
   2059    public:
   2060     ValueHolder() : value_() {}
   2061     explicit ValueHolder(const T& value) : value_(value) {}
   2062 
   2063     T* pointer() { return &value_; }
   2064 
   2065    private:
   2066     T value_;
   2067     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
   2068   };
   2069 
   2070   static pthread_key_t CreateKey() {
   2071     pthread_key_t key;
   2072     // When a thread exits, DeleteThreadLocalValue() will be called on
   2073     // the object managed for that thread.
   2074     GTEST_CHECK_POSIX_SUCCESS_(
   2075         pthread_key_create(&key, &DeleteThreadLocalValue));
   2076     return key;
   2077   }
   2078 
   2079   T* GetOrCreateValue() const {
   2080     ThreadLocalValueHolderBase* const holder =
   2081         static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
   2082     if (holder != NULL) {
   2083       return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
   2084     }
   2085 
   2086     ValueHolder* const new_holder = default_factory_->MakeNewHolder();
   2087     ThreadLocalValueHolderBase* const holder_base = new_holder;
   2088     GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
   2089     return new_holder->pointer();
   2090   }
   2091 
   2092   class ValueHolderFactory {
   2093    public:
   2094     ValueHolderFactory() {}
   2095     virtual ~ValueHolderFactory() {}
   2096     virtual ValueHolder* MakeNewHolder() const = 0;
   2097 
   2098    private:
   2099     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
   2100   };
   2101 
   2102   class DefaultValueHolderFactory : public ValueHolderFactory {
   2103    public:
   2104     DefaultValueHolderFactory() {}
   2105     virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
   2106 
   2107    private:
   2108     GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
   2109   };
   2110 
   2111   class InstanceValueHolderFactory : public ValueHolderFactory {
   2112    public:
   2113     explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
   2114     virtual ValueHolder* MakeNewHolder() const {
   2115       return new ValueHolder(value_);
   2116     }
   2117 
   2118    private:
   2119     const T value_;  // The value for each thread.
   2120 
   2121     GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
   2122   };
   2123 
   2124   // A key pthreads uses for looking up per-thread values.
   2125   const pthread_key_t key_;
   2126   scoped_ptr<ValueHolderFactory> default_factory_;
   2127 
   2128   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
   2129 };
   2130 
   2131 # endif  // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
   2132 
   2133 #else  // GTEST_IS_THREADSAFE
   2134 
   2135 // A dummy implementation of synchronization primitives (mutex, lock,
   2136 // and thread-local variable).  Necessary for compiling Google Test where
   2137 // mutex is not supported - using Google Test in multiple threads is not
   2138 // supported on such platforms.
   2139 
   2140 class Mutex {
   2141  public:
   2142   Mutex() {}
   2143   void Lock() {}
   2144   void Unlock() {}
   2145   void AssertHeld() const {}
   2146 };
   2147 
   2148 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
   2149   extern ::testing::internal::Mutex mutex
   2150 
   2151 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
   2152 
   2153 // We cannot name this class MutexLock because the ctor declaration would
   2154 // conflict with a macro named MutexLock, which is defined on some
   2155 // platforms. That macro is used as a defensive measure to prevent against
   2156 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
   2157 // "MutexLock l(&mu)".  Hence the typedef trick below.
   2158 class GTestMutexLock {
   2159  public:
   2160   explicit GTestMutexLock(Mutex*) {}  // NOLINT
   2161 };
   2162 
   2163 typedef GTestMutexLock MutexLock;
   2164 
   2165 template <typename T>
   2166 class ThreadLocal {
   2167  public:
   2168   ThreadLocal() : value_() {}
   2169   explicit ThreadLocal(const T& value) : value_(value) {}
   2170   T* pointer() { return &value_; }
   2171   const T* pointer() const { return &value_; }
   2172   const T& get() const { return value_; }
   2173   void set(const T& value) { value_ = value; }
   2174  private:
   2175   T value_;
   2176 };
   2177 
   2178 #endif  // GTEST_IS_THREADSAFE
   2179 
   2180 // Returns the number of threads running in the process, or 0 to indicate that
   2181 // we cannot detect it.
   2182 GTEST_API_ size_t GetThreadCount();
   2183 
   2184 // Passing non-POD classes through ellipsis (...) crashes the ARM
   2185 // compiler and generates a warning in Sun Studio.  The Nokia Symbian
   2186 // and the IBM XL C/C++ compiler try to instantiate a copy constructor
   2187 // for objects passed through ellipsis (...), failing for uncopyable
   2188 // objects.  We define this to ensure that only POD is passed through
   2189 // ellipsis on these systems.
   2190 #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC)
   2191 // We lose support for NULL detection where the compiler doesn't like
   2192 // passing non-POD classes through ellipsis (...).
   2193 # define GTEST_ELLIPSIS_NEEDS_POD_ 1
   2194 #else
   2195 # define GTEST_CAN_COMPARE_NULL 1
   2196 #endif
   2197 
   2198 // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
   2199 // const T& and const T* in a function template.  These compilers
   2200 // _can_ decide between class template specializations for T and T*,
   2201 // so a tr1::type_traits-like is_pointer works.
   2202 #if defined(__SYMBIAN32__) || defined(__IBMCPP__)
   2203 # define GTEST_NEEDS_IS_POINTER_ 1
   2204 #endif
   2205 
   2206 template <bool bool_value>
   2207 struct bool_constant {
   2208   typedef bool_constant<bool_value> type;
   2209   static const bool value = bool_value;
   2210 };
   2211 template <bool bool_value> const bool bool_constant<bool_value>::value;
   2212 
   2213 typedef bool_constant<false> false_type;
   2214 typedef bool_constant<true> true_type;
   2215 
   2216 template <typename T>
   2217 struct is_pointer : public false_type {};
   2218 
   2219 template <typename T>
   2220 struct is_pointer<T*> : public true_type {};
   2221 
   2222 template <typename Iterator>
   2223 struct IteratorTraits {
   2224   typedef typename Iterator::value_type value_type;
   2225 };
   2226 
   2227 template <typename T>
   2228 struct IteratorTraits<T*> {
   2229   typedef T value_type;
   2230 };
   2231 
   2232 template <typename T>
   2233 struct IteratorTraits<const T*> {
   2234   typedef T value_type;
   2235 };
   2236 
   2237 #if GTEST_OS_WINDOWS
   2238 # define GTEST_PATH_SEP_ "\\"
   2239 # define GTEST_HAS_ALT_PATH_SEP_ 1
   2240 // The biggest signed integer type the compiler supports.
   2241 typedef __int64 BiggestInt;
   2242 #else
   2243 # define GTEST_PATH_SEP_ "/"
   2244 # define GTEST_HAS_ALT_PATH_SEP_ 0
   2245 typedef long long BiggestInt;  // NOLINT
   2246 #endif  // GTEST_OS_WINDOWS
   2247 
   2248 // Utilities for char.
   2249 
   2250 // isspace(int ch) and friends accept an unsigned char or EOF.  char
   2251 // may be signed, depending on the compiler (or compiler flags).
   2252 // Therefore we need to cast a char to unsigned char before calling
   2253 // isspace(), etc.
   2254 
   2255 inline bool IsAlpha(char ch) {
   2256   return isalpha(static_cast<unsigned char>(ch)) != 0;
   2257 }
   2258 inline bool IsAlNum(char ch) {
   2259   return isalnum(static_cast<unsigned char>(ch)) != 0;
   2260 }
   2261 inline bool IsDigit(char ch) {
   2262   return isdigit(static_cast<unsigned char>(ch)) != 0;
   2263 }
   2264 inline bool IsLower(char ch) {
   2265   return islower(static_cast<unsigned char>(ch)) != 0;
   2266 }
   2267 inline bool IsSpace(char ch) {
   2268   return isspace(static_cast<unsigned char>(ch)) != 0;
   2269 }
   2270 inline bool IsUpper(char ch) {
   2271   return isupper(static_cast<unsigned char>(ch)) != 0;
   2272 }
   2273 inline bool IsXDigit(char ch) {
   2274   return isxdigit(static_cast<unsigned char>(ch)) != 0;
   2275 }
   2276 inline bool IsXDigit(wchar_t ch) {
   2277   const unsigned char low_byte = static_cast<unsigned char>(ch);
   2278   return ch == low_byte && isxdigit(low_byte) != 0;
   2279 }
   2280 
   2281 inline char ToLower(char ch) {
   2282   return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
   2283 }
   2284 inline char ToUpper(char ch) {
   2285   return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
   2286 }
   2287 
   2288 inline std::string StripTrailingSpaces(std::string str) {
   2289   std::string::iterator it = str.end();
   2290   while (it != str.begin() && IsSpace(*--it))
   2291     it = str.erase(it);
   2292   return str;
   2293 }
   2294 
   2295 // The testing::internal::posix namespace holds wrappers for common
   2296 // POSIX functions.  These wrappers hide the differences between
   2297 // Windows/MSVC and POSIX systems.  Since some compilers define these
   2298 // standard functions as macros, the wrapper cannot have the same name
   2299 // as the wrapped function.
   2300 
   2301 namespace posix {
   2302 
   2303 // Functions with a different name on Windows.
   2304 
   2305 #if GTEST_OS_WINDOWS
   2306 
   2307 typedef struct _stat StatStruct;
   2308 
   2309 # ifdef __BORLANDC__
   2310 inline int IsATTY(int fd) { return isatty(fd); }
   2311 inline int StrCaseCmp(const char* s1, const char* s2) {
   2312   return stricmp(s1, s2);
   2313 }
   2314 inline char* StrDup(const char* src) { return strdup(src); }
   2315 # else  // !__BORLANDC__
   2316 #  if GTEST_OS_WINDOWS_MOBILE
   2317 inline int IsATTY(int /* fd */) { return 0; }
   2318 #  else
   2319 inline int IsATTY(int fd) { return _isatty(fd); }
   2320 #  endif  // GTEST_OS_WINDOWS_MOBILE
   2321 inline int StrCaseCmp(const char* s1, const char* s2) {
   2322   return _stricmp(s1, s2);
   2323 }
   2324 inline char* StrDup(const char* src) { return _strdup(src); }
   2325 # endif  // __BORLANDC__
   2326 
   2327 # if GTEST_OS_WINDOWS_MOBILE
   2328 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
   2329 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
   2330 // time and thus not defined there.
   2331 # else
   2332 inline int FileNo(FILE* file) { return _fileno(file); }
   2333 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
   2334 inline int RmDir(const char* dir) { return _rmdir(dir); }
   2335 inline bool IsDir(const StatStruct& st) {
   2336   return (_S_IFDIR & st.st_mode) != 0;
   2337 }
   2338 # endif  // GTEST_OS_WINDOWS_MOBILE
   2339 
   2340 #else
   2341 
   2342 typedef struct stat StatStruct;
   2343 
   2344 inline int FileNo(FILE* file) { return fileno(file); }
   2345 inline int IsATTY(int fd) { return isatty(fd); }
   2346 inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
   2347 inline int StrCaseCmp(const char* s1, const char* s2) {
   2348   return strcasecmp(s1, s2);
   2349 }
   2350 inline char* StrDup(const char* src) { return strdup(src); }
   2351 inline int RmDir(const char* dir) { return rmdir(dir); }
   2352 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
   2353 
   2354 #endif  // GTEST_OS_WINDOWS
   2355 
   2356 // Functions deprecated by MSVC 8.0.
   2357 
   2358 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
   2359 
   2360 inline const char* StrNCpy(char* dest, const char* src, size_t n) {
   2361   return strncpy(dest, src, n);
   2362 }
   2363 
   2364 // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
   2365 // StrError() aren't needed on Windows CE at this time and thus not
   2366 // defined there.
   2367 
   2368 #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
   2369 inline int ChDir(const char* dir) { return chdir(dir); }
   2370 #endif
   2371 inline FILE* FOpen(const char* path, const char* mode) {
   2372   return fopen(path, mode);
   2373 }
   2374 #if !GTEST_OS_WINDOWS_MOBILE
   2375 inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
   2376   return freopen(path, mode, stream);
   2377 }
   2378 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
   2379 #endif
   2380 inline int FClose(FILE* fp) { return fclose(fp); }
   2381 #if !GTEST_OS_WINDOWS_MOBILE
   2382 inline int Read(int fd, void* buf, unsigned int count) {
   2383   return static_cast<int>(read(fd, buf, count));
   2384 }
   2385 inline int Write(int fd, const void* buf, unsigned int count) {
   2386   return static_cast<int>(write(fd, buf, count));
   2387 }
   2388 inline int Close(int fd) { return close(fd); }
   2389 inline const char* StrError(int errnum) { return strerror(errnum); }
   2390 #endif
   2391 inline const char* GetEnv(const char* name) {
   2392 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT
   2393   // We are on Windows CE, which has no environment variables.
   2394   static_cast<void>(name);  // To prevent 'unused argument' warning.
   2395   return NULL;
   2396 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
   2397   // Environment variables which we programmatically clear will be set to the
   2398   // empty string rather than unset (NULL).  Handle that case.
   2399   const char* const env = getenv(name);
   2400   return (env != NULL && env[0] != '\0') ? env : NULL;
   2401 #else
   2402   return getenv(name);
   2403 #endif
   2404 }
   2405 
   2406 GTEST_DISABLE_MSC_WARNINGS_POP_()
   2407 
   2408 #if GTEST_OS_WINDOWS_MOBILE
   2409 // Windows CE has no C library. The abort() function is used in
   2410 // several places in Google Test. This implementation provides a reasonable
   2411 // imitation of standard behaviour.
   2412 void Abort();
   2413 #else
   2414 inline void Abort() { abort(); }
   2415 #endif  // GTEST_OS_WINDOWS_MOBILE
   2416 
   2417 }  // namespace posix
   2418 
   2419 // MSVC "deprecates" snprintf and issues warnings wherever it is used.  In
   2420 // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
   2421 // MSVC-based platforms.  We map the GTEST_SNPRINTF_ macro to the appropriate
   2422 // function in order to achieve that.  We use macro definition here because
   2423 // snprintf is a variadic function.
   2424 #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
   2425 // MSVC 2005 and above support variadic macros.
   2426 # define GTEST_SNPRINTF_(buffer, size, format, ...) \
   2427      _snprintf_s(buffer, size, size, format, __VA_ARGS__)
   2428 #elif defined(_MSC_VER)
   2429 // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't
   2430 // complain about _snprintf.
   2431 # define GTEST_SNPRINTF_ _snprintf
   2432 #else
   2433 # define GTEST_SNPRINTF_ snprintf
   2434 #endif
   2435 
   2436 // The maximum number a BiggestInt can represent.  This definition
   2437 // works no matter BiggestInt is represented in one's complement or
   2438 // two's complement.
   2439 //
   2440 // We cannot rely on numeric_limits in STL, as __int64 and long long
   2441 // are not part of standard C++ and numeric_limits doesn't need to be
   2442 // defined for them.
   2443 const BiggestInt kMaxBiggestInt =
   2444     ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
   2445 
   2446 // This template class serves as a compile-time function from size to
   2447 // type.  It maps a size in bytes to a primitive type with that
   2448 // size. e.g.
   2449 //
   2450 //   TypeWithSize<4>::UInt
   2451 //
   2452 // is typedef-ed to be unsigned int (unsigned integer made up of 4
   2453 // bytes).
   2454 //
   2455 // Such functionality should belong to STL, but I cannot find it
   2456 // there.
   2457 //
   2458 // Google Test uses this class in the implementation of floating-point
   2459 // comparison.
   2460 //
   2461 // For now it only handles UInt (unsigned int) as that's all Google Test
   2462 // needs.  Other types can be easily added in the future if need
   2463 // arises.
   2464 template <size_t size>
   2465 class TypeWithSize {
   2466  public:
   2467   // This prevents the user from using TypeWithSize<N> with incorrect
   2468   // values of N.
   2469   typedef void UInt;
   2470 };
   2471 
   2472 // The specialization for size 4.
   2473 template <>
   2474 class TypeWithSize<4> {
   2475  public:
   2476   // unsigned int has size 4 in both gcc and MSVC.
   2477   //
   2478   // As base/basictypes.h doesn't compile on Windows, we cannot use
   2479   // uint32, uint64, and etc here.
   2480   typedef int Int;
   2481   typedef unsigned int UInt;
   2482 };
   2483 
   2484 // The specialization for size 8.
   2485 template <>
   2486 class TypeWithSize<8> {
   2487  public:
   2488 #if GTEST_OS_WINDOWS
   2489   typedef __int64 Int;
   2490   typedef unsigned __int64 UInt;
   2491 #else
   2492   typedef long long Int;  // NOLINT
   2493   typedef unsigned long long UInt;  // NOLINT
   2494 #endif  // GTEST_OS_WINDOWS
   2495 };
   2496 
   2497 // Integer types of known sizes.
   2498 typedef TypeWithSize<4>::Int Int32;
   2499 typedef TypeWithSize<4>::UInt UInt32;
   2500 typedef TypeWithSize<8>::Int Int64;
   2501 typedef TypeWithSize<8>::UInt UInt64;
   2502 typedef TypeWithSize<8>::Int TimeInMillis;  // Represents time in milliseconds.
   2503 
   2504 // Utilities for command line flags and environment variables.
   2505 
   2506 // Macro for referencing flags.
   2507 #if !defined(GTEST_FLAG)
   2508 # define GTEST_FLAG(name) FLAGS_gtest_##name
   2509 #endif  // !defined(GTEST_FLAG)
   2510 
   2511 #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
   2512 # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
   2513 #endif  // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
   2514 
   2515 #if !defined(GTEST_DECLARE_bool_)
   2516 # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
   2517 
   2518 // Macros for declaring flags.
   2519 # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
   2520 # define GTEST_DECLARE_int32_(name) \
   2521     GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
   2522 #define GTEST_DECLARE_string_(name) \
   2523     GTEST_API_ extern ::std::string GTEST_FLAG(name)
   2524 
   2525 // Macros for defining flags.
   2526 #define GTEST_DEFINE_bool_(name, default_val, doc) \
   2527     GTEST_API_ bool GTEST_FLAG(name) = (default_val)
   2528 #define GTEST_DEFINE_int32_(name, default_val, doc) \
   2529     GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
   2530 #define GTEST_DEFINE_string_(name, default_val, doc) \
   2531     GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
   2532 
   2533 #endif  // !defined(GTEST_DECLARE_bool_)
   2534 
   2535 // Thread annotations
   2536 #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
   2537 # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
   2538 # define GTEST_LOCK_EXCLUDED_(locks)
   2539 #endif  // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
   2540 
   2541 // Parses 'str' for a 32-bit signed integer.  If successful, writes the result
   2542 // to *value and returns true; otherwise leaves *value unchanged and returns
   2543 // false.
   2544 // TODO(chandlerc): Find a better way to refactor flag and environment parsing
   2545 // out of both gtest-port.cc and gtest.cc to avoid exporting this utility
   2546 // function.
   2547 bool ParseInt32(const Message& src_text, const char* str, Int32* value);
   2548 
   2549 // Parses a bool/Int32/string from the environment variable
   2550 // corresponding to the given Google Test flag.
   2551 bool BoolFromGTestEnv(const char* flag, bool default_val);
   2552 GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
   2553 const char* StringFromGTestEnv(const char* flag, const char* default_val);
   2554 
   2555 }  // namespace internal
   2556 }  // namespace testing
   2557 
   2558 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
   2559 
   2560