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