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