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