PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/include/gtest/internal/gtest-port.h

http://github.com/tomahawk-player/tomahawk
C++ Header | 1497 lines | 795 code | 183 blank | 519 comment | 58 complexity | a9c4168d117a18fab771f08826ca1026 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
  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. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  36. #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  37. // The user can define the following macros in the build script to
  38. // control Google Test's behavior. If the user doesn't define a macro
  39. // in this list, Google Test will define it.
  40. //
  41. // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2)
  42. // is/isn't available.
  43. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
  44. // are enabled.
  45. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string
  46. // is/isn't available (some systems define
  47. // ::string, which is different to std::string).
  48. // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
  49. // is/isn't available (some systems define
  50. // ::wstring, which is different to std::wstring).
  51. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
  52. // is/isn't available.
  53. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't
  54. // enabled.
  55. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
  56. // std::wstring does/doesn't work (Google Test can
  57. // be used where std::wstring is unavailable).
  58. // GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple
  59. // is/isn't available.
  60. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
  61. // compiler supports Microsoft's "Structured
  62. // Exception Handling".
  63. // GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google
  64. // Test's own tr1 tuple implementation should be
  65. // used. Unused when the user sets
  66. // GTEST_HAS_TR1_TUPLE to 0.
  67. // GTEST_LINKED_AS_SHARED_LIBRARY
  68. // - Define to 1 when compiling tests that use
  69. // Google Test as a shared library (known as
  70. // DLL on Windows).
  71. // GTEST_CREATE_SHARED_LIBRARY
  72. // - Define to 1 when compiling Google Test itself
  73. // as a shared library.
  74. // This header defines the following utilities:
  75. //
  76. // Macros indicating the current platform (defined to 1 if compiled on
  77. // the given platform; otherwise undefined):
  78. // GTEST_OS_AIX - IBM AIX
  79. // GTEST_OS_CYGWIN - Cygwin
  80. // GTEST_OS_LINUX - Linux
  81. // GTEST_OS_MAC - Mac OS X
  82. // GTEST_OS_SOLARIS - Sun Solaris
  83. // GTEST_OS_SYMBIAN - Symbian
  84. // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
  85. // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
  86. // GTEST_OS_WINDOWS_MINGW - MinGW
  87. // GTEST_OS_WINDOWS_MOBILE - Windows Mobile
  88. // GTEST_OS_ZOS - z/OS
  89. //
  90. // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
  91. // most stable support. Since core members of the Google Test project
  92. // don't have access to other platforms, support for them may be less
  93. // stable. If you notice any problems on your platform, please notify
  94. // googletestframework@googlegroups.com (patches for fixing them are
  95. // even more welcome!).
  96. //
  97. // Note that it is possible that none of the GTEST_OS_* macros are defined.
  98. //
  99. // Macros indicating available Google Test features (defined to 1 if
  100. // the corresponding feature is supported; otherwise undefined):
  101. // GTEST_HAS_COMBINE - the Combine() function (for value-parameterized
  102. // tests)
  103. // GTEST_HAS_DEATH_TEST - death tests
  104. // GTEST_HAS_PARAM_TEST - value-parameterized tests
  105. // GTEST_HAS_TYPED_TEST - typed tests
  106. // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
  107. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used.
  108. // GTEST_USES_SIMPLE_RE - our own simple regex is used;
  109. // the above two are mutually exclusive.
  110. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
  111. //
  112. // Macros for basic C++ coding:
  113. // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
  114. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
  115. // variable don't have to be used.
  116. // GTEST_DISALLOW_ASSIGN_ - disables operator=.
  117. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
  118. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
  119. //
  120. // Synchronization:
  121. // Mutex, MutexLock, ThreadLocal, GetThreadCount()
  122. // - synchronization primitives.
  123. // GTEST_IS_THREADSAFE - defined to 1 to indicate that the above
  124. // synchronization primitives have real implementations
  125. // and Google Test is thread-safe; or 0 otherwise.
  126. //
  127. // Template meta programming:
  128. // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only.
  129. //
  130. // Smart pointers:
  131. // scoped_ptr - as in TR2.
  132. //
  133. // Regular expressions:
  134. // RE - a simple regular expression class using the POSIX
  135. // Extended Regular Expression syntax. Not available on
  136. // Windows.
  137. //
  138. // Logging:
  139. // GTEST_LOG_() - logs messages at the specified severity level.
  140. // LogToStderr() - directs all log messages to stderr.
  141. // FlushInfoLog() - flushes informational log messages.
  142. //
  143. // Stdout and stderr capturing:
  144. // CaptureStdout() - starts capturing stdout.
  145. // GetCapturedStdout() - stops capturing stdout and returns the captured
  146. // string.
  147. // CaptureStderr() - starts capturing stderr.
  148. // GetCapturedStderr() - stops capturing stderr and returns the captured
  149. // string.
  150. //
  151. // Integer types:
  152. // TypeWithSize - maps an integer to a int type.
  153. // Int32, UInt32, Int64, UInt64, TimeInMillis
  154. // - integers of known sizes.
  155. // BiggestInt - the biggest signed integer type.
  156. //
  157. // Command-line utilities:
  158. // GTEST_FLAG() - references a flag.
  159. // GTEST_DECLARE_*() - declares a flag.
  160. // GTEST_DEFINE_*() - defines a flag.
  161. // GetArgvs() - returns the command line as a vector of strings.
  162. //
  163. // Environment variable utilities:
  164. // GetEnv() - gets the value of an environment variable.
  165. // BoolFromGTestEnv() - parses a bool environment variable.
  166. // Int32FromGTestEnv() - parses an Int32 environment variable.
  167. // StringFromGTestEnv() - parses a string environment variable.
  168. #include <stddef.h> // For ptrdiff_t
  169. #include <stdlib.h>
  170. #include <stdio.h>
  171. #include <string.h>
  172. #ifndef _WIN32_WCE
  173. #include <sys/stat.h>
  174. #endif // !_WIN32_WCE
  175. #include <iostream> // NOLINT
  176. #include <sstream> // NOLINT
  177. #include <string> // NOLINT
  178. #define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
  179. #define GTEST_FLAG_PREFIX_ "gtest_"
  180. #define GTEST_FLAG_PREFIX_DASH_ "gtest-"
  181. #define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
  182. #define GTEST_NAME_ "Google Test"
  183. #define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/"
  184. // Determines the version of gcc that is used to compile this.
  185. #ifdef __GNUC__
  186. // 40302 means version 4.3.2.
  187. #define GTEST_GCC_VER_ \
  188. (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
  189. #endif // __GNUC__
  190. // Determines the platform on which Google Test is compiled.
  191. #ifdef __CYGWIN__
  192. #define GTEST_OS_CYGWIN 1
  193. #elif defined __SYMBIAN32__
  194. #define GTEST_OS_SYMBIAN 1
  195. #elif defined _WIN32
  196. #define GTEST_OS_WINDOWS 1
  197. #ifdef _WIN32_WCE
  198. #define GTEST_OS_WINDOWS_MOBILE 1
  199. #elif defined(__MINGW__) || defined(__MINGW32__)
  200. #define GTEST_OS_WINDOWS_MINGW 1
  201. #else
  202. #define GTEST_OS_WINDOWS_DESKTOP 1
  203. #endif // _WIN32_WCE
  204. #elif defined __APPLE__
  205. #define GTEST_OS_MAC 1
  206. #elif defined __linux__
  207. #define GTEST_OS_LINUX 1
  208. #elif defined __MVS__
  209. #define GTEST_OS_ZOS 1
  210. #elif defined(__sun) && defined(__SVR4)
  211. #define GTEST_OS_SOLARIS 1
  212. #elif defined(_AIX)
  213. #define GTEST_OS_AIX 1
  214. #endif // __CYGWIN__
  215. #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_SYMBIAN || \
  216. GTEST_OS_SOLARIS || GTEST_OS_AIX
  217. // On some platforms, <regex.h> needs someone to define size_t, and
  218. // won't compile otherwise. We can #include it here as we already
  219. // included <stdlib.h>, which is guaranteed to define size_t through
  220. // <stddef.h>.
  221. #include <regex.h> // NOLINT
  222. #include <strings.h> // NOLINT
  223. #include <sys/types.h> // NOLINT
  224. #include <time.h> // NOLINT
  225. #include <unistd.h> // NOLINT
  226. #define GTEST_USES_POSIX_RE 1
  227. #elif GTEST_OS_WINDOWS
  228. #if !GTEST_OS_WINDOWS_MOBILE
  229. #include <direct.h> // NOLINT
  230. #include <io.h> // NOLINT
  231. #endif
  232. // <regex.h> is not available on Windows. Use our own simple regex
  233. // implementation instead.
  234. #define GTEST_USES_SIMPLE_RE 1
  235. #else
  236. // <regex.h> may not be available on this platform. Use our own
  237. // simple regex implementation instead.
  238. #define GTEST_USES_SIMPLE_RE 1
  239. #endif // GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC ||
  240. // GTEST_OS_SYMBIAN || GTEST_OS_SOLARIS || GTEST_OS_AIX
  241. #ifndef GTEST_HAS_EXCEPTIONS
  242. // The user didn't tell us whether exceptions are enabled, so we need
  243. // to figure it out.
  244. #if defined(_MSC_VER) || defined(__BORLANDC__)
  245. // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
  246. // macro to enable exceptions, so we'll do the same.
  247. // Assumes that exceptions are enabled by default.
  248. #ifndef _HAS_EXCEPTIONS
  249. #define _HAS_EXCEPTIONS 1
  250. #endif // _HAS_EXCEPTIONS
  251. #define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
  252. #elif defined(__GNUC__) && __EXCEPTIONS
  253. // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
  254. #define GTEST_HAS_EXCEPTIONS 1
  255. #elif defined(__SUNPRO_CC)
  256. // Sun Pro CC supports exceptions. However, there is no compile-time way of
  257. // detecting whether they are enabled or not. Therefore, we assume that
  258. // they are enabled unless the user tells us otherwise.
  259. #define GTEST_HAS_EXCEPTIONS 1
  260. #elif defined(__IBMCPP__) && __EXCEPTIONS
  261. // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
  262. #define GTEST_HAS_EXCEPTIONS 1
  263. #else
  264. // For other compilers, we assume exceptions are disabled to be
  265. // conservative.
  266. #define GTEST_HAS_EXCEPTIONS 0
  267. #endif // defined(_MSC_VER) || defined(__BORLANDC__)
  268. #endif // GTEST_HAS_EXCEPTIONS
  269. #if !defined(GTEST_HAS_STD_STRING)
  270. // Even though we don't use this macro any longer, we keep it in case
  271. // some clients still depend on it.
  272. #define GTEST_HAS_STD_STRING 1
  273. #elif !GTEST_HAS_STD_STRING
  274. // The user told us that ::std::string isn't available.
  275. #error "Google Test cannot be used where ::std::string isn't available."
  276. #endif // !defined(GTEST_HAS_STD_STRING)
  277. #ifndef GTEST_HAS_GLOBAL_STRING
  278. // The user didn't tell us whether ::string is available, so we need
  279. // to figure it out.
  280. #define GTEST_HAS_GLOBAL_STRING 0
  281. #endif // GTEST_HAS_GLOBAL_STRING
  282. #ifndef GTEST_HAS_STD_WSTRING
  283. // The user didn't tell us whether ::std::wstring is available, so we need
  284. // to figure it out.
  285. // TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
  286. // is available.
  287. // Cygwin 1.5 and below doesn't support ::std::wstring.
  288. // Cygwin 1.7 might add wstring support; this should be updated when clear.
  289. // Solaris' libc++ doesn't support it either.
  290. #define GTEST_HAS_STD_WSTRING (!(GTEST_OS_CYGWIN || GTEST_OS_SOLARIS))
  291. #endif // GTEST_HAS_STD_WSTRING
  292. #ifndef GTEST_HAS_GLOBAL_WSTRING
  293. // The user didn't tell us whether ::wstring is available, so we need
  294. // to figure it out.
  295. #define GTEST_HAS_GLOBAL_WSTRING \
  296. (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
  297. #endif // GTEST_HAS_GLOBAL_WSTRING
  298. // Determines whether RTTI is available.
  299. #ifndef GTEST_HAS_RTTI
  300. // The user didn't tell us whether RTTI is enabled, so we need to
  301. // figure it out.
  302. #ifdef _MSC_VER
  303. #ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled.
  304. #define GTEST_HAS_RTTI 1
  305. #else
  306. #define GTEST_HAS_RTTI 0
  307. #endif
  308. // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
  309. #elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
  310. #ifdef __GXX_RTTI
  311. #define GTEST_HAS_RTTI 1
  312. #else
  313. #define GTEST_HAS_RTTI 0
  314. #endif // __GXX_RTTI
  315. // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
  316. // both the typeid and dynamic_cast features are present.
  317. #elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
  318. #ifdef __RTTI_ALL__
  319. #define GTEST_HAS_RTTI 1
  320. #else
  321. #define GTEST_HAS_RTTI 0
  322. #endif
  323. #else
  324. // For all other compilers, we assume RTTI is enabled.
  325. #define GTEST_HAS_RTTI 1
  326. #endif // _MSC_VER
  327. #endif // GTEST_HAS_RTTI
  328. // It's this header's responsibility to #include <typeinfo> when RTTI
  329. // is enabled.
  330. #if GTEST_HAS_RTTI
  331. #include <typeinfo>
  332. #endif
  333. // Determines whether Google Test can use the pthreads library.
  334. #ifndef GTEST_HAS_PTHREAD
  335. // The user didn't tell us explicitly, so we assume pthreads support is
  336. // available on Linux and Mac.
  337. //
  338. // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
  339. // to your compiler flags.
  340. #define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC)
  341. #endif // GTEST_HAS_PTHREAD
  342. // Determines whether Google Test can use tr1/tuple. You can define
  343. // this macro to 0 to prevent Google Test from using tuple (any
  344. // feature depending on tuple with be disabled in this mode).
  345. #ifndef GTEST_HAS_TR1_TUPLE
  346. // The user didn't tell us not to do it, so we assume it's OK.
  347. #define GTEST_HAS_TR1_TUPLE 1
  348. #endif // GTEST_HAS_TR1_TUPLE
  349. // Determines whether Google Test's own tr1 tuple implementation
  350. // should be used.
  351. #ifndef GTEST_USE_OWN_TR1_TUPLE
  352. // The user didn't tell us, so we need to figure it out.
  353. // We use our own TR1 tuple if we aren't sure the user has an
  354. // implementation of it already. At this time, GCC 4.0.0+ and MSVC
  355. // 2010 are the only mainstream compilers that come with a TR1 tuple
  356. // implementation. NVIDIA's CUDA NVCC compiler pretends to be GCC by
  357. // defining __GNUC__ and friends, but cannot compile GCC's tuple
  358. // implementation. MSVC 2008 (9.0) provides TR1 tuple in a 323 MB
  359. // Feature Pack download, which we cannot assume the user has.
  360. #if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000)) \
  361. || _MSC_VER >= 1600
  362. #define GTEST_USE_OWN_TR1_TUPLE 0
  363. #else
  364. #define GTEST_USE_OWN_TR1_TUPLE 1
  365. #endif
  366. #endif // GTEST_USE_OWN_TR1_TUPLE
  367. // To avoid conditional compilation everywhere, we make it
  368. // gtest-port.h's responsibility to #include the header implementing
  369. // tr1/tuple.
  370. #if GTEST_HAS_TR1_TUPLE
  371. #if GTEST_USE_OWN_TR1_TUPLE
  372. #include <gtest/internal/gtest-tuple.h>
  373. #elif GTEST_OS_SYMBIAN
  374. // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
  375. // use STLport's tuple implementation, which unfortunately doesn't
  376. // work as the copy of STLport distributed with Symbian is incomplete.
  377. // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
  378. // use its own tuple implementation.
  379. #ifdef BOOST_HAS_TR1_TUPLE
  380. #undef BOOST_HAS_TR1_TUPLE
  381. #endif // BOOST_HAS_TR1_TUPLE
  382. // This prevents <boost/tr1/detail/config.hpp>, which defines
  383. // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
  384. #define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
  385. #include <tuple>
  386. #elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
  387. // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header. This does
  388. // not conform to the TR1 spec, which requires the header to be <tuple>.
  389. #if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
  390. // Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
  391. // which is #included by <tr1/tuple>, to not compile when RTTI is
  392. // disabled. _TR1_FUNCTIONAL is the header guard for
  393. // <tr1/functional>. Hence the following #define is a hack to prevent
  394. // <tr1/functional> from being included.
  395. #define _TR1_FUNCTIONAL 1
  396. #include <tr1/tuple>
  397. #undef _TR1_FUNCTIONAL // Allows the user to #include
  398. // <tr1/functional> if he chooses to.
  399. #else
  400. #include <tr1/tuple> // NOLINT
  401. #endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
  402. #else
  403. // If the compiler is not GCC 4.0+, we assume the user is using a
  404. // spec-conforming TR1 implementation.
  405. #include <tuple> // NOLINT
  406. #endif // GTEST_USE_OWN_TR1_TUPLE
  407. #endif // GTEST_HAS_TR1_TUPLE
  408. // Determines whether clone(2) is supported.
  409. // Usually it will only be available on Linux, excluding
  410. // Linux on the Itanium architecture.
  411. // Also see http://linux.die.net/man/2/clone.
  412. #ifndef GTEST_HAS_CLONE
  413. // The user didn't tell us, so we need to figure it out.
  414. #if GTEST_OS_LINUX && !defined(__ia64__)
  415. #define GTEST_HAS_CLONE 1
  416. #else
  417. #define GTEST_HAS_CLONE 0
  418. #endif // GTEST_OS_LINUX && !defined(__ia64__)
  419. #endif // GTEST_HAS_CLONE
  420. // Determines whether to support stream redirection. This is used to test
  421. // output correctness and to implement death tests.
  422. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
  423. #define GTEST_HAS_STREAM_REDIRECTION_ 1
  424. #endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
  425. // Determines whether to support death tests.
  426. // Google Test does not support death tests for VC 7.1 and earlier as
  427. // abort() in a VC 7.1 application compiled as GUI in debug config
  428. // pops up a dialog window that cannot be suppressed programmatically.
  429. #if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
  430. (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
  431. GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX)
  432. #define GTEST_HAS_DEATH_TEST 1
  433. #include <vector> // NOLINT
  434. #endif
  435. // We don't support MSVC 7.1 with exceptions disabled now. Therefore
  436. // all the compilers we care about are adequate for supporting
  437. // value-parameterized tests.
  438. #define GTEST_HAS_PARAM_TEST 1
  439. // Determines whether to support type-driven tests.
  440. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
  441. // Sun Pro CC, and IBM Visual Age support.
  442. #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
  443. defined(__IBMCPP__)
  444. #define GTEST_HAS_TYPED_TEST 1
  445. #define GTEST_HAS_TYPED_TEST_P 1
  446. #endif
  447. // Determines whether to support Combine(). This only makes sense when
  448. // value-parameterized tests are enabled. The implementation doesn't
  449. // work on Sun Studio since it doesn't understand templated conversion
  450. // operators.
  451. #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
  452. #define GTEST_HAS_COMBINE 1
  453. #endif
  454. // Determines whether the system compiler uses UTF-16 for encoding wide strings.
  455. #define GTEST_WIDE_STRING_USES_UTF16_ \
  456. (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
  457. // Defines some utility macros.
  458. // The GNU compiler emits a warning if nested "if" statements are followed by
  459. // an "else" statement and braces are not used to explicitly disambiguate the
  460. // "else" binding. This leads to problems with code like:
  461. //
  462. // if (gate)
  463. // ASSERT_*(condition) << "Some message";
  464. //
  465. // The "switch (0) case 0:" idiom is used to suppress this.
  466. #ifdef __INTEL_COMPILER
  467. #define GTEST_AMBIGUOUS_ELSE_BLOCKER_
  468. #else
  469. #define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: // NOLINT
  470. #endif
  471. // Use this annotation at the end of a struct/class definition to
  472. // prevent the compiler from optimizing away instances that are never
  473. // used. This is useful when all interesting logic happens inside the
  474. // c'tor and / or d'tor. Example:
  475. //
  476. // struct Foo {
  477. // Foo() { ... }
  478. // } GTEST_ATTRIBUTE_UNUSED_;
  479. //
  480. // Also use it after a variable or parameter declaration to tell the
  481. // compiler the variable/parameter does not have to be used.
  482. #if defined(__GNUC__) && !defined(COMPILER_ICC)
  483. #define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
  484. #else
  485. #define GTEST_ATTRIBUTE_UNUSED_
  486. #endif
  487. // A macro to disallow operator=
  488. // This should be used in the private: declarations for a class.
  489. #define GTEST_DISALLOW_ASSIGN_(type)\
  490. void operator=(type const &)
  491. // A macro to disallow copy constructor and operator=
  492. // This should be used in the private: declarations for a class.
  493. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
  494. type(type const &);\
  495. GTEST_DISALLOW_ASSIGN_(type)
  496. // Tell the compiler to warn about unused return values for functions declared
  497. // with this macro. The macro should be used on function declarations
  498. // following the argument list:
  499. //
  500. // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
  501. #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
  502. #define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
  503. #else
  504. #define GTEST_MUST_USE_RESULT_
  505. #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
  506. // Determine whether the compiler supports Microsoft's Structured Exception
  507. // Handling. This is supported by several Windows compilers but generally
  508. // does not exist on any other system.
  509. #ifndef GTEST_HAS_SEH
  510. // The user didn't tell us, so we need to figure it out.
  511. #if defined(_MSC_VER) || defined(__BORLANDC__)
  512. // These two compilers are known to support SEH.
  513. #define GTEST_HAS_SEH 1
  514. #else
  515. // Assume no SEH.
  516. #define GTEST_HAS_SEH 0
  517. #endif
  518. #endif // GTEST_HAS_SEH
  519. #ifdef _MSC_VER
  520. #if GTEST_LINKED_AS_SHARED_LIBRARY
  521. #define GTEST_API_ __declspec(dllimport)
  522. #elif GTEST_CREATE_SHARED_LIBRARY
  523. #define GTEST_API_ __declspec(dllexport)
  524. #endif
  525. #endif // _MSC_VER
  526. #ifndef GTEST_API_
  527. #define GTEST_API_
  528. #endif
  529. namespace testing {
  530. class Message;
  531. namespace internal {
  532. class String;
  533. typedef ::std::stringstream StrStream;
  534. // A helper for suppressing warnings on constant condition. It just
  535. // returns 'condition'.
  536. GTEST_API_ bool IsTrue(bool condition);
  537. // Defines scoped_ptr.
  538. // This implementation of scoped_ptr is PARTIAL - it only contains
  539. // enough stuff to satisfy Google Test's need.
  540. template <typename T>
  541. class scoped_ptr {
  542. public:
  543. typedef T element_type;
  544. explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
  545. ~scoped_ptr() { reset(); }
  546. T& operator*() const { return *ptr_; }
  547. T* operator->() const { return ptr_; }
  548. T* get() const { return ptr_; }
  549. T* release() {
  550. T* const ptr = ptr_;
  551. ptr_ = NULL;
  552. return ptr;
  553. }
  554. void reset(T* p = NULL) {
  555. if (p != ptr_) {
  556. if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type.
  557. delete ptr_;
  558. }
  559. ptr_ = p;
  560. }
  561. }
  562. private:
  563. T* ptr_;
  564. GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
  565. };
  566. // Defines RE.
  567. // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
  568. // Regular Expression syntax.
  569. class GTEST_API_ RE {
  570. public:
  571. // A copy constructor is required by the Standard to initialize object
  572. // references from r-values.
  573. RE(const RE& other) { Init(other.pattern()); }
  574. // Constructs an RE from a string.
  575. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
  576. #if GTEST_HAS_GLOBAL_STRING
  577. RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT
  578. #endif // GTEST_HAS_GLOBAL_STRING
  579. RE(const char* regex) { Init(regex); } // NOLINT
  580. ~RE();
  581. // Returns the string representation of the regex.
  582. const char* pattern() const { return pattern_; }
  583. // FullMatch(str, re) returns true iff regular expression re matches
  584. // the entire str.
  585. // PartialMatch(str, re) returns true iff regular expression re
  586. // matches a substring of str (including str itself).
  587. //
  588. // TODO(wan@google.com): make FullMatch() and PartialMatch() work
  589. // when str contains NUL characters.
  590. static bool FullMatch(const ::std::string& str, const RE& re) {
  591. return FullMatch(str.c_str(), re);
  592. }
  593. static bool PartialMatch(const ::std::string& str, const RE& re) {
  594. return PartialMatch(str.c_str(), re);
  595. }
  596. #if GTEST_HAS_GLOBAL_STRING
  597. static bool FullMatch(const ::string& str, const RE& re) {
  598. return FullMatch(str.c_str(), re);
  599. }
  600. static bool PartialMatch(const ::string& str, const RE& re) {
  601. return PartialMatch(str.c_str(), re);
  602. }
  603. #endif // GTEST_HAS_GLOBAL_STRING
  604. static bool FullMatch(const char* str, const RE& re);
  605. static bool PartialMatch(const char* str, const RE& re);
  606. private:
  607. void Init(const char* regex);
  608. // We use a const char* instead of a string, as Google Test may be used
  609. // where string is not available. We also do not use Google Test's own
  610. // String type here, in order to simplify dependencies between the
  611. // files.
  612. const char* pattern_;
  613. bool is_valid_;
  614. #if GTEST_USES_POSIX_RE
  615. regex_t full_regex_; // For FullMatch().
  616. regex_t partial_regex_; // For PartialMatch().
  617. #else // GTEST_USES_SIMPLE_RE
  618. const char* full_pattern_; // For FullMatch();
  619. #endif
  620. GTEST_DISALLOW_ASSIGN_(RE);
  621. };
  622. // Defines logging utilities:
  623. // GTEST_LOG_(severity) - logs messages at the specified severity level. The
  624. // message itself is streamed into the macro.
  625. // LogToStderr() - directs all log messages to stderr.
  626. // FlushInfoLog() - flushes informational log messages.
  627. enum GTestLogSeverity {
  628. GTEST_INFO,
  629. GTEST_WARNING,
  630. GTEST_ERROR,
  631. GTEST_FATAL
  632. };
  633. // Formats log entry severity, provides a stream object for streaming the
  634. // log message, and terminates the message with a newline when going out of
  635. // scope.
  636. class GTEST_API_ GTestLog {
  637. public:
  638. GTestLog(GTestLogSeverity severity, const char* file, int line);
  639. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  640. ~GTestLog();
  641. ::std::ostream& GetStream() { return ::std::cerr; }
  642. private:
  643. const GTestLogSeverity severity_;
  644. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
  645. };
  646. #define GTEST_LOG_(severity) \
  647. ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
  648. __FILE__, __LINE__).GetStream()
  649. inline void LogToStderr() {}
  650. inline void FlushInfoLog() { fflush(NULL); }
  651. // INTERNAL IMPLEMENTATION - DO NOT USE.
  652. //
  653. // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
  654. // is not satisfied.
  655. // Synopsys:
  656. // GTEST_CHECK_(boolean_condition);
  657. // or
  658. // GTEST_CHECK_(boolean_condition) << "Additional message";
  659. //
  660. // This checks the condition and if the condition is not satisfied
  661. // it prints message about the condition violation, including the
  662. // condition itself, plus additional message streamed into it, if any,
  663. // and then it aborts the program. It aborts the program irrespective of
  664. // whether it is built in the debug mode or not.
  665. #define GTEST_CHECK_(condition) \
  666. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  667. if (::testing::internal::IsTrue(condition)) \
  668. ; \
  669. else \
  670. GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
  671. // An all-mode assert to verify that the given POSIX-style function
  672. // call returns 0 (indicating success). Known limitation: this
  673. // doesn't expand to a balanced 'if' statement, so enclose the macro
  674. // in {} if you need to use it as the only statement in an 'if'
  675. // branch.
  676. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
  677. if (const int gtest_error = (posix_call)) \
  678. GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
  679. << gtest_error
  680. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  681. //
  682. // Downcasts the pointer of type Base to Derived.
  683. // Derived must be a subclass of Base. The parameter MUST
  684. // point to a class of type Derived, not any subclass of it.
  685. // When RTTI is available, the function performs a runtime
  686. // check to enforce this.
  687. template <class Derived, class Base>
  688. Derived* CheckedDowncastToActualType(Base* base) {
  689. #if GTEST_HAS_RTTI
  690. GTEST_CHECK_(typeid(*base) == typeid(Derived));
  691. return dynamic_cast<Derived*>(base); // NOLINT
  692. #else
  693. return static_cast<Derived*>(base); // Poor man's downcast.
  694. #endif
  695. }
  696. #if GTEST_HAS_STREAM_REDIRECTION_
  697. // Defines the stderr capturer:
  698. // CaptureStdout - starts capturing stdout.
  699. // GetCapturedStdout - stops capturing stdout and returns the captured string.
  700. // CaptureStderr - starts capturing stderr.
  701. // GetCapturedStderr - stops capturing stderr and returns the captured string.
  702. //
  703. GTEST_API_ void CaptureStdout();
  704. GTEST_API_ String GetCapturedStdout();
  705. GTEST_API_ void CaptureStderr();
  706. GTEST_API_ String GetCapturedStderr();
  707. #endif // GTEST_HAS_STREAM_REDIRECTION_
  708. #if GTEST_HAS_DEATH_TEST
  709. // A copy of all command line arguments. Set by InitGoogleTest().
  710. extern ::std::vector<String> g_argvs;
  711. // GTEST_HAS_DEATH_TEST implies we have ::std::string.
  712. const ::std::vector<String>& GetArgvs();
  713. #endif // GTEST_HAS_DEATH_TEST
  714. // Defines synchronization primitives.
  715. #if GTEST_HAS_PTHREAD
  716. // Sleeps for (roughly) n milli-seconds. This function is only for
  717. // testing Google Test's own constructs. Don't use it in user tests,
  718. // either directly or indirectly.
  719. inline void SleepMilliseconds(int n) {
  720. const timespec time = {
  721. 0, // 0 seconds.
  722. n * 1000L * 1000L, // And n ms.
  723. };
  724. nanosleep(&time, NULL);
  725. }
  726. // Allows a controller thread to pause execution of newly created
  727. // threads until notified. Instances of this class must be created
  728. // and destroyed in the controller thread.
  729. //
  730. // This class is only for testing Google Test's own constructs. Do not
  731. // use it in user tests, either directly or indirectly.
  732. class Notification {
  733. public:
  734. Notification() : notified_(false) {}
  735. // Notifies all threads created with this notification to start. Must
  736. // be called from the controller thread.
  737. void Notify() { notified_ = true; }
  738. // Blocks until the controller thread notifies. Must be called from a test
  739. // thread.
  740. void WaitForNotification() {
  741. while(!notified_) {
  742. SleepMilliseconds(10);
  743. }
  744. }
  745. private:
  746. volatile bool notified_;
  747. GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
  748. };
  749. // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
  750. // Consequently, it cannot select a correct instantiation of ThreadWithParam
  751. // in order to call its Run(). Introducing ThreadWithParamBase as a
  752. // non-templated base class for ThreadWithParam allows us to bypass this
  753. // problem.
  754. class ThreadWithParamBase {
  755. public:
  756. virtual ~ThreadWithParamBase() {}
  757. virtual void Run() = 0;
  758. };
  759. // pthread_create() accepts a pointer to a function type with the C linkage.
  760. // According to the Standard (7.5/1), function types with different linkages
  761. // are different even if they are otherwise identical. Some compilers (for
  762. // example, SunStudio) treat them as different types. Since class methods
  763. // cannot be defined with C-linkage we need to define a free C-function to
  764. // pass into pthread_create().
  765. extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
  766. static_cast<ThreadWithParamBase*>(thread)->Run();
  767. return NULL;
  768. }
  769. // Helper class for testing Google Test's multi-threading constructs.
  770. // To use it, write:
  771. //
  772. // void ThreadFunc(int param) { /* Do things with param */ }
  773. // Notification thread_can_start;
  774. // ...
  775. // // The thread_can_start parameter is optional; you can supply NULL.
  776. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
  777. // thread_can_start.Notify();
  778. //
  779. // These classes are only for testing Google Test's own constructs. Do
  780. // not use them in user tests, either directly or indirectly.
  781. template <typename T>
  782. class ThreadWithParam : public ThreadWithParamBase {
  783. public:
  784. typedef void (*UserThreadFunc)(T);
  785. ThreadWithParam(
  786. UserThreadFunc func, T param, Notification* thread_can_start)
  787. : func_(func),
  788. param_(param),
  789. thread_can_start_(thread_can_start),
  790. finished_(false) {
  791. ThreadWithParamBase* const base = this;
  792. // The thread can be created only after all fields except thread_
  793. // have been initialized.
  794. GTEST_CHECK_POSIX_SUCCESS_(
  795. pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
  796. }
  797. ~ThreadWithParam() { Join(); }
  798. void Join() {
  799. if (!finished_) {
  800. GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
  801. finished_ = true;
  802. }
  803. }
  804. virtual void Run() {
  805. if (thread_can_start_ != NULL)
  806. thread_can_start_->WaitForNotification();
  807. func_(param_);
  808. }
  809. private:
  810. const UserThreadFunc func_; // User-supplied thread function.
  811. const T param_; // User-supplied parameter to the thread function.
  812. // When non-NULL, used to block execution until the controller thread
  813. // notifies.
  814. Notification* const thread_can_start_;
  815. bool finished_; // true iff we know that the thread function has finished.
  816. pthread_t thread_; // The native thread object.
  817. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
  818. };
  819. // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
  820. // true.
  821. #include <pthread.h>
  822. // MutexBase and Mutex implement mutex on pthreads-based platforms. They
  823. // are used in conjunction with class MutexLock:
  824. //
  825. // Mutex mutex;
  826. // ...
  827. // MutexLock lock(&mutex); // Acquires the mutex and releases it at the end
  828. // // of the current scope.
  829. //
  830. // MutexBase implements behavior for both statically and dynamically
  831. // allocated mutexes. Do not use MutexBase directly. Instead, write
  832. // the following to define a static mutex:
  833. //
  834. // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
  835. //
  836. // You can forward declare a static mutex like this:
  837. //
  838. // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
  839. //
  840. // To create a dynamic mutex, just define an object of type Mutex.
  841. class MutexBase {
  842. public:
  843. // Acquires this mutex.
  844. void Lock() {
  845. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
  846. owner_ = pthread_self();
  847. }
  848. // Releases this mutex.
  849. void Unlock() {
  850. // We don't protect writing to owner_ here, as it's the caller's
  851. // responsibility to ensure that the current thread holds the
  852. // mutex when this is called.
  853. owner_ = 0;
  854. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
  855. }
  856. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  857. // with high probability.
  858. void AssertHeld() const {
  859. GTEST_CHECK_(owner_ == pthread_self())
  860. << "The current thread is not holding the mutex @" << this;
  861. }
  862. // A static mutex may be used before main() is entered. It may even
  863. // be used before the dynamic initialization stage. Therefore we
  864. // must be able to initialize a static mutex object at link time.
  865. // This means MutexBase has to be a POD and its member variables
  866. // have to be public.
  867. public:
  868. pthread_mutex_t mutex_; // The underlying pthread mutex.
  869. pthread_t owner_; // The thread holding the mutex; 0 means no one holds it.
  870. };
  871. // Forward-declares a static mutex.
  872. #define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  873. extern ::testing::internal::MutexBase mutex
  874. // Defines and statically (i.e. at link time) initializes a static mutex.
  875. #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
  876. ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, 0 }
  877. // The Mutex class can only be used for mutexes created at runtime. It
  878. // shares its API with MutexBase otherwise.
  879. class Mutex : public MutexBase {
  880. public:
  881. Mutex() {
  882. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
  883. owner_ = 0;
  884. }
  885. ~Mutex() {
  886. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
  887. }
  888. private:
  889. GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
  890. };
  891. // We cannot name this class MutexLock as the ctor declaration would
  892. // conflict with a macro named MutexLock, which is defined on some
  893. // platforms. Hence the typedef trick below.
  894. class GTestMutexLock {
  895. public:
  896. explicit GTestMutexLock(MutexBase* mutex)
  897. : mutex_(mutex) { mutex_->Lock(); }
  898. ~GTestMutexLock() { mutex_->Unlock(); }
  899. private:
  900. MutexBase* const mutex_;
  901. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
  902. };
  903. typedef GTestMutexLock MutexLock;
  904. // Helpers for ThreadLocal.
  905. // pthread_key_create() requires DeleteThreadLocalValue() to have
  906. // C-linkage. Therefore it cannot be templatized to access
  907. // ThreadLocal<T>. Hence the need for class
  908. // ThreadLocalValueHolderBase.
  909. class ThreadLocalValueHolderBase {
  910. public:
  911. virtual ~ThreadLocalValueHolderBase() {}
  912. };
  913. // Called by pthread to delete thread-local data stored by
  914. // pthread_setspecific().
  915. extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
  916. delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
  917. }
  918. // Implements thread-local storage on pthreads-based systems.
  919. //
  920. // // Thread 1
  921. // ThreadLocal<int> tl(100); // 100 is the default value for each thread.
  922. //
  923. // // Thread 2
  924. // tl.set(150); // Changes the value for thread 2 only.
  925. // EXPECT_EQ(150, tl.get());
  926. //
  927. // // Thread 1
  928. // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
  929. // tl.set(200);
  930. // EXPECT_EQ(200, tl.get());
  931. //
  932. // The template type argument T must have a public copy constructor.
  933. // In addition, the default ThreadLocal constructor requires T to have
  934. // a public default constructor.
  935. //
  936. // An object managed for a thread by a ThreadLocal instance is deleted
  937. // when the thread exits. Or, if the ThreadLocal instance dies in
  938. // that thread, when the ThreadLocal dies. It's the user's
  939. // responsibility to ensure that all other threads using a ThreadLocal
  940. // have exited when it dies, or the per-thread objects for those
  941. // threads will not be deleted.
  942. //
  943. // Google Test only uses global ThreadLocal objects. That means they
  944. // will die after main() has returned. Therefore, no per-thread
  945. // object managed by Google Test will be leaked as long as all threads
  946. // using Google Test have exited when main() returns.
  947. template <typename T>
  948. class ThreadLocal {
  949. public:
  950. ThreadLocal() : key_(CreateKey()),
  951. default_() {}
  952. explicit ThreadLocal(const T& value) : key_(CreateKey()),
  953. default_(value) {}
  954. ~ThreadLocal() {
  955. // Destroys the managed object for the current thread, if any.
  956. DeleteThreadLocalValue(pthread_getspecific(key_));
  957. // Releases resources associated with the key. This will *not*
  958. // delete managed objects for other threads.
  959. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
  960. }
  961. T* pointer() { return GetOrCreateValue(); }
  962. const T* pointer() const { return GetOrCreateValue(); }
  963. const T& get() const { return *pointer(); }
  964. void set(const T& value) { *pointer() = value; }
  965. private:
  966. // Holds a value of type T.
  967. class ValueHolder : public ThreadLocalValueHolderBase {
  968. public:
  969. explicit ValueHolder(const T& value) : value_(value) {}
  970. T* pointer() { return &value_; }
  971. private:
  972. T value_;
  973. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
  974. };
  975. static pthread_key_t CreateKey() {
  976. pthread_key_t key;
  977. // When a thread exits, DeleteThreadLocalValue() will be called on
  978. // the object managed for that thread.
  979. GTEST_CHECK_POSIX_SUCCESS_(
  980. pthread_key_create(&key, &DeleteThreadLocalValue));
  981. return key;
  982. }
  983. T* GetOrCreateValue() const {
  984. ThreadLocalValueHolderBase* const holder =
  985. static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
  986. if (holder != NULL) {
  987. return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
  988. }
  989. ValueHolder* const new_holder = new ValueHolder(default_);
  990. ThreadLocalValueHolderBase* const holder_base = new_holder;
  991. GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
  992. return new_holder->pointer();
  993. }
  994. // A key pthreads uses for looking up per-thread values.
  995. const pthread_key_t key_;
  996. const T default_; // The default value for each thread.
  997. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
  998. };
  999. #define GTEST_IS_THREADSAFE 1
  1000. #else // GTEST_HAS_PTHREAD
  1001. // A dummy implementation of synchronization primitives (mutex, lock,
  1002. // and thread-local variable). Necessary for compiling Google Test where
  1003. // mutex is not supported - using Google Test in multiple threads is not
  1004. // supported on such platforms.
  1005. class Mutex {
  1006. public:
  1007. Mutex() {}
  1008. void AssertHeld() const {}
  1009. };
  1010. #define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1011. extern ::testing::internal::Mutex mutex
  1012. #define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
  1013. class GTestMutexLock {
  1014. public:
  1015. explicit GTestMutexLock(Mutex*) {} // NOLINT
  1016. };
  1017. typedef GTestMutexLock MutexLock;
  1018. template <typename T>
  1019. class ThreadLocal {
  1020. public:
  1021. ThreadLocal() : value_() {}
  1022. explicit ThreadLocal(const T& value) : value_(value) {}
  1023. T* pointer() { return &value_; }
  1024. const T* pointer() const { return &value_; }
  1025. const T& get() const { return value_; }
  1026. void set(const T& value) { value_ = value; }
  1027. private:
  1028. T value_;
  1029. };
  1030. // The above synchronization primitives have dummy implementations.
  1031. // Therefore Google Test is not thread-safe.
  1032. #define GTEST_IS_THREADSAFE 0
  1033. #endif // GTEST_HAS_PTHREAD
  1034. // Returns the number of threads running in the process, or 0 to indicate that
  1035. // we cannot detect it.
  1036. GTEST_API_ size_t GetThreadCount();
  1037. // Passing non-POD classes through ellipsis (...) crashes the ARM
  1038. // compiler and generates a warning in Sun Studio. The Nokia Symbian
  1039. // and the IBM XL C/C++ compiler try to instantiate a copy constructor
  1040. // for objects passed through ellipsis (...), failing for uncopyable
  1041. // objects. We define this to ensure that only POD is passed through
  1042. // ellipsis on these systems.
  1043. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC)
  1044. // We lose support for NULL detection where the compiler doesn't like
  1045. // passing non-POD classes through ellipsis (...).
  1046. #define GTEST_ELLIPSIS_NEEDS_POD_ 1
  1047. #else
  1048. #define GTEST_CAN_COMPARE_NULL 1
  1049. #endif
  1050. // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
  1051. // const T& and const T* in a function template. These compilers
  1052. // _can_ decide between class template specializations for T and T*,
  1053. // so a tr1::type_traits-like is_pointer works.
  1054. #if defined(__SYMBIAN32__) || defined(__IBMCPP__)
  1055. #define GTEST_NEEDS_IS_POINTER_ 1
  1056. #endif
  1057. template <bool bool_value>
  1058. struct bool_constant {
  1059. typedef bool_constant<bool_value> type;
  1060. static const bool value = bool_value;
  1061. };
  1062. template <bool bool_value> const bool bool_constant<bool_value>::value;
  1063. typedef bool_constant<false> false_type;
  1064. typedef bool_constant<true> true_type;
  1065. template <typename T>
  1066. struct is_pointer : public false_type {};
  1067. template <typename T>
  1068. struct is_pointer<T*> : public true_type {};
  1069. #if GTEST_OS_WINDOWS
  1070. #define GTEST_PATH_SEP_ "\\"
  1071. #define GTEST_HAS_ALT_PATH_SEP_ 1
  1072. // The biggest signed integer type the compiler supports.
  1073. typedef __int64 BiggestInt;
  1074. #else
  1075. #define GTEST_PATH_SEP_ "/"
  1076. #define GTEST_HAS_ALT_PATH_SEP_ 0
  1077. typedef long long BiggestInt; // NOLINT
  1078. #endif // GTEST_OS_WINDOWS
  1079. // The testing::internal::posix namespace holds wrappers for common
  1080. // POSIX functions. These wrappers hide the differences between
  1081. // Windows/MSVC and POSIX systems. Since some compilers define these
  1082. // standard functions as macros, the wrapper cannot have the same name
  1083. // as the wrapped function.
  1084. namespace posix {
  1085. // Functions with a different name on Windows.
  1086. #if GTEST_OS_WINDOWS
  1087. typedef struct _stat StatStruct;
  1088. #ifdef __BORLANDC__
  1089. inline int IsATTY(int fd) { return isatty(fd); }
  1090. inline int StrCaseCmp(const char* s1, const char* s2) {
  1091. return stricmp(s1, s2);
  1092. }
  1093. inline char* StrDup(const char* src) { return strdup(src); }
  1094. #else // !__BORLANDC__
  1095. #if GTEST_OS_WINDOWS_MOBILE
  1096. inline int IsATTY(int /* fd */) { return 0; }
  1097. #else
  1098. inline int IsATTY(int fd) { return _isatty(fd); }
  1099. #endif // GTEST_OS_WINDOWS_MOBILE
  1100. inline int StrCaseCmp(const char* s1, const char* s2) {
  1101. return _stricmp(s1, s2);
  1102. }
  1103. inline char* StrDup(const char* src) { return _strdup(src); }
  1104. #endif // __BORLANDC__
  1105. #if GTEST_OS_WINDOWS_MOBILE
  1106. inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
  1107. // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
  1108. // time and thus not defined there.
  1109. #else
  1110. inline int FileNo(FILE* file) { return _fileno(file); }
  1111. inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
  1112. inline int RmDir(const char* dir) { return _rmdir(dir); }
  1113. inline bool IsDir(const StatStruct& st) {
  1114. return (_S_IFDIR & st.st_mode) != 0;
  1115. }
  1116. #endif // GTEST_OS_WINDOWS_MOBILE
  1117. #else
  1118. typedef struct stat StatStruct;
  1119. inline int FileNo(FILE* file) { return fileno(file); }
  1120. inline int IsATTY(int fd) { return isatty(fd); }
  1121. inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
  1122. inline int StrCaseCmp(const char* s1, const char* s2) {
  1123. return strcasecmp(s1, s2);
  1124. }
  1125. inline char* StrDup(const char* src) { return strdup(src); }
  1126. inline int RmDir(const char* dir) { return rmdir(dir); }
  1127. inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
  1128. #endif // GTEST_OS_WINDOWS
  1129. // Functions deprecated by MSVC 8.0.
  1130. #ifdef _MSC_VER
  1131. // Temporarily disable warning 4996 (deprecated function).
  1132. #pragma warning(push)
  1133. #pragma warning(disable:4996)
  1134. #endif
  1135. inline const char* StrNCpy(char* dest, const char* src, size_t n) {
  1136. return strncpy(dest, src, n);
  1137. }
  1138. // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
  1139. // StrError() aren't needed on Windows CE at this time and thus not
  1140. // defined there.
  1141. #if !GTEST_OS_WINDOWS_MOBILE
  1142. inline int ChDir(const char* dir) { return chdir(dir); }
  1143. #endif
  1144. inline FILE* FOpen(const char* path, const char* mode) {
  1145. return fopen(path, mode);
  1146. }
  1147. #if !GTEST_OS_WINDOWS_MOBILE
  1148. inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
  1149. return freopen(path, mode, stream);
  1150. }
  1151. inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
  1152. #endif
  1153. inline int FClose(FILE* fp) { return fclose(fp); }
  1154. #if !GTEST_OS_WINDOWS_MOBILE
  1155. inline int Read(int fd, void* buf, unsigned int count) {
  1156. return static_cast<int>(read(fd, buf, count));
  1157. }
  1158. inline int Write(int fd, const void* buf, unsigned int count) {
  1159. return static_cast<int>(write(fd, buf, count));
  1160. }
  1161. inline int Close(int fd) { return close(fd); }
  1162. inline const char* StrError(int errnum) { return strerror(errnum); }
  1163. #endif
  1164. inline const char* GetEnv(const char* name) {
  1165. #if GTEST_OS_WINDOWS_MOBILE
  1166. // We are on Windows CE, which has no environment variables.
  1167. return NULL;
  1168. #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
  1169. // Environment variables which we programmatically clear will be set to the
  1170. // empty string rather than unset (NULL). Handle that case.
  1171. const char* const env = getenv(name);
  1172. return (env != NULL && env[0] != '\0') ? env : NULL;
  1173. #else
  1174. return getenv(name);
  1175. #endif
  1176. }
  1177. #ifdef _MSC_VER
  1178. #pragma warning(pop) // Restores the warning state.
  1179. #endif
  1180. #if GTEST_OS_WINDOWS_MOBILE
  1181. // Windows CE has no C library. The abort() function is used in
  1182. // several places in Google Test. This implementation provides a reasonable
  1183. // imitation of standard behaviour.
  1184. void Abort();
  1185. #else
  1186. inline void Abort() { abort(); }
  1187. #endif // GTEST_OS_WINDOWS_MOBILE
  1188. } // namespace posix
  1189. // The maximum number a BiggestInt can represent. This definition
  1190. // works no matter BiggestInt is represented in one's complement or
  1191. // two's complement.
  1192. //
  1193. // We cannot rely on numeric_limits in STL, as __int64 and long long
  1194. // are not part of standard C++ and numeric_limits doesn't need to be
  1195. // defined for them.
  1196. const BiggestInt kMaxBiggestInt =
  1197. ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
  1198. // This template class serves as a compile-time function from size to
  1199. // type. It maps a size in bytes to a primitive type with that
  1200. // size. e.g.
  1201. //
  1202. // TypeWithSize<4>::UInt
  1203. //
  1204. // is typedef-ed to be unsigned int (unsigned integer made up of 4
  1205. // bytes).
  1206. //
  1207. // Such functionality should belong to STL, but I cannot find it
  1208. // there.
  1209. //
  1210. // Google Test uses this class in the implementation of floating-point
  1211. // comparison.
  1212. //
  1213. // For now it only handles UInt (unsigned int) as that's all Google Test
  1214. // needs. Other types can be easily added in the future if need
  1215. // arises.
  1216. template <size_t size>
  1217. class TypeWithSize {
  1218. public:
  1219. // This prevents the user from using TypeWithSize<N> with incorrect
  1220. // values of N.
  1221. typedef void UInt;
  1222. };
  1223. // The specialization for size 4.
  1224. template <>
  1225. class TypeWithSize<4> {
  1226. public:
  1227. // unsigned int has size 4 in both gcc and MSVC.
  1228. //
  1229. // As base/basictypes.h doesn't compile on Windows, we cannot use
  1230. // uint32, uint64, and etc here.
  1231. typedef int Int;
  1232. typedef unsigned int UInt;
  1233. };
  1234. // The specialization for size 8.
  1235. template <>
  1236. class TypeWithSize<8> {
  1237. public:
  1238. #if GTEST_OS_WINDOWS
  1239. typedef __int64 Int;
  1240. typedef unsigned __int64 UInt;
  1241. #else
  1242. typedef long long Int; // NOLINT
  1243. typedef unsigned long long UInt; // NOLINT
  1244. #endif // GTEST_OS_WINDOWS
  1245. };
  1246. // Integer types of known sizes.
  1247. typedef TypeWithSize<4>::Int Int32;
  1248. typedef TypeWithSize<4>::UInt UInt32;
  1249. typedef TypeWithSize<8>::Int Int64;
  1250. typedef TypeWithSize<8>::UInt UInt64;
  1251. typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
  1252. // Utilities for command line flags and environment variables.
  1253. // Macro for referencing flags.
  1254. #define GTEST_FLAG(name) FLAGS_gtest_##name
  1255. // Macros for declaring flags.
  1256. #define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
  1257. #define GTEST_DECLARE_int32_(name) \
  1258. GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
  1259. #define GTEST_DECLARE_string_(name) \
  1260. GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name)
  1261. // Macros for defining flags.
  1262. #define GTEST_DEFINE_bool_(name, default_val, doc) \
  1263. GTEST_API_ bool GTEST_FLAG(name) = (default_val)
  1264. #define GTEST_DEFINE_int32_(name, default_val, doc) \
  1265. GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
  1266. #define GTEST_DEFINE_string_(name, default_val, doc) \
  1267. GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val)
  1268. // Parses 'str' for a 32-bit signed integer. If successful, writes the result
  1269. // to *value and returns true; otherwise leaves *value unchanged and returns
  1270. // false.
  1271. // TODO(chandlerc): Find a better way to refactor flag and environment parsing
  1272. // out of both gtest-port.cc and gtest.cc to avoid exporting this utility
  1273. // function.
  1274. bool ParseInt32(const Message& src_text, const char* str, Int32* value);
  1275. // Parses a bool/Int32/string from the environment variable
  1276. // corresponding to the given Google Test flag.
  1277. bool BoolFromGTestEnv(const char* flag, bool default_val);
  1278. GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
  1279. const char* StringFromGTestEnv(const char* flag, const char* default_val);
  1280. } // namespace internal
  1281. } // namespace testing
  1282. #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_