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