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