gtest-port.h revision 5df87d70b64dd8080ab9e3f1b0250e74715e2a60
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// tuple.
644// TODO(sbenza): Enable this block to start using std::tuple instead of
645//               std::tr1::tuple.
646#if 0 && GTEST_HAS_STD_TUPLE_
647# include <tuple>
648# define GTEST_TUPLE_NAMESPACE_ ::std
649#endif
650
651#if GTEST_HAS_TR1_TUPLE
652# ifndef GTEST_TUPLE_NAMESPACE_
653#  define GTEST_TUPLE_NAMESPACE_ ::std::tr1
654# endif  // GTEST_TUPLE_NAMESPACE_
655
656# if GTEST_USE_OWN_TR1_TUPLE
657#  include "gtest/internal/gtest-tuple.h"
658# elif GTEST_ENV_HAS_STD_TUPLE_
659#  include <tuple>
660// C++11 puts its tuple into the ::std namespace rather than
661// ::std::tr1.  gtest expects tuple to live in ::std::tr1, so put it there.
662// This causes undefined behavior, but supported compilers react in
663// the way we intend.
664namespace std {
665namespace tr1 {
666using ::std::get;
667using ::std::make_tuple;
668using ::std::tuple;
669using ::std::tuple_element;
670using ::std::tuple_size;
671}
672}
673
674# elif GTEST_OS_SYMBIAN
675
676// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
677// use STLport's tuple implementation, which unfortunately doesn't
678// work as the copy of STLport distributed with Symbian is incomplete.
679// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
680// use its own tuple implementation.
681#  ifdef BOOST_HAS_TR1_TUPLE
682#   undef BOOST_HAS_TR1_TUPLE
683#  endif  // BOOST_HAS_TR1_TUPLE
684
685// This prevents <boost/tr1/detail/config.hpp>, which defines
686// BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
687#  define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
688#  include <tuple>
689
690# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
691// GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header.  This does
692// not conform to the TR1 spec, which requires the header to be <tuple>.
693
694#  if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
695// Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
696// which is #included by <tr1/tuple>, to not compile when RTTI is
697// disabled.  _TR1_FUNCTIONAL is the header guard for
698// <tr1/functional>.  Hence the following #define is a hack to prevent
699// <tr1/functional> from being included.
700#   define _TR1_FUNCTIONAL 1
701#   include <tr1/tuple>
702#   undef _TR1_FUNCTIONAL  // Allows the user to #include
703                        // <tr1/functional> if he chooses to.
704#  else
705#   include <tr1/tuple>  // NOLINT
706#  endif  // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
707
708# else
709// If the compiler is not GCC 4.0+, we assume the user is using a
710// spec-conforming TR1 implementation.
711#  include <tuple>  // NOLINT
712# endif  // GTEST_USE_OWN_TR1_TUPLE
713
714#endif  // GTEST_HAS_TR1_TUPLE
715
716// Determines whether clone(2) is supported.
717// Usually it will only be available on Linux, excluding
718// Linux on the Itanium architecture.
719// Also see http://linux.die.net/man/2/clone.
720#ifndef GTEST_HAS_CLONE
721// The user didn't tell us, so we need to figure it out.
722
723# if GTEST_OS_LINUX && !defined(__ia64__)
724#  if GTEST_OS_LINUX_ANDROID
725// On Android, clone() is only available on ARM starting with Gingerbread.
726#    if defined(__arm__) && __ANDROID_API__ >= 9
727#     define GTEST_HAS_CLONE 1
728#    else
729#     define GTEST_HAS_CLONE 0
730#    endif
731#  else
732#   define GTEST_HAS_CLONE 1
733#  endif
734# else
735#  define GTEST_HAS_CLONE 0
736# endif  // GTEST_OS_LINUX && !defined(__ia64__)
737
738#endif  // GTEST_HAS_CLONE
739
740// Determines whether to support stream redirection. This is used to test
741// output correctness and to implement death tests.
742#ifndef GTEST_HAS_STREAM_REDIRECTION
743// By default, we assume that stream redirection is supported on all
744// platforms except known mobile ones.
745# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN
746#  define GTEST_HAS_STREAM_REDIRECTION 0
747# else
748#  define GTEST_HAS_STREAM_REDIRECTION 1
749# endif  // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
750#endif  // GTEST_HAS_STREAM_REDIRECTION
751
752// Determines whether to support death tests.
753// Google Test does not support death tests for VC 7.1 and earlier as
754// abort() in a VC 7.1 application compiled as GUI in debug config
755// pops up a dialog window that cannot be suppressed programmatically.
756#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
757     (GTEST_OS_MAC && !GTEST_OS_IOS) || GTEST_OS_IOS_SIMULATOR || \
758     (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
759     GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
760     GTEST_OS_OPENBSD || GTEST_OS_QNX)
761# define GTEST_HAS_DEATH_TEST 1
762# include <vector>  // NOLINT
763#endif
764
765// We don't support MSVC 7.1 with exceptions disabled now.  Therefore
766// all the compilers we care about are adequate for supporting
767// value-parameterized tests.
768#define GTEST_HAS_PARAM_TEST 1
769
770// Determines whether to support type-driven tests.
771
772// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
773// Sun Pro CC, IBM Visual Age, and HP aCC support.
774#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
775    defined(__IBMCPP__) || defined(__HP_aCC)
776# define GTEST_HAS_TYPED_TEST 1
777# define GTEST_HAS_TYPED_TEST_P 1
778#endif
779
780// Determines whether to support Combine(). This only makes sense when
781// value-parameterized tests are enabled.  The implementation doesn't
782// work on Sun Studio since it doesn't understand templated conversion
783// operators.
784#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
785# define GTEST_HAS_COMBINE 1
786#endif
787
788// Determines whether the system compiler uses UTF-16 for encoding wide strings.
789#define GTEST_WIDE_STRING_USES_UTF16_ \
790    (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
791
792// Determines whether test results can be streamed to a socket.
793#if GTEST_OS_LINUX
794# define GTEST_CAN_STREAM_RESULTS_ 1
795#endif
796
797// Defines some utility macros.
798
799// The GNU compiler emits a warning if nested "if" statements are followed by
800// an "else" statement and braces are not used to explicitly disambiguate the
801// "else" binding.  This leads to problems with code like:
802//
803//   if (gate)
804//     ASSERT_*(condition) << "Some message";
805//
806// The "switch (0) case 0:" idiom is used to suppress this.
807#ifdef __INTEL_COMPILER
808# define GTEST_AMBIGUOUS_ELSE_BLOCKER_
809#else
810# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default:  // NOLINT
811#endif
812
813// Use this annotation at the end of a struct/class definition to
814// prevent the compiler from optimizing away instances that are never
815// used.  This is useful when all interesting logic happens inside the
816// c'tor and / or d'tor.  Example:
817//
818//   struct Foo {
819//     Foo() { ... }
820//   } GTEST_ATTRIBUTE_UNUSED_;
821//
822// Also use it after a variable or parameter declaration to tell the
823// compiler the variable/parameter does not have to be used.
824#if defined(__GNUC__) && !defined(COMPILER_ICC)
825# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
826#else
827# define GTEST_ATTRIBUTE_UNUSED_
828#endif
829
830// A macro to disallow operator=
831// This should be used in the private: declarations for a class.
832#define GTEST_DISALLOW_ASSIGN_(type)\
833  void operator=(type const &)
834
835// A macro to disallow copy constructor and operator=
836// This should be used in the private: declarations for a class.
837#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
838  type(type const &);\
839  GTEST_DISALLOW_ASSIGN_(type)
840
841// Tell the compiler to warn about unused return values for functions declared
842// with this macro.  The macro should be used on function declarations
843// following the argument list:
844//
845//   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
846#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
847# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
848#else
849# define GTEST_MUST_USE_RESULT_
850#endif  // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
851
852#if GTEST_LANG_CXX11
853# define GTEST_MOVE_(x) ::std::move(x)  // NOLINT
854#else
855# define GTEST_MOVE_(x) x
856#endif
857
858// MS C++ compiler emits warning when a conditional expression is compile time
859// constant. In some contexts this warning is false positive and needs to be
860// suppressed. Use the following two macros in such cases:
861//
862// GTEST_INTENTIONAL_CONST_COND_PUSH_
863// while (true) {
864// GTEST_INTENTIONAL_CONST_COND_POP_
865// }
866#if defined(_MSC_VER)
867# define GTEST_INTENTIONAL_CONST_COND_PUSH_ \
868    __pragma(warning(push)) \
869    __pragma(warning(disable: 4127))
870# define GTEST_INTENTIONAL_CONST_COND_POP_ \
871    __pragma(warning(pop))
872#else
873# define GTEST_INTENTIONAL_CONST_COND_PUSH_
874# define GTEST_INTENTIONAL_CONST_COND_POP_
875#endif
876
877// Determine whether the compiler supports Microsoft's Structured Exception
878// Handling.  This is supported by several Windows compilers but generally
879// does not exist on any other system.
880#ifndef GTEST_HAS_SEH
881// The user didn't tell us, so we need to figure it out.
882
883# if defined(_MSC_VER) || defined(__BORLANDC__)
884// These two compilers are known to support SEH.
885#  define GTEST_HAS_SEH 1
886# else
887// Assume no SEH.
888#  define GTEST_HAS_SEH 0
889# endif
890
891#define GTEST_IS_THREADSAFE \
892    (GTEST_OS_WINDOWS || GTEST_HAS_PTHREAD)
893
894#endif  // GTEST_HAS_SEH
895
896#ifdef _MSC_VER
897
898# if GTEST_LINKED_AS_SHARED_LIBRARY
899#  define GTEST_API_ __declspec(dllimport)
900# elif GTEST_CREATE_SHARED_LIBRARY
901#  define GTEST_API_ __declspec(dllexport)
902# endif
903
904#endif  // _MSC_VER
905
906#ifndef GTEST_API_
907# define GTEST_API_
908#endif
909
910#ifdef __GNUC__
911// Ask the compiler to never inline a given function.
912# define GTEST_NO_INLINE_ __attribute__((noinline))
913#else
914# define GTEST_NO_INLINE_
915#endif
916
917// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
918#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
919# define GTEST_HAS_CXXABI_H_ 1
920#else
921# define GTEST_HAS_CXXABI_H_ 0
922#endif
923
924// A function level attribute to disable checking for use of uninitialized
925// memory when built with MemorySanitizer.
926#if defined(__clang__)
927# if __has_feature(memory_sanitizer)
928#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
929       __attribute__((no_sanitize_memory))
930# else
931#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
932# endif  // __has_feature(memory_sanitizer)
933#else
934# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
935#endif  // __clang__
936
937// A function level attribute to disable AddressSanitizer instrumentation.
938#if defined(__clang__)
939# if __has_feature(address_sanitizer)
940#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
941       __attribute__((no_sanitize_address))
942# else
943#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
944# endif  // __has_feature(address_sanitizer)
945#else
946# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
947#endif  // __clang__
948
949// A function level attribute to disable ThreadSanitizer instrumentation.
950#if defined(__clang__)
951# if __has_feature(thread_sanitizer)
952#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
953       __attribute__((no_sanitize_thread))
954# else
955#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
956# endif  // __has_feature(thread_sanitizer)
957#else
958# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
959#endif  // __clang__
960
961namespace testing {
962
963class Message;
964
965// Import tuple and friends into the ::testing namespace.
966// It is part of our interface, having them in ::testing allows us to change
967// their types as needed.
968using GTEST_TUPLE_NAMESPACE_::get;
969using GTEST_TUPLE_NAMESPACE_::make_tuple;
970using GTEST_TUPLE_NAMESPACE_::tuple;
971using GTEST_TUPLE_NAMESPACE_::tuple_size;
972using GTEST_TUPLE_NAMESPACE_::tuple_element;
973
974namespace internal {
975
976// A secret type that Google Test users don't know about.  It has no
977// definition on purpose.  Therefore it's impossible to create a
978// Secret object, which is what we want.
979class Secret;
980
981// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
982// expression is true. For example, you could use it to verify the
983// size of a static array:
984//
985//   GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
986//                         names_incorrect_size);
987//
988// or to make sure a struct is smaller than a certain size:
989//
990//   GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
991//
992// The second argument to the macro is the name of the variable. If
993// the expression is false, most compilers will issue a warning/error
994// containing the name of the variable.
995
996template <bool>
997struct CompileAssert {
998};
999
1000#define GTEST_COMPILE_ASSERT_(expr, msg) \
1001  typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
1002      msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
1003
1004// Implementation details of GTEST_COMPILE_ASSERT_:
1005//
1006// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
1007//   elements (and thus is invalid) when the expression is false.
1008//
1009// - The simpler definition
1010//
1011//    #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
1012//
1013//   does not work, as gcc supports variable-length arrays whose sizes
1014//   are determined at run-time (this is gcc's extension and not part
1015//   of the C++ standard).  As a result, gcc fails to reject the
1016//   following code with the simple definition:
1017//
1018//     int foo;
1019//     GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
1020//                                      // not a compile-time constant.
1021//
1022// - By using the type CompileAssert<(bool(expr))>, we ensures that
1023//   expr is a compile-time constant.  (Template arguments must be
1024//   determined at compile-time.)
1025//
1026// - The outter parentheses in CompileAssert<(bool(expr))> are necessary
1027//   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
1028//
1029//     CompileAssert<bool(expr)>
1030//
1031//   instead, these compilers will refuse to compile
1032//
1033//     GTEST_COMPILE_ASSERT_(5 > 0, some_message);
1034//
1035//   (They seem to think the ">" in "5 > 0" marks the end of the
1036//   template argument list.)
1037//
1038// - The array size is (bool(expr) ? 1 : -1), instead of simply
1039//
1040//     ((expr) ? 1 : -1).
1041//
1042//   This is to avoid running into a bug in MS VC 7.1, which
1043//   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
1044
1045// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
1046//
1047// This template is declared, but intentionally undefined.
1048template <typename T1, typename T2>
1049struct StaticAssertTypeEqHelper;
1050
1051template <typename T>
1052struct StaticAssertTypeEqHelper<T, T> {};
1053
1054// Evaluates to the number of elements in 'array'.
1055#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
1056
1057#if GTEST_HAS_GLOBAL_STRING
1058typedef ::string string;
1059#else
1060typedef ::std::string string;
1061#endif  // GTEST_HAS_GLOBAL_STRING
1062
1063#if GTEST_HAS_GLOBAL_WSTRING
1064typedef ::wstring wstring;
1065#elif GTEST_HAS_STD_WSTRING
1066typedef ::std::wstring wstring;
1067#endif  // GTEST_HAS_GLOBAL_WSTRING
1068
1069// A helper for suppressing warnings on constant condition.  It just
1070// returns 'condition'.
1071GTEST_API_ bool IsTrue(bool condition);
1072
1073// Defines scoped_ptr.
1074
1075// This implementation of scoped_ptr is PARTIAL - it only contains
1076// enough stuff to satisfy Google Test's need.
1077template <typename T>
1078class scoped_ptr {
1079 public:
1080  typedef T element_type;
1081
1082  explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
1083  ~scoped_ptr() { reset(); }
1084
1085  T& operator*() const { return *ptr_; }
1086  T* operator->() const { return ptr_; }
1087  T* get() const { return ptr_; }
1088
1089  T* release() {
1090    T* const ptr = ptr_;
1091    ptr_ = NULL;
1092    return ptr;
1093  }
1094
1095  void reset(T* p = NULL) {
1096    if (p != ptr_) {
1097      if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
1098        delete ptr_;
1099      }
1100      ptr_ = p;
1101    }
1102  }
1103
1104 private:
1105  T* ptr_;
1106
1107  GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
1108};
1109
1110// Defines RE.
1111
1112// A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
1113// Regular Expression syntax.
1114class GTEST_API_ RE {
1115 public:
1116  // A copy constructor is required by the Standard to initialize object
1117  // references from r-values.
1118  RE(const RE& other) { Init(other.pattern()); }
1119
1120  // Constructs an RE from a string.
1121  RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
1122
1123#if GTEST_HAS_GLOBAL_STRING
1124
1125  RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
1126
1127#endif  // GTEST_HAS_GLOBAL_STRING
1128
1129  RE(const char* regex) { Init(regex); }  // NOLINT
1130  ~RE();
1131
1132  // Returns the string representation of the regex.
1133  const char* pattern() const { return pattern_; }
1134
1135  // FullMatch(str, re) returns true iff regular expression re matches
1136  // the entire str.
1137  // PartialMatch(str, re) returns true iff regular expression re
1138  // matches a substring of str (including str itself).
1139  //
1140  // TODO(wan@google.com): make FullMatch() and PartialMatch() work
1141  // when str contains NUL characters.
1142  static bool FullMatch(const ::std::string& str, const RE& re) {
1143    return FullMatch(str.c_str(), re);
1144  }
1145  static bool PartialMatch(const ::std::string& str, const RE& re) {
1146    return PartialMatch(str.c_str(), re);
1147  }
1148
1149#if GTEST_HAS_GLOBAL_STRING
1150
1151  static bool FullMatch(const ::string& str, const RE& re) {
1152    return FullMatch(str.c_str(), re);
1153  }
1154  static bool PartialMatch(const ::string& str, const RE& re) {
1155    return PartialMatch(str.c_str(), re);
1156  }
1157
1158#endif  // GTEST_HAS_GLOBAL_STRING
1159
1160  static bool FullMatch(const char* str, const RE& re);
1161  static bool PartialMatch(const char* str, const RE& re);
1162
1163 private:
1164  void Init(const char* regex);
1165
1166  // We use a const char* instead of an std::string, as Google Test used to be
1167  // used where std::string is not available.  TODO(wan@google.com): change to
1168  // std::string.
1169  const char* pattern_;
1170  bool is_valid_;
1171
1172#if GTEST_USES_POSIX_RE
1173
1174  regex_t full_regex_;     // For FullMatch().
1175  regex_t partial_regex_;  // For PartialMatch().
1176
1177#else  // GTEST_USES_SIMPLE_RE
1178
1179  const char* full_pattern_;  // For FullMatch();
1180
1181#endif
1182
1183  GTEST_DISALLOW_ASSIGN_(RE);
1184};
1185
1186// Formats a source file path and a line number as they would appear
1187// in an error message from the compiler used to compile this code.
1188GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
1189
1190// Formats a file location for compiler-independent XML output.
1191// Although this function is not platform dependent, we put it next to
1192// FormatFileLocation in order to contrast the two functions.
1193GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
1194                                                               int line);
1195
1196// Defines logging utilities:
1197//   GTEST_LOG_(severity) - logs messages at the specified severity level. The
1198//                          message itself is streamed into the macro.
1199//   LogToStderr()  - directs all log messages to stderr.
1200//   FlushInfoLog() - flushes informational log messages.
1201
1202enum GTestLogSeverity {
1203  GTEST_INFO,
1204  GTEST_WARNING,
1205  GTEST_ERROR,
1206  GTEST_FATAL
1207};
1208
1209// Formats log entry severity, provides a stream object for streaming the
1210// log message, and terminates the message with a newline when going out of
1211// scope.
1212class GTEST_API_ GTestLog {
1213 public:
1214  GTestLog(GTestLogSeverity severity, const char* file, int line);
1215
1216  // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1217  ~GTestLog();
1218
1219  ::std::ostream& GetStream() { return ::std::cerr; }
1220
1221 private:
1222  const GTestLogSeverity severity_;
1223
1224  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
1225};
1226
1227#define GTEST_LOG_(severity) \
1228    ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
1229                                  __FILE__, __LINE__).GetStream()
1230
1231inline void LogToStderr() {}
1232inline void FlushInfoLog() { fflush(NULL); }
1233
1234// INTERNAL IMPLEMENTATION - DO NOT USE.
1235//
1236// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
1237// is not satisfied.
1238//  Synopsys:
1239//    GTEST_CHECK_(boolean_condition);
1240//     or
1241//    GTEST_CHECK_(boolean_condition) << "Additional message";
1242//
1243//    This checks the condition and if the condition is not satisfied
1244//    it prints message about the condition violation, including the
1245//    condition itself, plus additional message streamed into it, if any,
1246//    and then it aborts the program. It aborts the program irrespective of
1247//    whether it is built in the debug mode or not.
1248#define GTEST_CHECK_(condition) \
1249    GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1250    if (::testing::internal::IsTrue(condition)) \
1251      ; \
1252    else \
1253      GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
1254
1255// An all-mode assert to verify that the given POSIX-style function
1256// call returns 0 (indicating success).  Known limitation: this
1257// doesn't expand to a balanced 'if' statement, so enclose the macro
1258// in {} if you need to use it as the only statement in an 'if'
1259// branch.
1260#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
1261  if (const int gtest_error = (posix_call)) \
1262    GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
1263                      << gtest_error
1264
1265// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1266//
1267// Use ImplicitCast_ as a safe version of static_cast for upcasting in
1268// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
1269// const Foo*).  When you use ImplicitCast_, the compiler checks that
1270// the cast is safe.  Such explicit ImplicitCast_s are necessary in
1271// surprisingly many situations where C++ demands an exact type match
1272// instead of an argument type convertable to a target type.
1273//
1274// The syntax for using ImplicitCast_ is the same as for static_cast:
1275//
1276//   ImplicitCast_<ToType>(expr)
1277//
1278// ImplicitCast_ would have been part of the C++ standard library,
1279// but the proposal was submitted too late.  It will probably make
1280// its way into the language in the future.
1281//
1282// This relatively ugly name is intentional. It prevents clashes with
1283// similar functions users may have (e.g., implicit_cast). The internal
1284// namespace alone is not enough because the function can be found by ADL.
1285template<typename To>
1286inline To ImplicitCast_(To x) { return x; }
1287
1288// When you upcast (that is, cast a pointer from type Foo to type
1289// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
1290// always succeed.  When you downcast (that is, cast a pointer from
1291// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
1292// how do you know the pointer is really of type SubclassOfFoo?  It
1293// could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
1294// when you downcast, you should use this macro.  In debug mode, we
1295// use dynamic_cast<> to double-check the downcast is legal (we die
1296// if it's not).  In normal mode, we do the efficient static_cast<>
1297// instead.  Thus, it's important to test in debug mode to make sure
1298// the cast is legal!
1299//    This is the only place in the code we should use dynamic_cast<>.
1300// In particular, you SHOULDN'T be using dynamic_cast<> in order to
1301// do RTTI (eg code like this:
1302//    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
1303//    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
1304// You should design the code some other way not to need this.
1305//
1306// This relatively ugly name is intentional. It prevents clashes with
1307// similar functions users may have (e.g., down_cast). The internal
1308// namespace alone is not enough because the function can be found by ADL.
1309template<typename To, typename From>  // use like this: DownCast_<T*>(foo);
1310inline To DownCast_(From* f) {  // so we only accept pointers
1311  // Ensures that To is a sub-type of From *.  This test is here only
1312  // for compile-time type checking, and has no overhead in an
1313  // optimized build at run-time, as it will be optimized away
1314  // completely.
1315  GTEST_INTENTIONAL_CONST_COND_PUSH_
1316  if (false) {
1317  GTEST_INTENTIONAL_CONST_COND_POP_
1318    const To to = NULL;
1319    ::testing::internal::ImplicitCast_<From*>(to);
1320  }
1321
1322#if GTEST_HAS_RTTI
1323  // RTTI: debug mode only!
1324  GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL);
1325#endif
1326  return static_cast<To>(f);
1327}
1328
1329// Downcasts the pointer of type Base to Derived.
1330// Derived must be a subclass of Base. The parameter MUST
1331// point to a class of type Derived, not any subclass of it.
1332// When RTTI is available, the function performs a runtime
1333// check to enforce this.
1334template <class Derived, class Base>
1335Derived* CheckedDowncastToActualType(Base* base) {
1336#if GTEST_HAS_RTTI
1337  GTEST_CHECK_(typeid(*base) == typeid(Derived));
1338  return dynamic_cast<Derived*>(base);  // NOLINT
1339#else
1340  return static_cast<Derived*>(base);  // Poor man's downcast.
1341#endif
1342}
1343
1344#if GTEST_HAS_STREAM_REDIRECTION
1345
1346// Defines the stderr capturer:
1347//   CaptureStdout     - starts capturing stdout.
1348//   GetCapturedStdout - stops capturing stdout and returns the captured string.
1349//   CaptureStderr     - starts capturing stderr.
1350//   GetCapturedStderr - stops capturing stderr and returns the captured string.
1351//
1352GTEST_API_ void CaptureStdout();
1353GTEST_API_ std::string GetCapturedStdout();
1354GTEST_API_ void CaptureStderr();
1355GTEST_API_ std::string GetCapturedStderr();
1356
1357#endif  // GTEST_HAS_STREAM_REDIRECTION
1358
1359
1360#if GTEST_HAS_DEATH_TEST
1361
1362const ::std::vector<testing::internal::string>& GetInjectableArgvs();
1363void SetInjectableArgvs(const ::std::vector<testing::internal::string>*
1364                             new_argvs);
1365
1366// A copy of all command line arguments.  Set by InitGoogleTest().
1367extern ::std::vector<testing::internal::string> g_argvs;
1368
1369#endif  // GTEST_HAS_DEATH_TEST
1370
1371// Defines synchronization primitives.
1372#if GTEST_IS_THREADSAFE
1373# if GTEST_HAS_PTHREAD
1374// Sleeps for (roughly) n milliseconds.  This function is only for testing
1375// Google Test's own constructs.  Don't use it in user tests, either
1376// directly or indirectly.
1377inline void SleepMilliseconds(int n) {
1378  const timespec time = {
1379    0,                  // 0 seconds.
1380    n * 1000L * 1000L,  // And n ms.
1381  };
1382  nanosleep(&time, NULL);
1383}
1384# endif  // GTEST_HAS_PTHREAD
1385
1386# if 0  // OS detection
1387# elif GTEST_HAS_PTHREAD
1388// Allows a controller thread to pause execution of newly created
1389// threads until notified.  Instances of this class must be created
1390// and destroyed in the controller thread.
1391//
1392// This class is only for testing Google Test's own constructs. Do not
1393// use it in user tests, either directly or indirectly.
1394class Notification {
1395 public:
1396  Notification() : notified_(false) {
1397    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
1398  }
1399  ~Notification() {
1400    pthread_mutex_destroy(&mutex_);
1401  }
1402
1403  // Notifies all threads created with this notification to start. Must
1404  // be called from the controller thread.
1405  void Notify() {
1406    pthread_mutex_lock(&mutex_);
1407    notified_ = true;
1408    pthread_mutex_unlock(&mutex_);
1409  }
1410
1411  // Blocks until the controller thread notifies. Must be called from a test
1412  // thread.
1413  void WaitForNotification() {
1414    for (;;) {
1415      pthread_mutex_lock(&mutex_);
1416      const bool notified = notified_;
1417      pthread_mutex_unlock(&mutex_);
1418      if (notified)
1419        break;
1420      SleepMilliseconds(10);
1421    }
1422  }
1423
1424 private:
1425  pthread_mutex_t mutex_;
1426  bool notified_;
1427
1428  GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1429};
1430
1431# elif GTEST_OS_WINDOWS
1432
1433GTEST_API_ void SleepMilliseconds(int n);
1434
1435// Provides leak-safe Windows kernel handle ownership.
1436// Used in death tests and in threading support.
1437class GTEST_API_ AutoHandle {
1438 public:
1439  // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
1440  // avoid including <windows.h> in this header file. Including <windows.h> is
1441  // undesirable because it defines a lot of symbols and macros that tend to
1442  // conflict with client code. This assumption is verified by
1443  // WindowsTypesTest.HANDLEIsVoidStar.
1444  typedef void* Handle;
1445  AutoHandle();
1446  explicit AutoHandle(Handle handle);
1447
1448  ~AutoHandle();
1449
1450  Handle Get() const;
1451  void Reset();
1452  void Reset(Handle handle);
1453
1454 private:
1455  // Returns true iff the handle is a valid handle object that can be closed.
1456  bool IsCloseable() const;
1457
1458  Handle handle_;
1459
1460  GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1461};
1462
1463// Allows a controller thread to pause execution of newly created
1464// threads until notified.  Instances of this class must be created
1465// and destroyed in the controller thread.
1466//
1467// This class is only for testing Google Test's own constructs. Do not
1468// use it in user tests, either directly or indirectly.
1469class GTEST_API_ Notification {
1470 public:
1471  Notification();
1472  void Notify();
1473  void WaitForNotification();
1474
1475 private:
1476  AutoHandle event_;
1477
1478  GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1479};
1480# endif  // OS detection
1481
1482// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
1483// defined, but we don't want to use MinGW's pthreads implementation, which
1484// has conformance problems with some versions of the POSIX standard.
1485# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1486
1487// As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
1488// Consequently, it cannot select a correct instantiation of ThreadWithParam
1489// in order to call its Run(). Introducing ThreadWithParamBase as a
1490// non-templated base class for ThreadWithParam allows us to bypass this
1491// problem.
1492class ThreadWithParamBase {
1493 public:
1494  virtual ~ThreadWithParamBase() {}
1495  virtual void Run() = 0;
1496};
1497
1498// pthread_create() accepts a pointer to a function type with the C linkage.
1499// According to the Standard (7.5/1), function types with different linkages
1500// are different even if they are otherwise identical.  Some compilers (for
1501// example, SunStudio) treat them as different types.  Since class methods
1502// cannot be defined with C-linkage we need to define a free C-function to
1503// pass into pthread_create().
1504extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
1505  static_cast<ThreadWithParamBase*>(thread)->Run();
1506  return NULL;
1507}
1508
1509// Helper class for testing Google Test's multi-threading constructs.
1510// To use it, write:
1511//
1512//   void ThreadFunc(int param) { /* Do things with param */ }
1513//   Notification thread_can_start;
1514//   ...
1515//   // The thread_can_start parameter is optional; you can supply NULL.
1516//   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
1517//   thread_can_start.Notify();
1518//
1519// These classes are only for testing Google Test's own constructs. Do
1520// not use them in user tests, either directly or indirectly.
1521template <typename T>
1522class ThreadWithParam : public ThreadWithParamBase {
1523 public:
1524  typedef void UserThreadFunc(T);
1525
1526  ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1527      : func_(func),
1528        param_(param),
1529        thread_can_start_(thread_can_start),
1530        finished_(false) {
1531    ThreadWithParamBase* const base = this;
1532    // The thread can be created only after all fields except thread_
1533    // have been initialized.
1534    GTEST_CHECK_POSIX_SUCCESS_(
1535        pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
1536  }
1537  ~ThreadWithParam() { Join(); }
1538
1539  void Join() {
1540    if (!finished_) {
1541      GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
1542      finished_ = true;
1543    }
1544  }
1545
1546  virtual void Run() {
1547    if (thread_can_start_ != NULL)
1548      thread_can_start_->WaitForNotification();
1549    func_(param_);
1550  }
1551
1552 private:
1553  UserThreadFunc* const func_;  // User-supplied thread function.
1554  const T param_;  // User-supplied parameter to the thread function.
1555  // When non-NULL, used to block execution until the controller thread
1556  // notifies.
1557  Notification* const thread_can_start_;
1558  bool finished_;  // true iff we know that the thread function has finished.
1559  pthread_t thread_;  // The native thread object.
1560
1561  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1562};
1563# endif  // GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1564
1565# if 0  // OS detection
1566# elif GTEST_OS_WINDOWS
1567
1568// Mutex implements mutex on Windows platforms.  It is used in conjunction
1569// with class MutexLock:
1570//
1571//   Mutex mutex;
1572//   ...
1573//   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the
1574//                            // end of the current scope.
1575//
1576// A static Mutex *must* be defined or declared using one of the following
1577// macros:
1578//   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
1579//   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
1580//
1581// (A non-static Mutex is defined/declared in the usual way).
1582class GTEST_API_ Mutex {
1583 public:
1584  enum MutexType { kStatic = 0, kDynamic = 1 };
1585  // We rely on kStaticMutex being 0 as it is to what the linker initializes
1586  // type_ in static mutexes.  critical_section_ will be initialized lazily
1587  // in ThreadSafeLazyInit().
1588  enum StaticConstructorSelector { kStaticMutex = 0 };
1589
1590  // This constructor intentionally does nothing.  It relies on type_ being
1591  // statically initialized to 0 (effectively setting it to kStatic) and on
1592  // ThreadSafeLazyInit() to lazily initialize the rest of the members.
1593  explicit Mutex(StaticConstructorSelector /*dummy*/) {}
1594
1595  Mutex();
1596  ~Mutex();
1597
1598  void Lock();
1599
1600  void Unlock();
1601
1602  // Does nothing if the current thread holds the mutex. Otherwise, crashes
1603  // with high probability.
1604  void AssertHeld();
1605
1606 private:
1607  // Initializes owner_thread_id_ and critical_section_ in static mutexes.
1608  void ThreadSafeLazyInit();
1609
1610  // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx,
1611  // we assume that 0 is an invalid value for thread IDs.
1612  unsigned int owner_thread_id_;
1613
1614  // For static mutexes, we rely on these members being initialized to zeros
1615  // by the linker.
1616  MutexType type_;
1617  long critical_section_init_phase_;  // NOLINT
1618  _RTL_CRITICAL_SECTION* critical_section_;
1619
1620  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1621};
1622
1623# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1624    extern ::testing::internal::Mutex mutex
1625
1626# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1627    ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
1628
1629// We cannot name this class MutexLock because the ctor declaration would
1630// conflict with a macro named MutexLock, which is defined on some
1631// platforms. That macro is used as a defensive measure to prevent against
1632// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1633// "MutexLock l(&mu)".  Hence the typedef trick below.
1634class GTestMutexLock {
1635 public:
1636  explicit GTestMutexLock(Mutex* mutex)
1637      : mutex_(mutex) { mutex_->Lock(); }
1638
1639  ~GTestMutexLock() { mutex_->Unlock(); }
1640
1641 private:
1642  Mutex* const mutex_;
1643
1644  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1645};
1646
1647typedef GTestMutexLock MutexLock;
1648
1649// Base class for ValueHolder<T>.  Allows a caller to hold and delete a value
1650// without knowing its type.
1651class ThreadLocalValueHolderBase {
1652 public:
1653  virtual ~ThreadLocalValueHolderBase() {}
1654};
1655
1656// Provides a way for a thread to send notifications to a ThreadLocal
1657// regardless of its parameter type.
1658class ThreadLocalBase {
1659 public:
1660  // Creates a new ValueHolder<T> object holding a default value passed to
1661  // this ThreadLocal<T>'s constructor and returns it.  It is the caller's
1662  // responsibility not to call this when the ThreadLocal<T> instance already
1663  // has a value on the current thread.
1664  virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
1665
1666 protected:
1667  ThreadLocalBase() {}
1668  virtual ~ThreadLocalBase() {}
1669
1670 private:
1671  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
1672};
1673
1674// Maps a thread to a set of ThreadLocals that have values instantiated on that
1675// thread and notifies them when the thread exits.  A ThreadLocal instance is
1676// expected to persist until all threads it has values on have terminated.
1677class GTEST_API_ ThreadLocalRegistry {
1678 public:
1679  // Registers thread_local_instance as having value on the current thread.
1680  // Returns a value that can be used to identify the thread from other threads.
1681  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
1682      const ThreadLocalBase* thread_local_instance);
1683
1684  // Invoked when a ThreadLocal instance is destroyed.
1685  static void OnThreadLocalDestroyed(
1686      const ThreadLocalBase* thread_local_instance);
1687};
1688
1689class GTEST_API_ ThreadWithParamBase {
1690 public:
1691  void Join();
1692
1693 protected:
1694  class Runnable {
1695   public:
1696    virtual ~Runnable() {}
1697    virtual void Run() = 0;
1698  };
1699
1700  ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
1701  virtual ~ThreadWithParamBase();
1702
1703 private:
1704  AutoHandle thread_;
1705};
1706
1707// Helper class for testing Google Test's multi-threading constructs.
1708template <typename T>
1709class ThreadWithParam : public ThreadWithParamBase {
1710 public:
1711  typedef void UserThreadFunc(T);
1712
1713  ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1714      : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
1715  }
1716  virtual ~ThreadWithParam() {}
1717
1718 private:
1719  class RunnableImpl : public Runnable {
1720   public:
1721    RunnableImpl(UserThreadFunc* func, T param)
1722        : func_(func),
1723          param_(param) {
1724    }
1725    virtual ~RunnableImpl() {}
1726    virtual void Run() {
1727      func_(param_);
1728    }
1729
1730   private:
1731    UserThreadFunc* const func_;
1732    const T param_;
1733
1734    GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
1735  };
1736
1737  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1738};
1739
1740// Implements thread-local storage on Windows systems.
1741//
1742//   // Thread 1
1743//   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.
1744//
1745//   // Thread 2
1746//   tl.set(150);  // Changes the value for thread 2 only.
1747//   EXPECT_EQ(150, tl.get());
1748//
1749//   // Thread 1
1750//   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.
1751//   tl.set(200);
1752//   EXPECT_EQ(200, tl.get());
1753//
1754// The template type argument T must have a public copy constructor.
1755// In addition, the default ThreadLocal constructor requires T to have
1756// a public default constructor.
1757//
1758// The users of a TheadLocal instance have to make sure that all but one
1759// threads (including the main one) using that instance have exited before
1760// destroying it. Otherwise, the per-thread objects managed for them by the
1761// ThreadLocal instance are not guaranteed to be destroyed on all platforms.
1762//
1763// Google Test only uses global ThreadLocal objects.  That means they
1764// will die after main() has returned.  Therefore, no per-thread
1765// object managed by Google Test will be leaked as long as all threads
1766// using Google Test have exited when main() returns.
1767template <typename T>
1768class ThreadLocal : public ThreadLocalBase {
1769 public:
1770  ThreadLocal() : default_() {}
1771  explicit ThreadLocal(const T& value) : default_(value) {}
1772
1773  ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
1774
1775  T* pointer() { return GetOrCreateValue(); }
1776  const T* pointer() const { return GetOrCreateValue(); }
1777  const T& get() const { return *pointer(); }
1778  void set(const T& value) { *pointer() = value; }
1779
1780 private:
1781  // Holds a value of T.  Can be deleted via its base class without the caller
1782  // knowing the type of T.
1783  class ValueHolder : public ThreadLocalValueHolderBase {
1784   public:
1785    explicit ValueHolder(const T& value) : value_(value) {}
1786
1787    T* pointer() { return &value_; }
1788
1789   private:
1790    T value_;
1791    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1792  };
1793
1794
1795  T* GetOrCreateValue() const {
1796    return static_cast<ValueHolder*>(
1797        ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
1798  }
1799
1800  virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
1801    return new ValueHolder(default_);
1802  }
1803
1804  const T default_;  // The default value for each thread.
1805
1806  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1807};
1808
1809# elif GTEST_HAS_PTHREAD
1810
1811// MutexBase and Mutex implement mutex on pthreads-based platforms.
1812class MutexBase {
1813 public:
1814  // Acquires this mutex.
1815  void Lock() {
1816    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
1817    owner_ = pthread_self();
1818    has_owner_ = true;
1819  }
1820
1821  // Releases this mutex.
1822  void Unlock() {
1823    // Since the lock is being released the owner_ field should no longer be
1824    // considered valid. We don't protect writing to has_owner_ here, as it's
1825    // the caller's responsibility to ensure that the current thread holds the
1826    // mutex when this is called.
1827    has_owner_ = false;
1828    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
1829  }
1830
1831  // Does nothing if the current thread holds the mutex. Otherwise, crashes
1832  // with high probability.
1833  void AssertHeld() const {
1834    GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
1835        << "The current thread is not holding the mutex @" << this;
1836  }
1837
1838  // A static mutex may be used before main() is entered.  It may even
1839  // be used before the dynamic initialization stage.  Therefore we
1840  // must be able to initialize a static mutex object at link time.
1841  // This means MutexBase has to be a POD and its member variables
1842  // have to be public.
1843 public:
1844  pthread_mutex_t mutex_;  // The underlying pthread mutex.
1845  // has_owner_ indicates whether the owner_ field below contains a valid thread
1846  // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
1847  // accesses to the owner_ field should be protected by a check of this field.
1848  // An alternative might be to memset() owner_ to all zeros, but there's no
1849  // guarantee that a zero'd pthread_t is necessarily invalid or even different
1850  // from pthread_self().
1851  bool has_owner_;
1852  pthread_t owner_;  // The thread holding the mutex.
1853};
1854
1855// Forward-declares a static mutex.
1856#  define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1857     extern ::testing::internal::MutexBase mutex
1858
1859// Defines and statically (i.e. at link time) initializes a static mutex.
1860// The initialization list here does not explicitly initialize each field,
1861// instead relying on default initialization for the unspecified fields. In
1862// particular, the owner_ field (a pthread_t) is not explicitly initialized.
1863// This allows initialization to work whether pthread_t is a scalar or struct.
1864// The flag -Wmissing-field-initializers must not be specified for this to work.
1865#  define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1866     ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false }
1867
1868// The Mutex class can only be used for mutexes created at runtime. It
1869// shares its API with MutexBase otherwise.
1870class Mutex : public MutexBase {
1871 public:
1872  Mutex() {
1873    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
1874    has_owner_ = false;
1875  }
1876  ~Mutex() {
1877    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
1878  }
1879
1880 private:
1881  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1882};
1883
1884// We cannot name this class MutexLock because the ctor declaration would
1885// conflict with a macro named MutexLock, which is defined on some
1886// platforms. That macro is used as a defensive measure to prevent against
1887// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1888// "MutexLock l(&mu)".  Hence the typedef trick below.
1889class GTestMutexLock {
1890 public:
1891  explicit GTestMutexLock(MutexBase* mutex)
1892      : mutex_(mutex) { mutex_->Lock(); }
1893
1894  ~GTestMutexLock() { mutex_->Unlock(); }
1895
1896 private:
1897  MutexBase* const mutex_;
1898
1899  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1900};
1901
1902typedef GTestMutexLock MutexLock;
1903
1904// Helpers for ThreadLocal.
1905
1906// pthread_key_create() requires DeleteThreadLocalValue() to have
1907// C-linkage.  Therefore it cannot be templatized to access
1908// ThreadLocal<T>.  Hence the need for class
1909// ThreadLocalValueHolderBase.
1910class ThreadLocalValueHolderBase {
1911 public:
1912  virtual ~ThreadLocalValueHolderBase() {}
1913};
1914
1915// Called by pthread to delete thread-local data stored by
1916// pthread_setspecific().
1917extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
1918  delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
1919}
1920
1921// Implements thread-local storage on pthreads-based systems.
1922template <typename T>
1923class ThreadLocal {
1924 public:
1925  ThreadLocal() : key_(CreateKey()),
1926                  default_() {}
1927  explicit ThreadLocal(const T& value) : key_(CreateKey()),
1928                                         default_(value) {}
1929
1930  ~ThreadLocal() {
1931    // Destroys the managed object for the current thread, if any.
1932    DeleteThreadLocalValue(pthread_getspecific(key_));
1933
1934    // Releases resources associated with the key.  This will *not*
1935    // delete managed objects for other threads.
1936    GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
1937  }
1938
1939  T* pointer() { return GetOrCreateValue(); }
1940  const T* pointer() const { return GetOrCreateValue(); }
1941  const T& get() const { return *pointer(); }
1942  void set(const T& value) { *pointer() = value; }
1943
1944 private:
1945  // Holds a value of type T.
1946  class ValueHolder : public ThreadLocalValueHolderBase {
1947   public:
1948    explicit ValueHolder(const T& value) : value_(value) {}
1949
1950    T* pointer() { return &value_; }
1951
1952   private:
1953    T value_;
1954    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1955  };
1956
1957  static pthread_key_t CreateKey() {
1958    pthread_key_t key;
1959    // When a thread exits, DeleteThreadLocalValue() will be called on
1960    // the object managed for that thread.
1961    GTEST_CHECK_POSIX_SUCCESS_(
1962        pthread_key_create(&key, &DeleteThreadLocalValue));
1963    return key;
1964  }
1965
1966  T* GetOrCreateValue() const {
1967    ThreadLocalValueHolderBase* const holder =
1968        static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
1969    if (holder != NULL) {
1970      return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
1971    }
1972
1973    ValueHolder* const new_holder = new ValueHolder(default_);
1974    ThreadLocalValueHolderBase* const holder_base = new_holder;
1975    GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
1976    return new_holder->pointer();
1977  }
1978
1979  // A key pthreads uses for looking up per-thread values.
1980  const pthread_key_t key_;
1981  const T default_;  // The default value for each thread.
1982
1983  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1984};
1985
1986# endif  // OS detection
1987
1988#else  // GTEST_IS_THREADSAFE
1989
1990// A dummy implementation of synchronization primitives (mutex, lock,
1991// and thread-local variable).  Necessary for compiling Google Test where
1992// mutex is not supported - using Google Test in multiple threads is not
1993// supported on such platforms.
1994
1995class Mutex {
1996 public:
1997  Mutex() {}
1998  void Lock() {}
1999  void Unlock() {}
2000  void AssertHeld() const {}
2001};
2002
2003# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2004  extern ::testing::internal::Mutex mutex
2005
2006# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
2007
2008// We cannot name this class MutexLock because the ctor declaration would
2009// conflict with a macro named MutexLock, which is defined on some
2010// platforms. That macro is used as a defensive measure to prevent against
2011// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2012// "MutexLock l(&mu)".  Hence the typedef trick below.
2013class GTestMutexLock {
2014 public:
2015  explicit GTestMutexLock(Mutex*) {}  // NOLINT
2016};
2017
2018typedef GTestMutexLock MutexLock;
2019
2020template <typename T>
2021class ThreadLocal {
2022 public:
2023  ThreadLocal() : value_() {}
2024  explicit ThreadLocal(const T& value) : value_(value) {}
2025  T* pointer() { return &value_; }
2026  const T* pointer() const { return &value_; }
2027  const T& get() const { return value_; }
2028  void set(const T& value) { value_ = value; }
2029 private:
2030  T value_;
2031};
2032
2033#endif  // GTEST_IS_THREADSAFE
2034
2035// Returns the number of threads running in the process, or 0 to indicate that
2036// we cannot detect it.
2037GTEST_API_ size_t GetThreadCount();
2038
2039// Passing non-POD classes through ellipsis (...) crashes the ARM
2040// compiler and generates a warning in Sun Studio.  The Nokia Symbian
2041// and the IBM XL C/C++ compiler try to instantiate a copy constructor
2042// for objects passed through ellipsis (...), failing for uncopyable
2043// objects.  We define this to ensure that only POD is passed through
2044// ellipsis on these systems.
2045#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC)
2046// We lose support for NULL detection where the compiler doesn't like
2047// passing non-POD classes through ellipsis (...).
2048# define GTEST_ELLIPSIS_NEEDS_POD_ 1
2049#else
2050# define GTEST_CAN_COMPARE_NULL 1
2051#endif
2052
2053// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
2054// const T& and const T* in a function template.  These compilers
2055// _can_ decide between class template specializations for T and T*,
2056// so a tr1::type_traits-like is_pointer works.
2057#if defined(__SYMBIAN32__) || defined(__IBMCPP__)
2058# define GTEST_NEEDS_IS_POINTER_ 1
2059#endif
2060
2061template <bool bool_value>
2062struct bool_constant {
2063  typedef bool_constant<bool_value> type;
2064  static const bool value = bool_value;
2065};
2066template <bool bool_value> const bool bool_constant<bool_value>::value;
2067
2068typedef bool_constant<false> false_type;
2069typedef bool_constant<true> true_type;
2070
2071template <typename T>
2072struct is_pointer : public false_type {};
2073
2074template <typename T>
2075struct is_pointer<T*> : public true_type {};
2076
2077template <typename Iterator>
2078struct IteratorTraits {
2079  typedef typename Iterator::value_type value_type;
2080};
2081
2082template <typename T>
2083struct IteratorTraits<T*> {
2084  typedef T value_type;
2085};
2086
2087template <typename T>
2088struct IteratorTraits<const T*> {
2089  typedef T value_type;
2090};
2091
2092#if GTEST_OS_WINDOWS
2093# define GTEST_PATH_SEP_ "\\"
2094# define GTEST_HAS_ALT_PATH_SEP_ 1
2095// The biggest signed integer type the compiler supports.
2096typedef __int64 BiggestInt;
2097#else
2098# define GTEST_PATH_SEP_ "/"
2099# define GTEST_HAS_ALT_PATH_SEP_ 0
2100typedef long long BiggestInt;  // NOLINT
2101#endif  // GTEST_OS_WINDOWS
2102
2103// Utilities for char.
2104
2105// isspace(int ch) and friends accept an unsigned char or EOF.  char
2106// may be signed, depending on the compiler (or compiler flags).
2107// Therefore we need to cast a char to unsigned char before calling
2108// isspace(), etc.
2109
2110inline bool IsAlpha(char ch) {
2111  return isalpha(static_cast<unsigned char>(ch)) != 0;
2112}
2113inline bool IsAlNum(char ch) {
2114  return isalnum(static_cast<unsigned char>(ch)) != 0;
2115}
2116inline bool IsDigit(char ch) {
2117  return isdigit(static_cast<unsigned char>(ch)) != 0;
2118}
2119inline bool IsLower(char ch) {
2120  return islower(static_cast<unsigned char>(ch)) != 0;
2121}
2122inline bool IsSpace(char ch) {
2123  return isspace(static_cast<unsigned char>(ch)) != 0;
2124}
2125inline bool IsUpper(char ch) {
2126  return isupper(static_cast<unsigned char>(ch)) != 0;
2127}
2128inline bool IsXDigit(char ch) {
2129  return isxdigit(static_cast<unsigned char>(ch)) != 0;
2130}
2131inline bool IsXDigit(wchar_t ch) {
2132  const unsigned char low_byte = static_cast<unsigned char>(ch);
2133  return ch == low_byte && isxdigit(low_byte) != 0;
2134}
2135
2136inline char ToLower(char ch) {
2137  return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
2138}
2139inline char ToUpper(char ch) {
2140  return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
2141}
2142
2143// The testing::internal::posix namespace holds wrappers for common
2144// POSIX functions.  These wrappers hide the differences between
2145// Windows/MSVC and POSIX systems.  Since some compilers define these
2146// standard functions as macros, the wrapper cannot have the same name
2147// as the wrapped function.
2148
2149namespace posix {
2150
2151// Functions with a different name on Windows.
2152
2153#if GTEST_OS_WINDOWS
2154
2155typedef struct _stat StatStruct;
2156
2157# ifdef __BORLANDC__
2158inline int IsATTY(int fd) { return isatty(fd); }
2159inline int StrCaseCmp(const char* s1, const char* s2) {
2160  return stricmp(s1, s2);
2161}
2162inline char* StrDup(const char* src) { return strdup(src); }
2163# else  // !__BORLANDC__
2164#  if GTEST_OS_WINDOWS_MOBILE
2165inline int IsATTY(int /* fd */) { return 0; }
2166#  else
2167inline int IsATTY(int fd) { return _isatty(fd); }
2168#  endif  // GTEST_OS_WINDOWS_MOBILE
2169inline int StrCaseCmp(const char* s1, const char* s2) {
2170  return _stricmp(s1, s2);
2171}
2172inline char* StrDup(const char* src) { return _strdup(src); }
2173# endif  // __BORLANDC__
2174
2175# if GTEST_OS_WINDOWS_MOBILE
2176inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
2177// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
2178// time and thus not defined there.
2179# else
2180inline int FileNo(FILE* file) { return _fileno(file); }
2181inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
2182inline int RmDir(const char* dir) { return _rmdir(dir); }
2183inline bool IsDir(const StatStruct& st) {
2184  return (_S_IFDIR & st.st_mode) != 0;
2185}
2186# endif  // GTEST_OS_WINDOWS_MOBILE
2187
2188#else
2189
2190typedef struct stat StatStruct;
2191
2192inline int FileNo(FILE* file) { return fileno(file); }
2193inline int IsATTY(int fd) { return isatty(fd); }
2194inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
2195inline int StrCaseCmp(const char* s1, const char* s2) {
2196  return strcasecmp(s1, s2);
2197}
2198inline char* StrDup(const char* src) { return strdup(src); }
2199inline int RmDir(const char* dir) { return rmdir(dir); }
2200inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2201
2202#endif  // GTEST_OS_WINDOWS
2203
2204// Functions deprecated by MSVC 8.0.
2205
2206#ifdef _MSC_VER
2207// Temporarily disable warning 4996 (deprecated function).
2208# pragma warning(push)
2209# pragma warning(disable:4996)
2210#endif
2211
2212inline const char* StrNCpy(char* dest, const char* src, size_t n) {
2213  return strncpy(dest, src, n);
2214}
2215
2216// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
2217// StrError() aren't needed on Windows CE at this time and thus not
2218// defined there.
2219
2220#if !GTEST_OS_WINDOWS_MOBILE
2221inline int ChDir(const char* dir) { return chdir(dir); }
2222#endif
2223inline FILE* FOpen(const char* path, const char* mode) {
2224  return fopen(path, mode);
2225}
2226#if !GTEST_OS_WINDOWS_MOBILE
2227inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
2228  return freopen(path, mode, stream);
2229}
2230inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
2231#endif
2232inline int FClose(FILE* fp) { return fclose(fp); }
2233#if !GTEST_OS_WINDOWS_MOBILE
2234inline int Read(int fd, void* buf, unsigned int count) {
2235  return static_cast<int>(read(fd, buf, count));
2236}
2237inline int Write(int fd, const void* buf, unsigned int count) {
2238  return static_cast<int>(write(fd, buf, count));
2239}
2240inline int Close(int fd) { return close(fd); }
2241inline const char* StrError(int errnum) { return strerror(errnum); }
2242#endif
2243inline const char* GetEnv(const char* name) {
2244#if GTEST_OS_WINDOWS_MOBILE
2245  // We are on Windows CE, which has no environment variables.
2246  return NULL;
2247#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
2248  // Environment variables which we programmatically clear will be set to the
2249  // empty string rather than unset (NULL).  Handle that case.
2250  const char* const env = getenv(name);
2251  return (env != NULL && env[0] != '\0') ? env : NULL;
2252#else
2253  return getenv(name);
2254#endif
2255}
2256
2257#ifdef _MSC_VER
2258# pragma warning(pop)  // Restores the warning state.
2259#endif
2260
2261#if GTEST_OS_WINDOWS_MOBILE
2262// Windows CE has no C library. The abort() function is used in
2263// several places in Google Test. This implementation provides a reasonable
2264// imitation of standard behaviour.
2265void Abort();
2266#else
2267inline void Abort() { abort(); }
2268#endif  // GTEST_OS_WINDOWS_MOBILE
2269
2270}  // namespace posix
2271
2272// MSVC "deprecates" snprintf and issues warnings wherever it is used.  In
2273// order to avoid these warnings, we need to use _snprintf or _snprintf_s on
2274// MSVC-based platforms.  We map the GTEST_SNPRINTF_ macro to the appropriate
2275// function in order to achieve that.  We use macro definition here because
2276// snprintf is a variadic function.
2277#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
2278// MSVC 2005 and above support variadic macros.
2279# define GTEST_SNPRINTF_(buffer, size, format, ...) \
2280     _snprintf_s(buffer, size, size, format, __VA_ARGS__)
2281#elif defined(_MSC_VER)
2282// Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't
2283// complain about _snprintf.
2284# define GTEST_SNPRINTF_ _snprintf
2285#else
2286# define GTEST_SNPRINTF_ snprintf
2287#endif
2288
2289// The maximum number a BiggestInt can represent.  This definition
2290// works no matter BiggestInt is represented in one's complement or
2291// two's complement.
2292//
2293// We cannot rely on numeric_limits in STL, as __int64 and long long
2294// are not part of standard C++ and numeric_limits doesn't need to be
2295// defined for them.
2296const BiggestInt kMaxBiggestInt =
2297    ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
2298
2299// This template class serves as a compile-time function from size to
2300// type.  It maps a size in bytes to a primitive type with that
2301// size. e.g.
2302//
2303//   TypeWithSize<4>::UInt
2304//
2305// is typedef-ed to be unsigned int (unsigned integer made up of 4
2306// bytes).
2307//
2308// Such functionality should belong to STL, but I cannot find it
2309// there.
2310//
2311// Google Test uses this class in the implementation of floating-point
2312// comparison.
2313//
2314// For now it only handles UInt (unsigned int) as that's all Google Test
2315// needs.  Other types can be easily added in the future if need
2316// arises.
2317template <size_t size>
2318class TypeWithSize {
2319 public:
2320  // This prevents the user from using TypeWithSize<N> with incorrect
2321  // values of N.
2322  typedef void UInt;
2323};
2324
2325// The specialization for size 4.
2326template <>
2327class TypeWithSize<4> {
2328 public:
2329  // unsigned int has size 4 in both gcc and MSVC.
2330  //
2331  // As base/basictypes.h doesn't compile on Windows, we cannot use
2332  // uint32, uint64, and etc here.
2333  typedef int Int;
2334  typedef unsigned int UInt;
2335};
2336
2337// The specialization for size 8.
2338template <>
2339class TypeWithSize<8> {
2340 public:
2341#if GTEST_OS_WINDOWS
2342  typedef __int64 Int;
2343  typedef unsigned __int64 UInt;
2344#else
2345  typedef long long Int;  // NOLINT
2346  typedef unsigned long long UInt;  // NOLINT
2347#endif  // GTEST_OS_WINDOWS
2348};
2349
2350// Integer types of known sizes.
2351typedef TypeWithSize<4>::Int Int32;
2352typedef TypeWithSize<4>::UInt UInt32;
2353typedef TypeWithSize<8>::Int Int64;
2354typedef TypeWithSize<8>::UInt UInt64;
2355typedef TypeWithSize<8>::Int TimeInMillis;  // Represents time in milliseconds.
2356
2357// Utilities for command line flags and environment variables.
2358
2359// Macro for referencing flags.
2360#define GTEST_FLAG(name) FLAGS_gtest_##name
2361
2362// Macros for declaring flags.
2363#define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
2364#define GTEST_DECLARE_int32_(name) \
2365    GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
2366#define GTEST_DECLARE_string_(name) \
2367    GTEST_API_ extern ::std::string GTEST_FLAG(name)
2368
2369// Macros for defining flags.
2370#define GTEST_DEFINE_bool_(name, default_val, doc) \
2371    GTEST_API_ bool GTEST_FLAG(name) = (default_val)
2372#define GTEST_DEFINE_int32_(name, default_val, doc) \
2373    GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
2374#define GTEST_DEFINE_string_(name, default_val, doc) \
2375    GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
2376
2377// Thread annotations
2378#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
2379#define GTEST_LOCK_EXCLUDED_(locks)
2380
2381// Parses 'str' for a 32-bit signed integer.  If successful, writes the result
2382// to *value and returns true; otherwise leaves *value unchanged and returns
2383// false.
2384// TODO(chandlerc): Find a better way to refactor flag and environment parsing
2385// out of both gtest-port.cc and gtest.cc to avoid exporting this utility
2386// function.
2387bool ParseInt32(const Message& src_text, const char* str, Int32* value);
2388
2389// Parses a bool/Int32/string from the environment variable
2390// corresponding to the given Google Test flag.
2391bool BoolFromGTestEnv(const char* flag, bool default_val);
2392GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
2393const char* StringFromGTestEnv(const char* flag, const char* default_val);
2394
2395}  // namespace internal
2396}  // namespace testing
2397
2398#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
2399