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