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