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