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