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.  They are subject to change without notice.  DO NOT USE
     34 // THEM IN USER CODE.
     35 //
     36 // This file is fundamental to Google Test.  All other Google Test source
     37 // files are expected to #include this.  Therefore, it cannot #include
     38 // any other Google Test header.
     39 
     40 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
     41 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
     42 
     43 // The user can define the following macros in the build script to
     44 // control Google Test's behavior.  If the user doesn't define a macro
     45 // in this list, Google Test will define it.
     46 //
     47 //   GTEST_HAS_CLONE          - Define it to 1/0 to indicate that clone(2)
     48 //                              is/isn't available.
     49 //   GTEST_HAS_EXCEPTIONS     - Define it to 1/0 to indicate that exceptions
     50 //                              are enabled.
     51 //   GTEST_HAS_GLOBAL_STRING  - Define it to 1/0 to indicate that ::string
     52 //                              is/isn't available (some systems define
     53 //                              ::string, which is different to std::string).
     54 //   GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
     55 //                              is/isn't available (some systems define
     56 //                              ::wstring, which is different to std::wstring).
     57 //   GTEST_HAS_POSIX_RE       - Define it to 1/0 to indicate that POSIX regular
     58 //                              expressions are/aren't available.
     59 //   GTEST_HAS_PTHREAD        - Define it to 1/0 to indicate that <pthread.h>
     60 //                              is/isn't available.
     61 //   GTEST_HAS_RTTI           - Define it to 1/0 to indicate that RTTI is/isn't
     62 //                              enabled.
     63 //   GTEST_HAS_STD_WSTRING    - Define it to 1/0 to indicate that
     64 //                              std::wstring does/doesn't work (Google Test can
     65 //                              be used where std::wstring is unavailable).
     66 //   GTEST_HAS_TR1_TUPLE      - Define it to 1/0 to indicate tr1::tuple
     67 //                              is/isn't available.
     68 //   GTEST_HAS_SEH            - Define it to 1/0 to indicate whether the
     69 //                              compiler supports Microsoft's "Structured
     70 //                              Exception Handling".
     71 //   GTEST_HAS_STREAM_REDIRECTION
     72 //                            - Define it to 1/0 to indicate whether the
     73 //                              platform supports I/O stream redirection using
     74 //                              dup() and dup2().
     75 //   GTEST_USE_OWN_TR1_TUPLE  - Define it to 1/0 to indicate whether Google
     76 //                              Test's own tr1 tuple implementation should be
     77 //                              used.  Unused when the user sets
     78 //                              GTEST_HAS_TR1_TUPLE to 0.
     79 //   GTEST_LANG_CXX11         - Define it to 1/0 to indicate that Google Test
     80 //                              is building in C++11/C++98 mode.
     81 //   GTEST_LINKED_AS_SHARED_LIBRARY
     82 //                            - Define to 1 when compiling tests that use
     83 //                              Google Test as a shared library (known as
     84 //                              DLL on Windows).
     85 //   GTEST_CREATE_SHARED_LIBRARY
     86 //                            - Define to 1 when compiling Google Test itself
     87 //                              as a shared library.
     88 
     89 // This header defines the following utilities:
     90 //
     91 // Macros indicating the current platform (defined to 1 if compiled on
     92 // the given platform; otherwise undefined):
     93 //   GTEST_OS_AIX      - IBM AIX
     94 //   GTEST_OS_CYGWIN   - Cygwin
     95 //   GTEST_OS_HPUX     - HP-UX
     96 //   GTEST_OS_LINUX    - Linux
     97 //     GTEST_OS_LINUX_ANDROID - Google Android
     98 //   GTEST_OS_MAC      - Mac OS X
     99 //     GTEST_OS_IOS    - iOS
    100 //       GTEST_OS_IOS_SIMULATOR - iOS simulator
    101 //   GTEST_OS_NACL     - Google Native Client (NaCl)
    102 //   GTEST_OS_OPENBSD  - OpenBSD
    103 //   GTEST_OS_QNX      - QNX
    104 //   GTEST_OS_SOLARIS  - Sun Solaris
    105 //   GTEST_OS_SYMBIAN  - Symbian
    106 //   GTEST_OS_WINDOWS  - Windows (Desktop, MinGW, or Mobile)
    107 //     GTEST_OS_WINDOWS_DESKTOP  - Windows Desktop
    108 //     GTEST_OS_WINDOWS_MINGW    - MinGW
    109 //     GTEST_OS_WINDOWS_MOBILE   - Windows Mobile
    110 //   GTEST_OS_ZOS      - z/OS
    111 //
    112 // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
    113 // most stable support.  Since core members of the Google Test project
    114 // don't have access to other platforms, support for them may be less
    115 // stable.  If you notice any problems on your platform, please notify
    116 // googletestframework (at) googlegroups.com (patches for fixing them are
    117 // even more welcome!).
    118 //
    119 // Note that it is possible that none of the GTEST_OS_* macros are defined.
    120 //
    121 // Macros indicating available Google Test features (defined to 1 if
    122 // the corresponding feature is supported; otherwise undefined):
    123 //   GTEST_HAS_COMBINE      - the Combine() function (for value-parameterized
    124 //                            tests)
    125 //   GTEST_HAS_DEATH_TEST   - death tests
    126 //   GTEST_HAS_PARAM_TEST   - value-parameterized tests
    127 //   GTEST_HAS_TYPED_TEST   - typed tests
    128 //   GTEST_HAS_TYPED_TEST_P - type-parameterized tests
    129 //   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used. Do not confuse with
    130 //                            GTEST_HAS_POSIX_RE (see above) which users can
    131 //                            define themselves.
    132 //   GTEST_USES_SIMPLE_RE   - our own simple regex is used;
    133 //                            the above two are mutually exclusive.
    134 //   GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
    135 //
    136 // Macros for basic C++ coding:
    137 //   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
    138 //   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a
    139 //                              variable don't have to be used.
    140 //   GTEST_DISALLOW_ASSIGN_   - disables operator=.
    141 //   GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
    142 //   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.
    143 //
    144 // Synchronization:
    145 //   Mutex, MutexLock, ThreadLocal, GetThreadCount()
    146 //                  - synchronization primitives.
    147 //   GTEST_IS_THREADSAFE - defined to 1 to indicate that the above
    148 //                         synchronization primitives have real implementations
    149 //                         and Google Test is thread-safe; or 0 otherwise.
    150 //
    151 // Template meta programming:
    152 //   is_pointer     - as in TR1; needed on Symbian and IBM XL C/C++ only.
    153 //   IteratorTraits - partial implementation of std::iterator_traits, which
    154 //                    is not available in libCstd when compiled with Sun C++.
    155 //
    156 // Smart pointers:
    157 //   scoped_ptr     - as in TR2.
    158 //
    159 // Regular expressions:
    160 //   RE             - a simple regular expression class using the POSIX
    161 //                    Extended Regular Expression syntax on UNIX-like
    162 //                    platforms, or a reduced regular exception syntax on
    163 //                    other platforms, including Windows.
    164 //
    165 // Logging:
    166 //   GTEST_LOG_()   - logs messages at the specified severity level.
    167 //   LogToStderr()  - directs all log messages to stderr.
    168 //   FlushInfoLog() - flushes informational log messages.
    169 //
    170 // Stdout and stderr capturing:
    171 //   CaptureStdout()     - starts capturing stdout.
    172 //   GetCapturedStdout() - stops capturing stdout and returns the captured
    173 //                         string.
    174 //   CaptureStderr()     - starts capturing stderr.
    175 //   GetCapturedStderr() - stops capturing stderr and returns the captured
    176 //                         string.
    177 //
    178 // Integer types:
    179 //   TypeWithSize   - maps an integer to a int type.
    180 //   Int32, UInt32, Int64, UInt64, TimeInMillis
    181 //                  - integers of known sizes.
    182 //   BiggestInt     - the biggest signed integer type.
    183 //
    184 // Command-line utilities:
    185 //   GTEST_FLAG()       - references a flag.
    186 //   GTEST_DECLARE_*()  - declares a flag.
    187 //   GTEST_DEFINE_*()   - defines a flag.
    188 //   GetInjectableArgvs() - returns the command line as a vector of strings.
    189 //
    190 // Environment variable utilities:
    191 //   GetEnv()             - gets the value of an environment variable.
    192 //   BoolFromGTestEnv()   - parses a bool environment variable.
    193 //   Int32FromGTestEnv()  - parses an Int32 environment variable.
    194 //   StringFromGTestEnv() - parses a string environment variable.
    195 
    196 #include <ctype.h>   // for isspace, etc
    197 #include <stddef.h>  // for ptrdiff_t
    198 #include <stdlib.h>
    199 #include <stdio.h>
    200 #include <string.h>
    201 #ifndef _WIN32_WCE
    202 # include <sys/types.h>
    203 # include <sys/stat.h>
    204 #endif  // !_WIN32_WCE
    205 
    206 #if defined __APPLE__
    207 # include <AvailabilityMacros.h>
    208 # include <TargetConditionals.h>
    209 #endif
    210 
    211 #include <iostream>  // NOLINT
    212 #include <sstream>  // NOLINT
    213 #include <string>  // NOLINT
    214 
    215 #define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
    216 #define GTEST_FLAG_PREFIX_ "gtest_"
    217 #define GTEST_FLAG_PREFIX_DASH_ "gtest-"
    218 #define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
    219 #define GTEST_NAME_ "Google Test"
    220 #define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/"
    221 
    222 // Determines the version of gcc that is used to compile this.
    223 #ifdef __GNUC__
    224 // 40302 means version 4.3.2.
    225 # define GTEST_GCC_VER_ \
    226     (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
    227 #endif  // __GNUC__
    228 
    229 // Determines the platform on which Google Test is compiled.
    230 #ifdef __CYGWIN__
    231 # define GTEST_OS_CYGWIN 1
    232 #elif defined __SYMBIAN32__
    233 # define GTEST_OS_SYMBIAN 1
    234 #elif defined _WIN32
    235 # define GTEST_OS_WINDOWS 1
    236 # ifdef _WIN32_WCE
    237 #  define GTEST_OS_WINDOWS_MOBILE 1
    238 # elif defined(__MINGW__) || defined(__MINGW32__)
    239 #  define GTEST_OS_WINDOWS_MINGW 1
    240 # else
    241 #  define GTEST_OS_WINDOWS_DESKTOP 1
    242 # endif  // _WIN32_WCE
    243 #elif defined __APPLE__
    244 # define GTEST_OS_MAC 1
    245 # if TARGET_OS_IPHONE
    246 #  define GTEST_OS_IOS 1
    247 #  if TARGET_IPHONE_SIMULATOR
    248 #   define GTEST_OS_IOS_SIMULATOR 1
    249 #  endif
    250 # endif
    251 #elif defined __linux__
    252 # define GTEST_OS_LINUX 1
    253 # if defined __ANDROID__
    254 #  define GTEST_OS_LINUX_ANDROID 1
    255 # endif
    256 #elif defined __MVS__
    257 # define GTEST_OS_ZOS 1
    258 #elif defined(__sun) && defined(__SVR4)
    259 # define GTEST_OS_SOLARIS 1
    260 #elif defined(_AIX)
    261 # define GTEST_OS_AIX 1
    262 #elif defined(__hpux)
    263 # define GTEST_OS_HPUX 1
    264 #elif defined __native_client__
    265 # define GTEST_OS_NACL 1
    266 #elif defined __OpenBSD__
    267 # define GTEST_OS_OPENBSD 1
    268 #elif defined __QNX__
    269 # define GTEST_OS_QNX 1
    270 #endif  // __CYGWIN__
    271 
    272 #ifndef GTEST_LANG_CXX11
    273 // gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when
    274 // -std={c,gnu}++{0x,11} is passed.  The C++11 standard specifies a
    275 // value for __cplusplus, and recent versions of clang, gcc, and
    276 // probably other compilers set that too in C++11 mode.
    277 # if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L
    278 // Compiling in at least C++11 mode.
    279 #  define GTEST_LANG_CXX11 1
    280 # else
    281 #  define GTEST_LANG_CXX11 0
    282 # endif
    283 #endif
    284 
    285 // Brings in definitions for functions used in the testing::internal::posix
    286 // namespace (read, write, close, chdir, isatty, stat). We do not currently
    287 // use them on Windows Mobile.
    288 #if !GTEST_OS_WINDOWS
    289 // This assumes that non-Windows OSes provide unistd.h. For OSes where this
    290 // is not the case, we need to include headers that provide the functions
    291 // mentioned above.
    292 # include <unistd.h>
    293 # include <strings.h>
    294 #elif !GTEST_OS_WINDOWS_MOBILE
    295 # include <direct.h>
    296 # include <io.h>
    297 #endif
    298 
    299 #if GTEST_OS_LINUX_ANDROID
    300 // Used to define __ANDROID_API__ matching the target NDK API level.
    301 #  include <android/api-level.h>  // NOLINT
    302 #endif
    303 
    304 // Defines this to true iff Google Test can use POSIX regular expressions.
    305 #ifndef GTEST_HAS_POSIX_RE
    306 # if GTEST_OS_LINUX_ANDROID
    307 // On Android, <regex.h> is only available starting with Gingerbread.
    308 #  define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
    309 # else
    310 #  define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS)
    311 # endif
    312 #endif
    313 
    314 #if GTEST_HAS_POSIX_RE
    315 
    316 // On some platforms, <regex.h> needs someone to define size_t, and
    317 // won't compile otherwise.  We can #include it here as we already
    318 // included <stdlib.h>, which is guaranteed to define size_t through
    319 // <stddef.h>.
    320 # include <regex.h>  // NOLINT
    321 
    322 # define GTEST_USES_POSIX_RE 1
    323 
    324 #elif GTEST_OS_WINDOWS
    325 
    326 // <regex.h> is not available on Windows.  Use our own simple regex
    327 // implementation instead.
    328 # define GTEST_USES_SIMPLE_RE 1
    329 
    330 #else
    331 
    332 // <regex.h> may not be available on this platform.  Use our own
    333 // simple regex implementation instead.
    334 # define GTEST_USES_SIMPLE_RE 1
    335 
    336 #endif  // GTEST_HAS_POSIX_RE
    337 
    338 #ifndef GTEST_HAS_EXCEPTIONS
    339 // The user didn't tell us whether exceptions are enabled, so we need
    340 // to figure it out.
    341 # if defined(_MSC_VER) || defined(__BORLANDC__)
    342 // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
    343 // macro to enable exceptions, so we'll do the same.
    344 // Assumes that exceptions are enabled by default.
    345 #  ifndef _HAS_EXCEPTIONS
    346 #   define _HAS_EXCEPTIONS 1
    347 #  endif  // _HAS_EXCEPTIONS
    348 #  define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
    349 # elif defined(__GNUC__) && __EXCEPTIONS
    350 // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
    351 #  define GTEST_HAS_EXCEPTIONS 1
    352 # elif defined(__SUNPRO_CC)
    353 // Sun Pro CC supports exceptions.  However, there is no compile-time way of
    354 // detecting whether they are enabled or not.  Therefore, we assume that
    355 // they are enabled unless the user tells us otherwise.
    356 #  define GTEST_HAS_EXCEPTIONS 1
    357 # elif defined(__IBMCPP__) && __EXCEPTIONS
    358 // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
    359 #  define GTEST_HAS_EXCEPTIONS 1
    360 # elif defined(__HP_aCC)
    361 // Exception handling is in effect by default in HP aCC compiler. It has to
    362 // be turned of by +noeh compiler option if desired.
    363 #  define GTEST_HAS_EXCEPTIONS 1
    364 # else
    365 // For other compilers, we assume exceptions are disabled to be
    366 // conservative.
    367 #  define GTEST_HAS_EXCEPTIONS 0
    368 # endif  // defined(_MSC_VER) || defined(__BORLANDC__)
    369 #endif  // GTEST_HAS_EXCEPTIONS
    370 
    371 #if !defined(GTEST_HAS_STD_STRING)
    372 // Even though we don't use this macro any longer, we keep it in case
    373 // some clients still depend on it.
    374 # define GTEST_HAS_STD_STRING 1
    375 #elif !GTEST_HAS_STD_STRING
    376 // The user told us that ::std::string isn't available.
    377 # error "Google Test cannot be used where ::std::string isn't available."
    378 #endif  // !defined(GTEST_HAS_STD_STRING)
    379 
    380 #ifndef GTEST_HAS_GLOBAL_STRING
    381 // The user didn't tell us whether ::string is available, so we need
    382 // to figure it out.
    383 
    384 # define GTEST_HAS_GLOBAL_STRING 0
    385 
    386 #endif  // GTEST_HAS_GLOBAL_STRING
    387 
    388 #ifndef GTEST_HAS_STD_WSTRING
    389 // The user didn't tell us whether ::std::wstring is available, so we need
    390 // to figure it out.
    391 // TODO(wan (at) google.com): uses autoconf to detect whether ::std::wstring
    392 //   is available.
    393 
    394 // Cygwin 1.7 and below doesn't support ::std::wstring.
    395 // Solaris' libc++ doesn't support it either.  Android has
    396 // no support for it at least as recent as Froyo (2.2).
    397 # define GTEST_HAS_STD_WSTRING \
    398     (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS))
    399 
    400 #endif  // GTEST_HAS_STD_WSTRING
    401 
    402 #ifndef GTEST_HAS_GLOBAL_WSTRING
    403 // The user didn't tell us whether ::wstring is available, so we need
    404 // to figure it out.
    405 # define GTEST_HAS_GLOBAL_WSTRING \
    406     (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
    407 #endif  // GTEST_HAS_GLOBAL_WSTRING
    408 
    409 // Determines whether RTTI is available.
    410 #ifndef GTEST_HAS_RTTI
    411 // The user didn't tell us whether RTTI is enabled, so we need to
    412 // figure it out.
    413 
    414 # ifdef _MSC_VER
    415 
    416 #  ifdef _CPPRTTI  // MSVC defines this macro iff RTTI is enabled.
    417 #   define GTEST_HAS_RTTI 1
    418 #  else
    419 #   define GTEST_HAS_RTTI 0
    420 #  endif
    421 
    422 // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
    423 # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
    424 
    425 #  ifdef __GXX_RTTI
    426 // When building against STLport with the Android NDK and with
    427 // -frtti -fno-exceptions, the build fails at link time with undefined
    428 // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
    429 // so disable RTTI when detected.
    430 #   if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
    431        !defined(__EXCEPTIONS)
    432 #    define GTEST_HAS_RTTI 0
    433 #   else
    434 #    define GTEST_HAS_RTTI 1
    435 #   endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
    436 #  else
    437 #   define GTEST_HAS_RTTI 0
    438 #  endif  // __GXX_RTTI
    439 
    440 // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
    441 // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
    442 // first version with C++ support.
    443 # elif defined(__clang__)
    444 
    445 #  define GTEST_HAS_RTTI __has_feature(cxx_rtti)
    446 
    447 // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
    448 // both the typeid and dynamic_cast features are present.
    449 # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
    450 
    451 #  ifdef __RTTI_ALL__
    452 #   define GTEST_HAS_RTTI 1
    453 #  else
    454 #   define GTEST_HAS_RTTI 0
    455 #  endif
    456 
    457 # else
    458 
    459 // For all other compilers, we assume RTTI is enabled.
    460 #  define GTEST_HAS_RTTI 1
    461 
    462 # endif  // _MSC_VER
    463 
    464 #endif  // GTEST_HAS_RTTI
    465 
    466 // It's this header's responsibility to #include <typeinfo> when RTTI
    467 // is enabled.
    468 #if GTEST_HAS_RTTI
    469 # include <typeinfo>
    470 #endif
    471 
    472 // Determines whether Google Test can use the pthreads library.
    473 #ifndef GTEST_HAS_PTHREAD
    474 // The user didn't tell us explicitly, so we assume pthreads support is
    475 // available on Linux and Mac.
    476 //
    477 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
    478 // to your compiler flags.
    479 # define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \
    480     || GTEST_OS_QNX)
    481 #endif  // GTEST_HAS_PTHREAD
    482 
    483 #if GTEST_HAS_PTHREAD
    484 // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
    485 // true.
    486 # include <pthread.h>  // NOLINT
    487 
    488 // For timespec and nanosleep, used below.
    489 # include <time.h>  // NOLINT
    490 #endif
    491 
    492 // Determines whether Google Test can use tr1/tuple.  You can define
    493 // this macro to 0 to prevent Google Test from using tuple (any
    494 // feature depending on tuple with be disabled in this mode).
    495 #ifndef GTEST_HAS_TR1_TUPLE
    496 # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR)
    497 // STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>.
    498 #  define GTEST_HAS_TR1_TUPLE 0
    499 # else
    500 // The user didn't tell us not to do it, so we assume it's OK.
    501 #  define GTEST_HAS_TR1_TUPLE 1
    502 # endif
    503 #endif  // GTEST_HAS_TR1_TUPLE
    504 
    505 // Determines whether Google Test's own tr1 tuple implementation
    506 // should be used.
    507 #ifndef GTEST_USE_OWN_TR1_TUPLE
    508 // The user didn't tell us, so we need to figure it out.
    509 
    510 // We use our own TR1 tuple if we aren't sure the user has an
    511 // implementation of it already.  At this time, libstdc++ 4.0.0+ and
    512 // MSVC 2010 are the only mainstream standard libraries that come
    513 // with a TR1 tuple implementation.  NVIDIA's CUDA NVCC compiler
    514 // pretends to be GCC by defining __GNUC__ and friends, but cannot
    515 // compile GCC's tuple implementation.  MSVC 2008 (9.0) provides TR1
    516 // tuple in a 323 MB Feature Pack download, which we cannot assume the
    517 // user has.  QNX's QCC compiler is a modified GCC but it doesn't
    518 // support TR1 tuple.  libc++ only provides std::tuple, in C++11 mode,
    519 // and it can be used with some compilers that define __GNUC__.
    520 # if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
    521       && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
    522 #  define GTEST_ENV_HAS_TR1_TUPLE_ 1
    523 # endif
    524 
    525 // C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
    526 // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
    527 // can build with clang but need to use gcc4.2's libstdc++).
    528 # if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
    529 #  define GTEST_ENV_HAS_STD_TUPLE_ 1
    530 # endif
    531 
    532 # if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
    533 #  define GTEST_USE_OWN_TR1_TUPLE 0
    534 # else
    535 #  define GTEST_USE_OWN_TR1_TUPLE 1
    536 # endif
    537 
    538 #endif  // GTEST_USE_OWN_TR1_TUPLE
    539 
    540 // To avoid conditional compilation everywhere, we make it
    541 // gtest-port.h's responsibility to #include the header implementing
    542 // tr1/tuple.
    543 #if GTEST_HAS_TR1_TUPLE
    544 
    545 # if GTEST_USE_OWN_TR1_TUPLE
    546 #  include "gtest/internal/gtest-tuple.h"
    547 # elif GTEST_ENV_HAS_STD_TUPLE_
    548 #  include <tuple>
    549 // C++11 puts its tuple into the ::std namespace rather than
    550 // ::std::tr1.  gtest expects tuple to live in ::std::tr1, so put it there.
    551 // This causes undefined behavior, but supported compilers react in
    552 // the way we intend.
    553 namespace std {
    554 namespace tr1 {
    555 using ::std::get;
    556 using ::std::make_tuple;
    557 using ::std::tuple;
    558 using ::std::tuple_element;
    559 using ::std::tuple_size;
    560 }
    561 }
    562 
    563 # elif GTEST_OS_SYMBIAN
    564 
    565 // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
    566 // use STLport's tuple implementation, which unfortunately doesn't
    567 // work as the copy of STLport distributed with Symbian is incomplete.
    568 // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
    569 // use its own tuple implementation.
    570 #  ifdef BOOST_HAS_TR1_TUPLE
    571 #   undef BOOST_HAS_TR1_TUPLE
    572 #  endif  // BOOST_HAS_TR1_TUPLE
    573 
    574 // This prevents <boost/tr1/detail/config.hpp>, which defines
    575 // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
    576 #  define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
    577 #  include <tuple>
    578 
    579 # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
    580 // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header.  This does
    581 // not conform to the TR1 spec, which requires the header to be <tuple>.
    582 
    583 #  if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
    584 // Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
    585 // which is #included by <tr1/tuple>, to not compile when RTTI is
    586 // disabled.  _TR1_FUNCTIONAL is the header guard for
    587 // <tr1/functional>.  Hence the following #define is a hack to prevent
    588 // <tr1/functional> from being included.
    589 #   define _TR1_FUNCTIONAL 1
    590 #   include <tr1/tuple>
    591 #   undef _TR1_FUNCTIONAL  // Allows the user to #include
    592                         // <tr1/functional> if he chooses to.
    593 #  else
    594 #   include <tr1/tuple>  // NOLINT
    595 #  endif  // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
    596 
    597 # else
    598 // If the compiler is not GCC 4.0+, we assume the user is using a
    599 // spec-conforming TR1 implementation.
    600 #  include <tuple>  // NOLINT
    601 # endif  // GTEST_USE_OWN_TR1_TUPLE
    602 
    603 #endif  // GTEST_HAS_TR1_TUPLE
    604 
    605 // Determines whether clone(2) is supported.
    606 // Usually it will only be available on Linux, excluding
    607 // Linux on the Itanium architecture.
    608 // Also see http://linux.die.net/man/2/clone.
    609 #ifndef GTEST_HAS_CLONE
    610 // The user didn't tell us, so we need to figure it out.
    611 
    612 # if GTEST_OS_LINUX && !defined(__ia64__)
    613 #  if GTEST_OS_LINUX_ANDROID
    614 // On Android, clone() became available at different API levels for each 32-bit
    615 // architecture.
    616 #    if defined(__LP64__) || \
    617         (defined(__arm__) && __ANDROID_API__ >= 9) || \
    618         (defined(__mips__) && __ANDROID_API__ >= 12) || \
    619         (defined(__i386__) && __ANDROID_API__ >= 17)
    620 #     define GTEST_HAS_CLONE 1
    621 #    else
    622 #     define GTEST_HAS_CLONE 0
    623 #    endif
    624 #  else
    625 #   define GTEST_HAS_CLONE 1
    626 #  endif
    627 # else
    628 #  define GTEST_HAS_CLONE 0
    629 # endif  // GTEST_OS_LINUX && !defined(__ia64__)
    630 
    631 #endif  // GTEST_HAS_CLONE
    632 
    633 // Determines whether to support stream redirection. This is used to test
    634 // output correctness and to implement death tests.
    635 #ifndef GTEST_HAS_STREAM_REDIRECTION
    636 // By default, we assume that stream redirection is supported on all
    637 // platforms except known mobile ones.
    638 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN
    639 #  define GTEST_HAS_STREAM_REDIRECTION 0
    640 # else
    641 #  define GTEST_HAS_STREAM_REDIRECTION 1
    642 # endif  // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
    643 #endif  // GTEST_HAS_STREAM_REDIRECTION
    644 
    645 // Determines whether to support death tests.
    646 // Google Test does not support death tests for VC 7.1 and earlier as
    647 // abort() in a VC 7.1 application compiled as GUI in debug config
    648 // pops up a dialog window that cannot be suppressed programmatically.
    649 #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
    650      (GTEST_OS_MAC && !GTEST_OS_IOS) || GTEST_OS_IOS_SIMULATOR || \
    651      (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
    652      GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
    653      GTEST_OS_OPENBSD || GTEST_OS_QNX)
    654 # define GTEST_HAS_DEATH_TEST 1
    655 # include <vector>  // NOLINT
    656 #endif
    657 
    658 // We don't support MSVC 7.1 with exceptions disabled now.  Therefore
    659 // all the compilers we care about are adequate for supporting
    660 // value-parameterized tests.
    661 #define GTEST_HAS_PARAM_TEST 1
    662 
    663 // Determines whether to support type-driven tests.
    664 
    665 // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
    666 // Sun Pro CC, IBM Visual Age, and HP aCC support.
    667 #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
    668     defined(__IBMCPP__) || defined(__HP_aCC)
    669 # define GTEST_HAS_TYPED_TEST 1
    670 # define GTEST_HAS_TYPED_TEST_P 1
    671 #endif
    672 
    673 // Determines whether to support Combine(). This only makes sense when
    674 // value-parameterized tests are enabled.  The implementation doesn't
    675 // work on Sun Studio since it doesn't understand templated conversion
    676 // operators.
    677 #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
    678 # define GTEST_HAS_COMBINE 1
    679 #endif
    680 
    681 // Determines whether the system compiler uses UTF-16 for encoding wide strings.
    682 #define GTEST_WIDE_STRING_USES_UTF16_ \
    683     (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
    684 
    685 // Determines whether test results can be streamed to a socket.
    686 #if GTEST_OS_LINUX
    687 # define GTEST_CAN_STREAM_RESULTS_ 1
    688 #endif
    689 
    690 // Defines some utility macros.
    691 
    692 // The GNU compiler emits a warning if nested "if" statements are followed by
    693 // an "else" statement and braces are not used to explicitly disambiguate the
    694 // "else" binding.  This leads to problems with code like:
    695 //
    696 //   if (gate)
    697 //     ASSERT_*(condition) << "Some message";
    698 //
    699 // The "switch (0) case 0:" idiom is used to suppress this.
    700 #ifdef __INTEL_COMPILER
    701 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
    702 #else
    703 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default:  // NOLINT
    704 #endif
    705 
    706 // Use this annotation at the end of a struct/class definition to
    707 // prevent the compiler from optimizing away instances that are never
    708 // used.  This is useful when all interesting logic happens inside the
    709 // c'tor and / or d'tor.  Example:
    710 //
    711 //   struct Foo {
    712 //     Foo() { ... }
    713 //   } GTEST_ATTRIBUTE_UNUSED_;
    714 //
    715 // Also use it after a variable or parameter declaration to tell the
    716 // compiler the variable/parameter does not have to be used.
    717 #if defined(__GNUC__) && !defined(COMPILER_ICC)
    718 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
    719 #else
    720 # define GTEST_ATTRIBUTE_UNUSED_
    721 #endif
    722 
    723 // A macro to disallow operator=
    724 // This should be used in the private: declarations for a class.
    725 #define GTEST_DISALLOW_ASSIGN_(type)\
    726   void operator=(type const &)
    727 
    728 // A macro to disallow copy constructor and operator=
    729 // This should be used in the private: declarations for a class.
    730 #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
    731   type(type const &);\
    732   GTEST_DISALLOW_ASSIGN_(type)
    733 
    734 // Tell the compiler to warn about unused return values for functions declared
    735 // with this macro.  The macro should be used on function declarations
    736 // following the argument list:
    737 //
    738 //   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
    739 #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
    740 # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
    741 #else
    742 # define GTEST_MUST_USE_RESULT_
    743 #endif  // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
    744 
    745 // Determine whether the compiler supports Microsoft's Structured Exception
    746 // Handling.  This is supported by several Windows compilers but generally
    747 // does not exist on any other system.
    748 #ifndef GTEST_HAS_SEH
    749 // The user didn't tell us, so we need to figure it out.
    750 
    751 # if defined(_MSC_VER) || defined(__BORLANDC__)
    752 // These two compilers are known to support SEH.
    753 #  define GTEST_HAS_SEH 1
    754 # else
    755 // Assume no SEH.
    756 #  define GTEST_HAS_SEH 0
    757 # endif
    758 
    759 #endif  // GTEST_HAS_SEH
    760 
    761 #ifdef _MSC_VER
    762 
    763 # if GTEST_LINKED_AS_SHARED_LIBRARY
    764 #  define GTEST_API_ __declspec(dllimport)
    765 # elif GTEST_CREATE_SHARED_LIBRARY
    766 #  define GTEST_API_ __declspec(dllexport)
    767 # endif
    768 
    769 #endif  // _MSC_VER
    770 
    771 #ifndef GTEST_API_
    772 # define GTEST_API_
    773 #endif
    774 
    775 #ifdef __GNUC__
    776 // Ask the compiler to never inline a given function.
    777 # define GTEST_NO_INLINE_ __attribute__((noinline))
    778 #else
    779 # define GTEST_NO_INLINE_
    780 #endif
    781 
    782 // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
    783 #if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
    784 # define GTEST_HAS_CXXABI_H_ 1
    785 #else
    786 # define GTEST_HAS_CXXABI_H_ 0
    787 #endif
    788 
    789 namespace testing {
    790 
    791 class Message;
    792 
    793 namespace internal {
    794 
    795 // A secret type that Google Test users don't know about.  It has no
    796 // definition on purpose.  Therefore it's impossible to create a
    797 // Secret object, which is what we want.
    798 class Secret;
    799 
    800 // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
    801 // expression is true. For example, you could use it to verify the
    802 // size of a static array:
    803 //
    804 //   GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES,
    805 //                         content_type_names_incorrect_size);
    806 //
    807 // or to make sure a struct is smaller than a certain size:
    808 //
    809 //   GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
    810 //
    811 // The second argument to the macro is the name of the variable. If
    812 // the expression is false, most compilers will issue a warning/error
    813 // containing the name of the variable.
    814 
    815 template <bool>
    816 struct CompileAssert {
    817 };
    818 
    819 #define GTEST_COMPILE_ASSERT_(expr, msg) \
    820   typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
    821       msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
    822 
    823 // Implementation details of GTEST_COMPILE_ASSERT_:
    824 //
    825 // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
    826 //   elements (and thus is invalid) when the expression is false.
    827 //
    828 // - The simpler definition
    829 //
    830 //    #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
    831 //
    832 //   does not work, as gcc supports variable-length arrays whose sizes
    833 //   are determined at run-time (this is gcc's extension and not part
    834 //   of the C++ standard).  As a result, gcc fails to reject the
    835 //   following code with the simple definition:
    836 //
    837 //     int foo;
    838 //     GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
    839 //                                      // not a compile-time constant.
    840 //
    841 // - By using the type CompileAssert<(bool(expr))>, we ensures that
    842 //   expr is a compile-time constant.  (Template arguments must be
    843 //   determined at compile-time.)
    844 //
    845 // - The outter parentheses in CompileAssert<(bool(expr))> are necessary
    846 //   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
    847 //
    848 //     CompileAssert<bool(expr)>
    849 //
    850 //   instead, these compilers will refuse to compile
    851 //
    852 //     GTEST_COMPILE_ASSERT_(5 > 0, some_message);
    853 //
    854 //   (They seem to think the ">" in "5 > 0" marks the end of the
    855 //   template argument list.)
    856 //
    857 // - The array size is (bool(expr) ? 1 : -1), instead of simply
    858 //
    859 //     ((expr) ? 1 : -1).
    860 //
    861 //   This is to avoid running into a bug in MS VC 7.1, which
    862 //   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
    863 
    864 // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
    865 //
    866 // This template is declared, but intentionally undefined.
    867 template <typename T1, typename T2>
    868 struct StaticAssertTypeEqHelper;
    869 
    870 template <typename T>
    871 struct StaticAssertTypeEqHelper<T, T> {};
    872 
    873 #if GTEST_HAS_GLOBAL_STRING
    874 typedef ::string string;
    875 #else
    876 typedef ::std::string string;
    877 #endif  // GTEST_HAS_GLOBAL_STRING
    878 
    879 #if GTEST_HAS_GLOBAL_WSTRING
    880 typedef ::wstring wstring;
    881 #elif GTEST_HAS_STD_WSTRING
    882 typedef ::std::wstring wstring;
    883 #endif  // GTEST_HAS_GLOBAL_WSTRING
    884 
    885 // A helper for suppressing warnings on constant condition.  It just
    886 // returns 'condition'.
    887 GTEST_API_ bool IsTrue(bool condition);
    888 
    889 // Defines scoped_ptr.
    890 
    891 // This implementation of scoped_ptr is PARTIAL - it only contains
    892 // enough stuff to satisfy Google Test's need.
    893 template <typename T>
    894 class scoped_ptr {
    895  public:
    896   typedef T element_type;
    897 
    898   explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
    899   ~scoped_ptr() { reset(); }
    900 
    901   T& operator*() const { return *ptr_; }
    902   T* operator->() const { return ptr_; }
    903   T* get() const { return ptr_; }
    904 
    905   T* release() {
    906     T* const ptr = ptr_;
    907     ptr_ = NULL;
    908     return ptr;
    909   }
    910 
    911   void reset(T* p = NULL) {
    912     if (p != ptr_) {
    913       if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
    914         delete ptr_;
    915       }
    916       ptr_ = p;
    917     }
    918   }
    919 
    920  private:
    921   T* ptr_;
    922 
    923   GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
    924 };
    925 
    926 // Defines RE.
    927 
    928 // A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
    929 // Regular Expression syntax.
    930 class GTEST_API_ RE {
    931  public:
    932   // A copy constructor is required by the Standard to initialize object
    933   // references from r-values.
    934   RE(const RE& other) { Init(other.pattern()); }
    935 
    936   // Constructs an RE from a string.
    937   RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
    938 
    939 #if GTEST_HAS_GLOBAL_STRING
    940 
    941   RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
    942 
    943 #endif  // GTEST_HAS_GLOBAL_STRING
    944 
    945   RE(const char* regex) { Init(regex); }  // NOLINT
    946   ~RE();
    947 
    948   // Returns the string representation of the regex.
    949   const char* pattern() const { return pattern_; }
    950 
    951   // FullMatch(str, re) returns true iff regular expression re matches
    952   // the entire str.
    953   // PartialMatch(str, re) returns true iff regular expression re
    954   // matches a substring of str (including str itself).
    955   //
    956   // TODO(wan (at) google.com): make FullMatch() and PartialMatch() work
    957   // when str contains NUL characters.
    958   static bool FullMatch(const ::std::string& str, const RE& re) {
    959     return FullMatch(str.c_str(), re);
    960   }
    961   static bool PartialMatch(const ::std::string& str, const RE& re) {
    962     return PartialMatch(str.c_str(), re);
    963   }
    964 
    965 #if GTEST_HAS_GLOBAL_STRING
    966 
    967   static bool FullMatch(const ::string& str, const RE& re) {
    968     return FullMatch(str.c_str(), re);
    969   }
    970   static bool PartialMatch(const ::string& str, const RE& re) {
    971     return PartialMatch(str.c_str(), re);
    972   }
    973 
    974 #endif  // GTEST_HAS_GLOBAL_STRING
    975 
    976   static bool FullMatch(const char* str, const RE& re);
    977   static bool PartialMatch(const char* str, const RE& re);
    978 
    979  private:
    980   void Init(const char* regex);
    981 
    982   // We use a const char* instead of an std::string, as Google Test used to be
    983   // used where std::string is not available.  TODO(wan (at) google.com): change to
    984   // std::string.
    985   const char* pattern_;
    986   bool is_valid_;
    987 
    988 #if GTEST_USES_POSIX_RE
    989 
    990   regex_t full_regex_;     // For FullMatch().
    991   regex_t partial_regex_;  // For PartialMatch().
    992 
    993 #else  // GTEST_USES_SIMPLE_RE
    994 
    995   const char* full_pattern_;  // For FullMatch();
    996 
    997 #endif
    998 
    999   GTEST_DISALLOW_ASSIGN_(RE);
   1000 };
   1001 
   1002 // Formats a source file path and a line number as they would appear
   1003 // in an error message from the compiler used to compile this code.
   1004 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
   1005 
   1006 // Formats a file location for compiler-independent XML output.
   1007 // Although this function is not platform dependent, we put it next to
   1008 // FormatFileLocation in order to contrast the two functions.
   1009 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
   1010                                                                int line);
   1011 
   1012 // Defines logging utilities:
   1013 //   GTEST_LOG_(severity) - logs messages at the specified severity level. The
   1014 //                          message itself is streamed into the macro.
   1015 //   LogToStderr()  - directs all log messages to stderr.
   1016 //   FlushInfoLog() - flushes informational log messages.
   1017 
   1018 enum GTestLogSeverity {
   1019   GTEST_INFO,
   1020   GTEST_WARNING,
   1021   GTEST_ERROR,
   1022   GTEST_FATAL
   1023 };
   1024 
   1025 // Formats log entry severity, provides a stream object for streaming the
   1026 // log message, and terminates the message with a newline when going out of
   1027 // scope.
   1028 class GTEST_API_ GTestLog {
   1029  public:
   1030   GTestLog(GTestLogSeverity severity, const char* file, int line);
   1031 
   1032   // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
   1033   ~GTestLog();
   1034 
   1035   ::std::ostream& GetStream() { return ::std::cerr; }
   1036 
   1037  private:
   1038   const GTestLogSeverity severity_;
   1039 
   1040   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
   1041 };
   1042 
   1043 #define GTEST_LOG_(severity) \
   1044     ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
   1045                                   __FILE__, __LINE__).GetStream()
   1046 
   1047 inline void LogToStderr() {}
   1048 inline void FlushInfoLog() { fflush(NULL); }
   1049 
   1050 // INTERNAL IMPLEMENTATION - DO NOT USE.
   1051 //
   1052 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
   1053 // is not satisfied.
   1054 //  Synopsys:
   1055 //    GTEST_CHECK_(boolean_condition);
   1056 //     or
   1057 //    GTEST_CHECK_(boolean_condition) << "Additional message";
   1058 //
   1059 //    This checks the condition and if the condition is not satisfied
   1060 //    it prints message about the condition violation, including the
   1061 //    condition itself, plus additional message streamed into it, if any,
   1062 //    and then it aborts the program. It aborts the program irrespective of
   1063 //    whether it is built in the debug mode or not.
   1064 #define GTEST_CHECK_(condition) \
   1065     GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
   1066     if (::testing::internal::IsTrue(condition)) \
   1067       ; \
   1068     else \
   1069       GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
   1070 
   1071 // An all-mode assert to verify that the given POSIX-style function
   1072 // call returns 0 (indicating success).  Known limitation: this
   1073 // doesn't expand to a balanced 'if' statement, so enclose the macro
   1074 // in {} if you need to use it as the only statement in an 'if'
   1075 // branch.
   1076 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
   1077   if (const int gtest_error = (posix_call)) \
   1078     GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
   1079                       << gtest_error
   1080 
   1081 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
   1082 //
   1083 // Use ImplicitCast_ as a safe version of static_cast for upcasting in
   1084 // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
   1085 // const Foo*).  When you use ImplicitCast_, the compiler checks that
   1086 // the cast is safe.  Such explicit ImplicitCast_s are necessary in
   1087 // surprisingly many situations where C++ demands an exact type match
   1088 // instead of an argument type convertable to a target type.
   1089 //
   1090 // The syntax for using ImplicitCast_ is the same as for static_cast:
   1091 //
   1092 //   ImplicitCast_<ToType>(expr)
   1093 //
   1094 // ImplicitCast_ would have been part of the C++ standard library,
   1095 // but the proposal was submitted too late.  It will probably make
   1096 // its way into the language in the future.
   1097 //
   1098 // This relatively ugly name is intentional. It prevents clashes with
   1099 // similar functions users may have (e.g., implicit_cast). The internal
   1100 // namespace alone is not enough because the function can be found by ADL.
   1101 template<typename To>
   1102 inline To ImplicitCast_(To x) { return x; }
   1103 
   1104 // When you upcast (that is, cast a pointer from type Foo to type
   1105 // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
   1106 // always succeed.  When you downcast (that is, cast a pointer from
   1107 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
   1108 // how do you know the pointer is really of type SubclassOfFoo?  It
   1109 // could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
   1110 // when you downcast, you should use this macro.  In debug mode, we
   1111 // use dynamic_cast<> to double-check the downcast is legal (we die
   1112 // if it's not).  In normal mode, we do the efficient static_cast<>
   1113 // instead.  Thus, it's important to test in debug mode to make sure
   1114 // the cast is legal!
   1115 //    This is the only place in the code we should use dynamic_cast<>.
   1116 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
   1117 // do RTTI (eg code like this:
   1118 //    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
   1119 //    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
   1120 // You should design the code some other way not to need this.
   1121 //
   1122 // This relatively ugly name is intentional. It prevents clashes with
   1123 // similar functions users may have (e.g., down_cast). The internal
   1124 // namespace alone is not enough because the function can be found by ADL.
   1125 template<typename To, typename From>  // use like this: DownCast_<T*>(foo);
   1126 inline To DownCast_(From* f) {  // so we only accept pointers
   1127   // Ensures that To is a sub-type of From *.  This test is here only
   1128   // for compile-time type checking, and has no overhead in an
   1129   // optimized build at run-time, as it will be optimized away
   1130   // completely.
   1131   if (false) {
   1132     const To to = NULL;
   1133     ::testing::internal::ImplicitCast_<From*>(to);
   1134   }
   1135 
   1136 #if GTEST_HAS_RTTI
   1137   // RTTI: debug mode only!
   1138   GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL);
   1139 #endif
   1140   return static_cast<To>(f);
   1141 }
   1142 
   1143 // Downcasts the pointer of type Base to Derived.
   1144 // Derived must be a subclass of Base. The parameter MUST
   1145 // point to a class of type Derived, not any subclass of it.
   1146 // When RTTI is available, the function performs a runtime
   1147 // check to enforce this.
   1148 template <class Derived, class Base>
   1149 Derived* CheckedDowncastToActualType(Base* base) {
   1150 #if GTEST_HAS_RTTI
   1151   GTEST_CHECK_(typeid(*base) == typeid(Derived));
   1152   return dynamic_cast<Derived*>(base);  // NOLINT
   1153 #else
   1154   return static_cast<Derived*>(base);  // Poor man's downcast.
   1155 #endif
   1156 }
   1157 
   1158 #if GTEST_HAS_STREAM_REDIRECTION
   1159 
   1160 // Defines the stderr capturer:
   1161 //   CaptureStdout     - starts capturing stdout.
   1162 //   GetCapturedStdout - stops capturing stdout and returns the captured string.
   1163 //   CaptureStderr     - starts capturing stderr.
   1164 //   GetCapturedStderr - stops capturing stderr and returns the captured string.
   1165 //
   1166 GTEST_API_ void CaptureStdout();
   1167 GTEST_API_ std::string GetCapturedStdout();
   1168 GTEST_API_ void CaptureStderr();
   1169 GTEST_API_ std::string GetCapturedStderr();
   1170 
   1171 #endif  // GTEST_HAS_STREAM_REDIRECTION
   1172 
   1173 
   1174 #if GTEST_HAS_DEATH_TEST
   1175 
   1176 const ::std::vector<testing::internal::string>& GetInjectableArgvs();
   1177 void SetInjectableArgvs(const ::std::vector<testing::internal::string>*
   1178                              new_argvs);
   1179 
   1180 // A copy of all command line arguments.  Set by InitGoogleTest().
   1181 extern ::std::vector<testing::internal::string> g_argvs;
   1182 
   1183 #endif  // GTEST_HAS_DEATH_TEST
   1184 
   1185 // Defines synchronization primitives.
   1186 
   1187 #if GTEST_HAS_PTHREAD
   1188 
   1189 // Sleeps for (roughly) n milli-seconds.  This function is only for
   1190 // testing Google Test's own constructs.  Don't use it in user tests,
   1191 // either directly or indirectly.
   1192 inline void SleepMilliseconds(int n) {
   1193   const timespec time = {
   1194     0,                  // 0 seconds.
   1195     n * 1000L * 1000L,  // And n ms.
   1196   };
   1197   nanosleep(&time, NULL);
   1198 }
   1199 
   1200 // Allows a controller thread to pause execution of newly created
   1201 // threads until notified.  Instances of this class must be created
   1202 // and destroyed in the controller thread.
   1203 //
   1204 // This class is only for testing Google Test's own constructs. Do not
   1205 // use it in user tests, either directly or indirectly.
   1206 class Notification {
   1207  public:
   1208   Notification() : notified_(false) {
   1209     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
   1210   }
   1211   ~Notification() {
   1212     pthread_mutex_destroy(&mutex_);
   1213   }
   1214 
   1215   // Notifies all threads created with this notification to start. Must
   1216   // be called from the controller thread.
   1217   void Notify() {
   1218     pthread_mutex_lock(&mutex_);
   1219     notified_ = true;
   1220     pthread_mutex_unlock(&mutex_);
   1221   }
   1222 
   1223   // Blocks until the controller thread notifies. Must be called from a test
   1224   // thread.
   1225   void WaitForNotification() {
   1226     for (;;) {
   1227       pthread_mutex_lock(&mutex_);
   1228       const bool notified = notified_;
   1229       pthread_mutex_unlock(&mutex_);
   1230       if (notified)
   1231         break;
   1232       SleepMilliseconds(10);
   1233     }
   1234   }
   1235 
   1236  private:
   1237   pthread_mutex_t mutex_;
   1238   bool notified_;
   1239 
   1240   GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
   1241 };
   1242 
   1243 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
   1244 // Consequently, it cannot select a correct instantiation of ThreadWithParam
   1245 // in order to call its Run(). Introducing ThreadWithParamBase as a
   1246 // non-templated base class for ThreadWithParam allows us to bypass this
   1247 // problem.
   1248 class ThreadWithParamBase {
   1249  public:
   1250   virtual ~ThreadWithParamBase() {}
   1251   virtual void Run() = 0;
   1252 };
   1253 
   1254 // pthread_create() accepts a pointer to a function type with the C linkage.
   1255 // According to the Standard (7.5/1), function types with different linkages
   1256 // are different even if they are otherwise identical.  Some compilers (for
   1257 // example, SunStudio) treat them as different types.  Since class methods
   1258 // cannot be defined with C-linkage we need to define a free C-function to
   1259 // pass into pthread_create().
   1260 extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
   1261   static_cast<ThreadWithParamBase*>(thread)->Run();
   1262   return NULL;
   1263 }
   1264 
   1265 // Helper class for testing Google Test's multi-threading constructs.
   1266 // To use it, write:
   1267 //
   1268 //   void ThreadFunc(int param) { /* Do things with param */ }
   1269 //   Notification thread_can_start;
   1270 //   ...
   1271 //   // The thread_can_start parameter is optional; you can supply NULL.
   1272 //   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
   1273 //   thread_can_start.Notify();
   1274 //
   1275 // These classes are only for testing Google Test's own constructs. Do
   1276 // not use them in user tests, either directly or indirectly.
   1277 template <typename T>
   1278 class ThreadWithParam : public ThreadWithParamBase {
   1279  public:
   1280   typedef void (*UserThreadFunc)(T);
   1281 
   1282   ThreadWithParam(
   1283       UserThreadFunc func, T param, Notification* thread_can_start)
   1284       : func_(func),
   1285         param_(param),
   1286         thread_can_start_(thread_can_start),
   1287         finished_(false) {
   1288     ThreadWithParamBase* const base = this;
   1289     // The thread can be created only after all fields except thread_
   1290     // have been initialized.
   1291     GTEST_CHECK_POSIX_SUCCESS_(
   1292         pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
   1293   }
   1294   ~ThreadWithParam() { Join(); }
   1295 
   1296   void Join() {
   1297     if (!finished_) {
   1298       GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
   1299       finished_ = true;
   1300     }
   1301   }
   1302 
   1303   virtual void Run() {
   1304     if (thread_can_start_ != NULL)
   1305       thread_can_start_->WaitForNotification();
   1306     func_(param_);
   1307   }
   1308 
   1309  private:
   1310   const UserThreadFunc func_;  // User-supplied thread function.
   1311   const T param_;  // User-supplied parameter to the thread function.
   1312   // When non-NULL, used to block execution until the controller thread
   1313   // notifies.
   1314   Notification* const thread_can_start_;
   1315   bool finished_;  // true iff we know that the thread function has finished.
   1316   pthread_t thread_;  // The native thread object.
   1317 
   1318   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
   1319 };
   1320 
   1321 // MutexBase and Mutex implement mutex on pthreads-based platforms. They
   1322 // are used in conjunction with class MutexLock:
   1323 //
   1324 //   Mutex mutex;
   1325 //   ...
   1326 //   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the end
   1327 //                            // of the current scope.
   1328 //
   1329 // MutexBase implements behavior for both statically and dynamically
   1330 // allocated mutexes.  Do not use MutexBase directly.  Instead, write
   1331 // the following to define a static mutex:
   1332 //
   1333 //   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
   1334 //
   1335 // You can forward declare a static mutex like this:
   1336 //
   1337 //   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
   1338 //
   1339 // To create a dynamic mutex, just define an object of type Mutex.
   1340 class MutexBase {
   1341  public:
   1342   // Acquires this mutex.
   1343   void Lock() {
   1344     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
   1345     owner_ = pthread_self();
   1346     has_owner_ = true;
   1347   }
   1348 
   1349   // Releases this mutex.
   1350   void Unlock() {
   1351     // Since the lock is being released the owner_ field should no longer be
   1352     // considered valid. We don't protect writing to has_owner_ here, as it's
   1353     // the caller's responsibility to ensure that the current thread holds the
   1354     // mutex when this is called.
   1355     has_owner_ = false;
   1356     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
   1357   }
   1358 
   1359   // Does nothing if the current thread holds the mutex. Otherwise, crashes
   1360   // with high probability.
   1361   void AssertHeld() const {
   1362     GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
   1363         << "The current thread is not holding the mutex @" << this;
   1364   }
   1365 
   1366   // A static mutex may be used before main() is entered.  It may even
   1367   // be used before the dynamic initialization stage.  Therefore we
   1368   // must be able to initialize a static mutex object at link time.
   1369   // This means MutexBase has to be a POD and its member variables
   1370   // have to be public.
   1371  public:
   1372   pthread_mutex_t mutex_;  // The underlying pthread mutex.
   1373   // has_owner_ indicates whether the owner_ field below contains a valid thread
   1374   // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
   1375   // accesses to the owner_ field should be protected by a check of this field.
   1376   // An alternative might be to memset() owner_ to all zeros, but there's no
   1377   // guarantee that a zero'd pthread_t is necessarily invalid or even different
   1378   // from pthread_self().
   1379   bool has_owner_;
   1380   pthread_t owner_;  // The thread holding the mutex.
   1381 };
   1382 
   1383 // Forward-declares a static mutex.
   1384 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
   1385     extern ::testing::internal::MutexBase mutex
   1386 
   1387 // Defines and statically (i.e. at link time) initializes a static mutex.
   1388 // The initialization list here does not explicitly initialize each field,
   1389 // instead relying on default initialization for the unspecified fields. In
   1390 // particular, the owner_ field (a pthread_t) is not explicitly initialized.
   1391 // This allows initialization to work whether pthread_t is a scalar or struct.
   1392 // The flag -Wmissing-field-initializers must not be specified for this to work.
   1393 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
   1394     ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false }
   1395 
   1396 // The Mutex class can only be used for mutexes created at runtime. It
   1397 // shares its API with MutexBase otherwise.
   1398 class Mutex : public MutexBase {
   1399  public:
   1400   Mutex() {
   1401     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
   1402     has_owner_ = false;
   1403   }
   1404   ~Mutex() {
   1405     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
   1406   }
   1407 
   1408  private:
   1409   GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
   1410 };
   1411 
   1412 // We cannot name this class MutexLock as the ctor declaration would
   1413 // conflict with a macro named MutexLock, which is defined on some
   1414 // platforms.  Hence the typedef trick below.
   1415 class GTestMutexLock {
   1416  public:
   1417   explicit GTestMutexLock(MutexBase* mutex)
   1418       : mutex_(mutex) { mutex_->Lock(); }
   1419 
   1420   ~GTestMutexLock() { mutex_->Unlock(); }
   1421 
   1422  private:
   1423   MutexBase* const mutex_;
   1424 
   1425   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
   1426 };
   1427 
   1428 typedef GTestMutexLock MutexLock;
   1429 
   1430 // Helpers for ThreadLocal.
   1431 
   1432 // pthread_key_create() requires DeleteThreadLocalValue() to have
   1433 // C-linkage.  Therefore it cannot be templatized to access
   1434 // ThreadLocal<T>.  Hence the need for class
   1435 // ThreadLocalValueHolderBase.
   1436 class ThreadLocalValueHolderBase {
   1437  public:
   1438   virtual ~ThreadLocalValueHolderBase() {}
   1439 };
   1440 
   1441 // Called by pthread to delete thread-local data stored by
   1442 // pthread_setspecific().
   1443 extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
   1444   delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
   1445 }
   1446 
   1447 // Implements thread-local storage on pthreads-based systems.
   1448 //
   1449 //   // Thread 1
   1450 //   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.
   1451 //
   1452 //   // Thread 2
   1453 //   tl.set(150);  // Changes the value for thread 2 only.
   1454 //   EXPECT_EQ(150, tl.get());
   1455 //
   1456 //   // Thread 1
   1457 //   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.
   1458 //   tl.set(200);
   1459 //   EXPECT_EQ(200, tl.get());
   1460 //
   1461 // The template type argument T must have a public copy constructor.
   1462 // In addition, the default ThreadLocal constructor requires T to have
   1463 // a public default constructor.
   1464 //
   1465 // An object managed for a thread by a ThreadLocal instance is deleted
   1466 // when the thread exits.  Or, if the ThreadLocal instance dies in
   1467 // that thread, when the ThreadLocal dies.  It's the user's
   1468 // responsibility to ensure that all other threads using a ThreadLocal
   1469 // have exited when it dies, or the per-thread objects for those
   1470 // threads will not be deleted.
   1471 //
   1472 // Google Test only uses global ThreadLocal objects.  That means they
   1473 // will die after main() has returned.  Therefore, no per-thread
   1474 // object managed by Google Test will be leaked as long as all threads
   1475 // using Google Test have exited when main() returns.
   1476 template <typename T>
   1477 class ThreadLocal {
   1478  public:
   1479   ThreadLocal() : key_(CreateKey()),
   1480                   default_() {}
   1481   explicit ThreadLocal(const T& value) : key_(CreateKey()),
   1482                                          default_(value) {}
   1483 
   1484   ~ThreadLocal() {
   1485     // Destroys the managed object for the current thread, if any.
   1486     DeleteThreadLocalValue(pthread_getspecific(key_));
   1487 
   1488     // Releases resources associated with the key.  This will *not*
   1489     // delete managed objects for other threads.
   1490     GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
   1491   }
   1492 
   1493   T* pointer() { return GetOrCreateValue(); }
   1494   const T* pointer() const { return GetOrCreateValue(); }
   1495   const T& get() const { return *pointer(); }
   1496   void set(const T& value) { *pointer() = value; }
   1497 
   1498  private:
   1499   // Holds a value of type T.
   1500   class ValueHolder : public ThreadLocalValueHolderBase {
   1501    public:
   1502     explicit ValueHolder(const T& value) : value_(value) {}
   1503 
   1504     T* pointer() { return &value_; }
   1505 
   1506    private:
   1507     T value_;
   1508     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
   1509   };
   1510 
   1511   static pthread_key_t CreateKey() {
   1512     pthread_key_t key;
   1513     // When a thread exits, DeleteThreadLocalValue() will be called on
   1514     // the object managed for that thread.
   1515     GTEST_CHECK_POSIX_SUCCESS_(
   1516         pthread_key_create(&key, &DeleteThreadLocalValue));
   1517     return key;
   1518   }
   1519 
   1520   T* GetOrCreateValue() const {
   1521     ThreadLocalValueHolderBase* const holder =
   1522         static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
   1523     if (holder != NULL) {
   1524       return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
   1525     }
   1526 
   1527     ValueHolder* const new_holder = new ValueHolder(default_);
   1528     ThreadLocalValueHolderBase* const holder_base = new_holder;
   1529     GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
   1530     return new_holder->pointer();
   1531   }
   1532 
   1533   // A key pthreads uses for looking up per-thread values.
   1534   const pthread_key_t key_;
   1535   const T default_;  // The default value for each thread.
   1536 
   1537   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
   1538 };
   1539 
   1540 # define GTEST_IS_THREADSAFE 1
   1541 
   1542 #else  // GTEST_HAS_PTHREAD
   1543 
   1544 // A dummy implementation of synchronization primitives (mutex, lock,
   1545 // and thread-local variable).  Necessary for compiling Google Test where
   1546 // mutex is not supported - using Google Test in multiple threads is not
   1547 // supported on such platforms.
   1548 
   1549 class Mutex {
   1550  public:
   1551   Mutex() {}
   1552   void Lock() {}
   1553   void Unlock() {}
   1554   void AssertHeld() const {}
   1555 };
   1556 
   1557 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
   1558   extern ::testing::internal::Mutex mutex
   1559 
   1560 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
   1561 
   1562 class GTestMutexLock {
   1563  public:
   1564   explicit GTestMutexLock(Mutex*) {}  // NOLINT
   1565 };
   1566 
   1567 typedef GTestMutexLock MutexLock;
   1568 
   1569 template <typename T>
   1570 class ThreadLocal {
   1571  public:
   1572   ThreadLocal() : value_() {}
   1573   explicit ThreadLocal(const T& value) : value_(value) {}
   1574   T* pointer() { return &value_; }
   1575   const T* pointer() const { return &value_; }
   1576   const T& get() const { return value_; }
   1577   void set(const T& value) { value_ = value; }
   1578  private:
   1579   T value_;
   1580 };
   1581 
   1582 // The above synchronization primitives have dummy implementations.
   1583 // Therefore Google Test is not thread-safe.
   1584 # define GTEST_IS_THREADSAFE 0
   1585 
   1586 #endif  // GTEST_HAS_PTHREAD
   1587 
   1588 // Returns the number of threads running in the process, or 0 to indicate that
   1589 // we cannot detect it.
   1590 GTEST_API_ size_t GetThreadCount();
   1591 
   1592 // Passing non-POD classes through ellipsis (...) crashes the ARM
   1593 // compiler and generates a warning in Sun Studio.  The Nokia Symbian
   1594 // and the IBM XL C/C++ compiler try to instantiate a copy constructor
   1595 // for objects passed through ellipsis (...), failing for uncopyable
   1596 // objects.  We define this to ensure that only POD is passed through
   1597 // ellipsis on these systems.
   1598 #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC)
   1599 // We lose support for NULL detection where the compiler doesn't like
   1600 // passing non-POD classes through ellipsis (...).
   1601 # define GTEST_ELLIPSIS_NEEDS_POD_ 1
   1602 #else
   1603 # define GTEST_CAN_COMPARE_NULL 1
   1604 #endif
   1605 
   1606 // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
   1607 // const T& and const T* in a function template.  These compilers
   1608 // _can_ decide between class template specializations for T and T*,
   1609 // so a tr1::type_traits-like is_pointer works.
   1610 #if defined(__SYMBIAN32__) || defined(__IBMCPP__)
   1611 # define GTEST_NEEDS_IS_POINTER_ 1
   1612 #endif
   1613 
   1614 template <bool bool_value>
   1615 struct bool_constant {
   1616   typedef bool_constant<bool_value> type;
   1617   static const bool value = bool_value;
   1618 };
   1619 template <bool bool_value> const bool bool_constant<bool_value>::value;
   1620 
   1621 typedef bool_constant<false> false_type;
   1622 typedef bool_constant<true> true_type;
   1623 
   1624 template <typename T>
   1625 struct is_pointer : public false_type {};
   1626 
   1627 template <typename T>
   1628 struct is_pointer<T*> : public true_type {};
   1629 
   1630 template <typename Iterator>
   1631 struct IteratorTraits {
   1632   typedef typename Iterator::value_type value_type;
   1633 };
   1634 
   1635 template <typename T>
   1636 struct IteratorTraits<T*> {
   1637   typedef T value_type;
   1638 };
   1639 
   1640 template <typename T>
   1641 struct IteratorTraits<const T*> {
   1642   typedef T value_type;
   1643 };
   1644 
   1645 #if GTEST_OS_WINDOWS
   1646 # define GTEST_PATH_SEP_ "\\"
   1647 # define GTEST_HAS_ALT_PATH_SEP_ 1
   1648 // The biggest signed integer type the compiler supports.
   1649 typedef __int64 BiggestInt;
   1650 #else
   1651 # define GTEST_PATH_SEP_ "/"
   1652 # define GTEST_HAS_ALT_PATH_SEP_ 0
   1653 typedef long long BiggestInt;  // NOLINT
   1654 #endif  // GTEST_OS_WINDOWS
   1655 
   1656 // Utilities for char.
   1657 
   1658 // isspace(int ch) and friends accept an unsigned char or EOF.  char
   1659 // may be signed, depending on the compiler (or compiler flags).
   1660 // Therefore we need to cast a char to unsigned char before calling
   1661 // isspace(), etc.
   1662 
   1663 inline bool IsAlpha(char ch) {
   1664   return isalpha(static_cast<unsigned char>(ch)) != 0;
   1665 }
   1666 inline bool IsAlNum(char ch) {
   1667   return isalnum(static_cast<unsigned char>(ch)) != 0;
   1668 }
   1669 inline bool IsDigit(char ch) {
   1670   return isdigit(static_cast<unsigned char>(ch)) != 0;
   1671 }
   1672 inline bool IsLower(char ch) {
   1673   return islower(static_cast<unsigned char>(ch)) != 0;
   1674 }
   1675 inline bool IsSpace(char ch) {
   1676   return isspace(static_cast<unsigned char>(ch)) != 0;
   1677 }
   1678 inline bool IsUpper(char ch) {
   1679   return isupper(static_cast<unsigned char>(ch)) != 0;
   1680 }
   1681 inline bool IsXDigit(char ch) {
   1682   return isxdigit(static_cast<unsigned char>(ch)) != 0;
   1683 }
   1684 inline bool IsXDigit(wchar_t ch) {
   1685   const unsigned char low_byte = static_cast<unsigned char>(ch);
   1686   return ch == low_byte && isxdigit(low_byte) != 0;
   1687 }
   1688 
   1689 inline char ToLower(char ch) {
   1690   return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
   1691 }
   1692 inline char ToUpper(char ch) {
   1693   return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
   1694 }
   1695 
   1696 // The testing::internal::posix namespace holds wrappers for common
   1697 // POSIX functions.  These wrappers hide the differences between
   1698 // Windows/MSVC and POSIX systems.  Since some compilers define these
   1699 // standard functions as macros, the wrapper cannot have the same name
   1700 // as the wrapped function.
   1701 
   1702 namespace posix {
   1703 
   1704 // Functions with a different name on Windows.
   1705 
   1706 #if GTEST_OS_WINDOWS
   1707 
   1708 typedef struct _stat StatStruct;
   1709 
   1710 # ifdef __BORLANDC__
   1711 inline int IsATTY(int fd) { return isatty(fd); }
   1712 inline int StrCaseCmp(const char* s1, const char* s2) {
   1713   return stricmp(s1, s2);
   1714 }
   1715 inline char* StrDup(const char* src) { return strdup(src); }
   1716 # else  // !__BORLANDC__
   1717 #  if GTEST_OS_WINDOWS_MOBILE
   1718 inline int IsATTY(int /* fd */) { return 0; }
   1719 #  else
   1720 inline int IsATTY(int fd) { return _isatty(fd); }
   1721 #  endif  // GTEST_OS_WINDOWS_MOBILE
   1722 inline int StrCaseCmp(const char* s1, const char* s2) {
   1723   return _stricmp(s1, s2);
   1724 }
   1725 inline char* StrDup(const char* src) { return _strdup(src); }
   1726 # endif  // __BORLANDC__
   1727 
   1728 # if GTEST_OS_WINDOWS_MOBILE
   1729 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
   1730 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
   1731 // time and thus not defined there.
   1732 # else
   1733 inline int FileNo(FILE* file) { return _fileno(file); }
   1734 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
   1735 inline int RmDir(const char* dir) { return _rmdir(dir); }
   1736 inline bool IsDir(const StatStruct& st) {
   1737   return (_S_IFDIR & st.st_mode) != 0;
   1738 }
   1739 # endif  // GTEST_OS_WINDOWS_MOBILE
   1740 
   1741 #else
   1742 
   1743 typedef struct stat StatStruct;
   1744 
   1745 inline int FileNo(FILE* file) { return fileno(file); }
   1746 inline int IsATTY(int fd) { return isatty(fd); }
   1747 inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
   1748 inline int StrCaseCmp(const char* s1, const char* s2) {
   1749   return strcasecmp(s1, s2);
   1750 }
   1751 inline char* StrDup(const char* src) { return strdup(src); }
   1752 inline int RmDir(const char* dir) { return rmdir(dir); }
   1753 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
   1754 
   1755 #endif  // GTEST_OS_WINDOWS
   1756 
   1757 // Functions deprecated by MSVC 8.0.
   1758 
   1759 #ifdef _MSC_VER
   1760 // Temporarily disable warning 4996 (deprecated function).
   1761 # pragma warning(push)
   1762 # pragma warning(disable:4996)
   1763 #endif
   1764 
   1765 inline const char* StrNCpy(char* dest, const char* src, size_t n) {
   1766   return strncpy(dest, src, n);
   1767 }
   1768 
   1769 // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
   1770 // StrError() aren't needed on Windows CE at this time and thus not
   1771 // defined there.
   1772 
   1773 #if !GTEST_OS_WINDOWS_MOBILE
   1774 inline int ChDir(const char* dir) { return chdir(dir); }
   1775 #endif
   1776 inline FILE* FOpen(const char* path, const char* mode) {
   1777   return fopen(path, mode);
   1778 }
   1779 #if !GTEST_OS_WINDOWS_MOBILE
   1780 inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
   1781   return freopen(path, mode, stream);
   1782 }
   1783 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
   1784 #endif
   1785 inline int FClose(FILE* fp) { return fclose(fp); }
   1786 #if !GTEST_OS_WINDOWS_MOBILE
   1787 inline int Read(int fd, void* buf, unsigned int count) {
   1788   return static_cast<int>(read(fd, buf, count));
   1789 }
   1790 inline int Write(int fd, const void* buf, unsigned int count) {
   1791   return static_cast<int>(write(fd, buf, count));
   1792 }
   1793 inline int Close(int fd) { return close(fd); }
   1794 inline const char* StrError(int errnum) { return strerror(errnum); }
   1795 #endif
   1796 inline const char* GetEnv(const char* name) {
   1797 #if GTEST_OS_WINDOWS_MOBILE
   1798   // We are on Windows CE, which has no environment variables.
   1799   return NULL;
   1800 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
   1801   // Environment variables which we programmatically clear will be set to the
   1802   // empty string rather than unset (NULL).  Handle that case.
   1803   const char* const env = getenv(name);
   1804   return (env != NULL && env[0] != '\0') ? env : NULL;
   1805 #else
   1806   return getenv(name);
   1807 #endif
   1808 }
   1809 
   1810 #ifdef _MSC_VER
   1811 # pragma warning(pop)  // Restores the warning state.
   1812 #endif
   1813 
   1814 #if GTEST_OS_WINDOWS_MOBILE
   1815 // Windows CE has no C library. The abort() function is used in
   1816 // several places in Google Test. This implementation provides a reasonable
   1817 // imitation of standard behaviour.
   1818 void Abort();
   1819 #elif defined(__ANDROID__) && defined(__mips__)
   1820 // Work-around broken abort() on Android/MIPS
   1821 inline void Abort() { fflush(NULL); exit(1); }
   1822 #else
   1823 inline void Abort() { abort(); }
   1824 #endif  // GTEST_OS_WINDOWS_MOBILE
   1825 
   1826 }  // namespace posix
   1827 
   1828 // MSVC "deprecates" snprintf and issues warnings wherever it is used.  In
   1829 // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
   1830 // MSVC-based platforms.  We map the GTEST_SNPRINTF_ macro to the appropriate
   1831 // function in order to achieve that.  We use macro definition here because
   1832 // snprintf is a variadic function.
   1833 #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
   1834 // MSVC 2005 and above support variadic macros.
   1835 # define GTEST_SNPRINTF_(buffer, size, format, ...) \
   1836      _snprintf_s(buffer, size, size, format, __VA_ARGS__)
   1837 #elif defined(_MSC_VER)
   1838 // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't
   1839 // complain about _snprintf.
   1840 # define GTEST_SNPRINTF_ _snprintf
   1841 #else
   1842 # define GTEST_SNPRINTF_ snprintf
   1843 #endif
   1844 
   1845 // The maximum number a BiggestInt can represent.  This definition
   1846 // works no matter BiggestInt is represented in one's complement or
   1847 // two's complement.
   1848 //
   1849 // We cannot rely on numeric_limits in STL, as __int64 and long long
   1850 // are not part of standard C++ and numeric_limits doesn't need to be
   1851 // defined for them.
   1852 const BiggestInt kMaxBiggestInt =
   1853     ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
   1854 
   1855 // This template class serves as a compile-time function from size to
   1856 // type.  It maps a size in bytes to a primitive type with that
   1857 // size. e.g.
   1858 //
   1859 //   TypeWithSize<4>::UInt
   1860 //
   1861 // is typedef-ed to be unsigned int (unsigned integer made up of 4
   1862 // bytes).
   1863 //
   1864 // Such functionality should belong to STL, but I cannot find it
   1865 // there.
   1866 //
   1867 // Google Test uses this class in the implementation of floating-point
   1868 // comparison.
   1869 //
   1870 // For now it only handles UInt (unsigned int) as that's all Google Test
   1871 // needs.  Other types can be easily added in the future if need
   1872 // arises.
   1873 template <size_t size>
   1874 class TypeWithSize {
   1875  public:
   1876   // This prevents the user from using TypeWithSize<N> with incorrect
   1877   // values of N.
   1878   typedef void UInt;
   1879 };
   1880 
   1881 // The specialization for size 4.
   1882 template <>
   1883 class TypeWithSize<4> {
   1884  public:
   1885   // unsigned int has size 4 in both gcc and MSVC.
   1886   //
   1887   // As base/basictypes.h doesn't compile on Windows, we cannot use
   1888   // uint32, uint64, and etc here.
   1889   typedef int Int;
   1890   typedef unsigned int UInt;
   1891 };
   1892 
   1893 // The specialization for size 8.
   1894 template <>
   1895 class TypeWithSize<8> {
   1896  public:
   1897 #if GTEST_OS_WINDOWS
   1898   typedef __int64 Int;
   1899   typedef unsigned __int64 UInt;
   1900 #else
   1901   typedef long long Int;  // NOLINT
   1902   typedef unsigned long long UInt;  // NOLINT
   1903 #endif  // GTEST_OS_WINDOWS
   1904 };
   1905 
   1906 // Integer types of known sizes.
   1907 typedef TypeWithSize<4>::Int Int32;
   1908 typedef TypeWithSize<4>::UInt UInt32;
   1909 typedef TypeWithSize<8>::Int Int64;
   1910 typedef TypeWithSize<8>::UInt UInt64;
   1911 typedef TypeWithSize<8>::Int TimeInMillis;  // Represents time in milliseconds.
   1912 
   1913 // Utilities for command line flags and environment variables.
   1914 
   1915 // Macro for referencing flags.
   1916 #define GTEST_FLAG(name) FLAGS_gtest_##name
   1917 
   1918 // Macros for declaring flags.
   1919 #define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
   1920 #define GTEST_DECLARE_int32_(name) \
   1921     GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
   1922 #define GTEST_DECLARE_string_(name) \
   1923     GTEST_API_ extern ::std::string GTEST_FLAG(name)
   1924 
   1925 // Macros for defining flags.
   1926 #define GTEST_DEFINE_bool_(name, default_val, doc) \
   1927     GTEST_API_ bool GTEST_FLAG(name) = (default_val)
   1928 #define GTEST_DEFINE_int32_(name, default_val, doc) \
   1929     GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
   1930 #define GTEST_DEFINE_string_(name, default_val, doc) \
   1931     GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
   1932 
   1933 // Thread annotations
   1934 #define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
   1935 #define GTEST_LOCK_EXCLUDED_(locks)
   1936 
   1937 // Parses 'str' for a 32-bit signed integer.  If successful, writes the result
   1938 // to *value and returns true; otherwise leaves *value unchanged and returns
   1939 // false.
   1940 // TODO(chandlerc): Find a better way to refactor flag and environment parsing
   1941 // out of both gtest-port.cc and gtest.cc to avoid exporting this utility
   1942 // function.
   1943 bool ParseInt32(const Message& src_text, const char* str, Int32* value);
   1944 
   1945 // Parses a bool/Int32/string from the environment variable
   1946 // corresponding to the given Google Test flag.
   1947 bool BoolFromGTestEnv(const char* flag, bool default_val);
   1948 GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
   1949 const char* StringFromGTestEnv(const char* flag, const char* default_val);
   1950 
   1951 }  // namespace internal
   1952 }  // namespace testing
   1953 
   1954 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
   1955