You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1778 lines
61 KiB

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