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 /*
987 #ifdef _MSC_VER
988 # if GTEST_LINKED_AS_SHARED_LIBRARY
989 #  define GTEST_API_ __declspec(dllimport)
990 # elif GTEST_CREATE_SHARED_LIBRARY
991 #  define GTEST_API_ __declspec(dllexport)
992 # endif
993 #elif __GNUC__ >= 4 || defined(__clang__)
994 # define GTEST_API_ __attribute__((visibility ("default")))
995 #endif  // _MSC_VER
996 */
997 
998 #endif  // GTEST_API_
999 
1000 #ifndef GTEST_API_
1001 # define GTEST_API_
1002 #endif  // GTEST_API_
1003 
1004 #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
1005 # define GTEST_DEFAULT_DEATH_TEST_STYLE  "fast"
1006 #endif  // GTEST_DEFAULT_DEATH_TEST_STYLE
1007 
1008 #ifdef __GNUC__
1009 // Ask the compiler to never inline a given function.
1010 # define GTEST_NO_INLINE_ __attribute__((noinline))
1011 #else
1012 # define GTEST_NO_INLINE_
1013 #endif
1014 
1015 // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
1016 #if !defined(GTEST_HAS_CXXABI_H_)
1017 # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
1018 #  define GTEST_HAS_CXXABI_H_ 1
1019 # else
1020 #  define GTEST_HAS_CXXABI_H_ 0
1021 # endif
1022 #endif
1023 
1024 // A function level attribute to disable checking for use of uninitialized
1025 // memory when built with MemorySanitizer.
1026 #if defined(__clang__)
1027 # if __has_feature(memory_sanitizer)
1028 #  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
1029        __attribute__((no_sanitize_memory))
1030 # else
1031 #  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1032 # endif  // __has_feature(memory_sanitizer)
1033 #else
1034 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1035 #endif  // __clang__
1036 
1037 // A function level attribute to disable AddressSanitizer instrumentation.
1038 #if defined(__clang__)
1039 # if __has_feature(address_sanitizer)
1040 #  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
1041        __attribute__((no_sanitize_address))
1042 # else
1043 #  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1044 # endif  // __has_feature(address_sanitizer)
1045 #else
1046 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1047 #endif  // __clang__
1048 
1049 // A function level attribute to disable ThreadSanitizer instrumentation.
1050 #if defined(__clang__)
1051 # if __has_feature(thread_sanitizer)
1052 #  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
1053        __attribute__((no_sanitize_thread))
1054 # else
1055 #  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1056 # endif  // __has_feature(thread_sanitizer)
1057 #else
1058 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1059 #endif  // __clang__
1060 
1061 namespace testing {
1062 
1063 class Message;
1064 
1065 #if defined(GTEST_TUPLE_NAMESPACE_)
1066 // Import tuple and friends into the ::testing namespace.
1067 // It is part of our interface, having them in ::testing allows us to change
1068 // their types as needed.
1069 using GTEST_TUPLE_NAMESPACE_::get;
1070 using GTEST_TUPLE_NAMESPACE_::make_tuple;
1071 using GTEST_TUPLE_NAMESPACE_::tuple;
1072 using GTEST_TUPLE_NAMESPACE_::tuple_size;
1073 using GTEST_TUPLE_NAMESPACE_::tuple_element;
1074 #endif  // defined(GTEST_TUPLE_NAMESPACE_)
1075 
1076 namespace internal {
1077 
1078 // A secret type that Google Test users don't know about.  It has no
1079 // definition on purpose.  Therefore it's impossible to create a
1080 // Secret object, which is what we want.
1081 class Secret;
1082 
1083 // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
1084 // expression is true. For example, you could use it to verify the
1085 // size of a static array:
1086 //
1087 //   GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
1088 //                         names_incorrect_size);
1089 //
1090 // or to make sure a struct is smaller than a certain size:
1091 //
1092 //   GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
1093 //
1094 // The second argument to the macro is the name of the variable. If
1095 // the expression is false, most compilers will issue a warning/error
1096 // containing the name of the variable.
1097 
1098 #if GTEST_LANG_CXX11
1099 # define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
1100 #else  // !GTEST_LANG_CXX11
1101 template <bool>
1102   struct CompileAssert {
1103 };
1104 
1105 # define GTEST_COMPILE_ASSERT_(expr, msg) \
1106   typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
1107       msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
1108 #endif  // !GTEST_LANG_CXX11
1109 
1110 // Implementation details of GTEST_COMPILE_ASSERT_:
1111 //
1112 // (In C++11, we simply use static_assert instead of the following)
1113 //
1114 // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
1115 //   elements (and thus is invalid) when the expression is false.
1116 //
1117 // - The simpler definition
1118 //
1119 //    #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
1120 //
1121 //   does not work, as gcc supports variable-length arrays whose sizes
1122 //   are determined at run-time (this is gcc's extension and not part
1123 //   of the C++ standard).  As a result, gcc fails to reject the
1124 //   following code with the simple definition:
1125 //
1126 //     int foo;
1127 //     GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
1128 //                                      // not a compile-time constant.
1129 //
1130 // - By using the type CompileAssert<(bool(expr))>, we ensures that
1131 //   expr is a compile-time constant.  (Template arguments must be
1132 //   determined at compile-time.)
1133 //
1134 // - The outter parentheses in CompileAssert<(bool(expr))> are necessary
1135 //   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
1136 //
1137 //     CompileAssert<bool(expr)>
1138 //
1139 //   instead, these compilers will refuse to compile
1140 //
1141 //     GTEST_COMPILE_ASSERT_(5 > 0, some_message);
1142 //
1143 //   (They seem to think the ">" in "5 > 0" marks the end of the
1144 //   template argument list.)
1145 //
1146 // - The array size is (bool(expr) ? 1 : -1), instead of simply
1147 //
1148 //     ((expr) ? 1 : -1).
1149 //
1150 //   This is to avoid running into a bug in MS VC 7.1, which
1151 //   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
1152 
1153 // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
1154 //
1155 // This template is declared, but intentionally undefined.
1156 template <typename T1, typename T2>
1157 struct StaticAssertTypeEqHelper;
1158 
1159 template <typename T>
1160 struct StaticAssertTypeEqHelper<T, T> {
1161   enum { value = true };
1162 };
1163 
1164 // Same as std::is_same<>.
1165 template <typename T, typename U>
1166 struct IsSame {
1167   enum { value = false };
1168 };
1169 template <typename T>
1170 struct IsSame<T, T> {
1171   enum { value = true };
1172 };
1173 
1174 // Evaluates to the number of elements in 'array'.
1175 #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
1176 
1177 #if GTEST_HAS_GLOBAL_STRING
1178 typedef ::string string;
1179 #else
1180 typedef ::std::string string;
1181 #endif  // GTEST_HAS_GLOBAL_STRING
1182 
1183 #if GTEST_HAS_GLOBAL_WSTRING
1184 typedef ::wstring wstring;
1185 #elif GTEST_HAS_STD_WSTRING
1186 typedef ::std::wstring wstring;
1187 #endif  // GTEST_HAS_GLOBAL_WSTRING
1188 
1189 // A helper for suppressing warnings on constant condition.  It just
1190 // returns 'condition'.
1191 GTEST_API_ bool IsTrue(bool condition);
1192 
1193 // Defines scoped_ptr.
1194 
1195 // This implementation of scoped_ptr is PARTIAL - it only contains
1196 // enough stuff to satisfy Google Test's need.
1197 template <typename T>
1198 class scoped_ptr {
1199  public:
1200   typedef T element_type;
1201 
1202   explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
1203   ~scoped_ptr() { reset(); }
1204 
1205   T& operator*() const { return *ptr_; }
1206   T* operator->() const { return ptr_; }
1207   T* get() const { return ptr_; }
1208 
1209   T* release() {
1210     T* const ptr = ptr_;
1211     ptr_ = NULL;
1212     return ptr;
1213   }
1214 
1215   void reset(T* p = NULL) {
1216     if (p != ptr_) {
1217       if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
1218         delete ptr_;
1219       }
1220       ptr_ = p;
1221     }
1222   }
1223 
1224   friend void swap(scoped_ptr& a, scoped_ptr& b) {
1225     using std::swap;
1226     swap(a.ptr_, b.ptr_);
1227   }
1228 
1229  private:
1230   T* ptr_;
1231 
1232   GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
1233 };
1234 
1235 // Defines RE.
1236 
1237 #if GTEST_USES_PCRE
1238 // if used, PCRE is injected by custom/gtest-port.h
1239 #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
1240 
1241 // A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
1242 // Regular Expression syntax.
1243 class GTEST_API_ RE {
1244  public:
1245   // A copy constructor is required by the Standard to initialize object
1246   // references from r-values.
1247   RE(const RE& other) { Init(other.pattern()); }
1248 
1249   // Constructs an RE from a string.
1250   RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
1251 
1252 # if GTEST_HAS_GLOBAL_STRING
1253 
1254   RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
1255 
1256 # endif  // GTEST_HAS_GLOBAL_STRING
1257 
1258   RE(const char* regex) { Init(regex); }  // NOLINT
1259   ~RE();
1260 
1261   // Returns the string representation of the regex.
1262   const char* pattern() const { return pattern_; }
1263 
1264   // FullMatch(str, re) returns true iff regular expression re matches
1265   // the entire str.
1266   // PartialMatch(str, re) returns true iff regular expression re
1267   // matches a substring of str (including str itself).
1268   //
1269   // FIXME: make FullMatch() and PartialMatch() work
1270   // when str contains NUL characters.
1271   static bool FullMatch(const ::std::string& str, const RE& re) {
1272     return FullMatch(str.c_str(), re);
1273   }
1274   static bool PartialMatch(const ::std::string& str, const RE& re) {
1275     return PartialMatch(str.c_str(), re);
1276   }
1277 
1278 # if GTEST_HAS_GLOBAL_STRING
1279 
1280   static bool FullMatch(const ::string& str, const RE& re) {
1281     return FullMatch(str.c_str(), re);
1282   }
1283   static bool PartialMatch(const ::string& str, const RE& re) {
1284     return PartialMatch(str.c_str(), re);
1285   }
1286 
1287 # endif  // GTEST_HAS_GLOBAL_STRING
1288 
1289   static bool FullMatch(const char* str, const RE& re);
1290   static bool PartialMatch(const char* str, const RE& re);
1291 
1292  private:
1293   void Init(const char* regex);
1294 
1295   // We use a const char* instead of an std::string, as Google Test used to be
1296   // used where std::string is not available.  FIXME: change to
1297   // std::string.
1298   const char* pattern_;
1299   bool is_valid_;
1300 
1301 # if GTEST_USES_POSIX_RE
1302 
1303   regex_t full_regex_;     // For FullMatch().
1304   regex_t partial_regex_;  // For PartialMatch().
1305 
1306 # else  // GTEST_USES_SIMPLE_RE
1307 
1308   const char* full_pattern_;  // For FullMatch();
1309 
1310 # endif
1311 
1312   GTEST_DISALLOW_ASSIGN_(RE);
1313 };
1314 
1315 #endif  // GTEST_USES_PCRE
1316 
1317 // Formats a source file path and a line number as they would appear
1318 // in an error message from the compiler used to compile this code.
1319 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
1320 
1321 // Formats a file location for compiler-independent XML output.
1322 // Although this function is not platform dependent, we put it next to
1323 // FormatFileLocation in order to contrast the two functions.
1324 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
1325                                                                int line);
1326 
1327 // Defines logging utilities:
1328 //   GTEST_LOG_(severity) - logs messages at the specified severity level. The
1329 //                          message itself is streamed into the macro.
1330 //   LogToStderr()  - directs all log messages to stderr.
1331 //   FlushInfoLog() - flushes informational log messages.
1332 
1333 enum GTestLogSeverity {
1334   GTEST_INFO,
1335   GTEST_WARNING,
1336   GTEST_ERROR,
1337   GTEST_FATAL
1338 };
1339 
1340 // Formats log entry severity, provides a stream object for streaming the
1341 // log message, and terminates the message with a newline when going out of
1342 // scope.
1343 class GTEST_API_ GTestLog {
1344  public:
1345   GTestLog(GTestLogSeverity severity, const char* file, int line);
1346 
1347   // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1348   ~GTestLog();
1349 
1350   ::std::ostream& GetStream() { return ::std::cerr; }
1351 
1352  private:
1353   const GTestLogSeverity severity_;
1354 
1355   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
1356 };
1357 
1358 #if !defined(GTEST_LOG_)
1359 
1360 # define GTEST_LOG_(severity) \
1361     ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
1362                                   __FILE__, __LINE__).GetStream()
1363 
1364 inline void LogToStderr() {}
1365 inline void FlushInfoLog() { fflush(NULL); }
1366 
1367 #endif  // !defined(GTEST_LOG_)
1368 
1369 #if !defined(GTEST_CHECK_)
1370 // INTERNAL IMPLEMENTATION - DO NOT USE.
1371 //
1372 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
1373 // is not satisfied.
1374 //  Synopsys:
1375 //    GTEST_CHECK_(boolean_condition);
1376 //     or
1377 //    GTEST_CHECK_(boolean_condition) << "Additional message";
1378 //
1379 //    This checks the condition and if the condition is not satisfied
1380 //    it prints message about the condition violation, including the
1381 //    condition itself, plus additional message streamed into it, if any,
1382 //    and then it aborts the program. It aborts the program irrespective of
1383 //    whether it is built in the debug mode or not.
1384 # define GTEST_CHECK_(condition) \
1385     GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1386     if (::testing::internal::IsTrue(condition)) \
1387       ; \
1388     else \
1389       GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
1390 #endif  // !defined(GTEST_CHECK_)
1391 
1392 // An all-mode assert to verify that the given POSIX-style function
1393 // call returns 0 (indicating success).  Known limitation: this
1394 // doesn't expand to a balanced 'if' statement, so enclose the macro
1395 // in {} if you need to use it as the only statement in an 'if'
1396 // branch.
1397 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
1398   if (const int gtest_error = (posix_call)) \
1399     GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
1400                       << gtest_error
1401 
1402 // Adds reference to a type if it is not a reference type,
1403 // otherwise leaves it unchanged.  This is the same as
1404 // tr1::add_reference, which is not widely available yet.
1405 template <typename T>
1406 struct AddReference { typedef T& type; };  // NOLINT
1407 template <typename T>
1408 struct AddReference<T&> { typedef T& type; };  // NOLINT
1409 
1410 // A handy wrapper around AddReference that works when the argument T
1411 // depends on template parameters.
1412 #define GTEST_ADD_REFERENCE_(T) \
1413     typename ::testing::internal::AddReference<T>::type
1414 
1415 // Transforms "T" into "const T&" according to standard reference collapsing
1416 // rules (this is only needed as a backport for C++98 compilers that do not
1417 // support reference collapsing). Specifically, it transforms:
1418 //
1419 //   char         ==> const char&
1420 //   const char   ==> const char&
1421 //   char&        ==> char&
1422 //   const char&  ==> const char&
1423 //
1424 // Note that the non-const reference will not have "const" added. This is
1425 // standard, and necessary so that "T" can always bind to "const T&".
1426 template <typename T>
1427 struct ConstRef { typedef const T& type; };
1428 template <typename T>
1429 struct ConstRef<T&> { typedef T& type; };
1430 
1431 // The argument T must depend on some template parameters.
1432 #define GTEST_REFERENCE_TO_CONST_(T) \
1433   typename ::testing::internal::ConstRef<T>::type
1434 
1435 #if GTEST_HAS_STD_MOVE_
1436 using std::forward;
1437 using std::move;
1438 
1439 template <typename T>
1440 struct RvalueRef {
1441   typedef T&& type;
1442 };
1443 #else  // GTEST_HAS_STD_MOVE_
1444 template <typename T>
1445 const T& move(const T& t) {
1446   return t;
1447 }
1448 template <typename T>
1449 GTEST_ADD_REFERENCE_(T) forward(GTEST_ADD_REFERENCE_(T) t) { return t; }
1450 
1451 template <typename T>
1452 struct RvalueRef {
1453   typedef const T& type;
1454 };
1455 #endif  // GTEST_HAS_STD_MOVE_
1456 
1457 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1458 //
1459 // Use ImplicitCast_ as a safe version of static_cast for upcasting in
1460 // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
1461 // const Foo*).  When you use ImplicitCast_, the compiler checks that
1462 // the cast is safe.  Such explicit ImplicitCast_s are necessary in
1463 // surprisingly many situations where C++ demands an exact type match
1464 // instead of an argument type convertable to a target type.
1465 //
1466 // The syntax for using ImplicitCast_ is the same as for static_cast:
1467 //
1468 //   ImplicitCast_<ToType>(expr)
1469 //
1470 // ImplicitCast_ would have been part of the C++ standard library,
1471 // but the proposal was submitted too late.  It will probably make
1472 // its way into the language in the future.
1473 //
1474 // This relatively ugly name is intentional. It prevents clashes with
1475 // similar functions users may have (e.g., implicit_cast). The internal
1476 // namespace alone is not enough because the function can be found by ADL.
1477 template<typename To>
1478 inline To ImplicitCast_(To x) { return x; }
1479 
1480 // When you upcast (that is, cast a pointer from type Foo to type
1481 // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
1482 // always succeed.  When you downcast (that is, cast a pointer from
1483 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
1484 // how do you know the pointer is really of type SubclassOfFoo?  It
1485 // could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
1486 // when you downcast, you should use this macro.  In debug mode, we
1487 // use dynamic_cast<> to double-check the downcast is legal (we die
1488 // if it's not).  In normal mode, we do the efficient static_cast<>
1489 // instead.  Thus, it's important to test in debug mode to make sure
1490 // the cast is legal!
1491 //    This is the only place in the code we should use dynamic_cast<>.
1492 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
1493 // do RTTI (eg code like this:
1494 //    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
1495 //    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
1496 // You should design the code some other way not to need this.
1497 //
1498 // This relatively ugly name is intentional. It prevents clashes with
1499 // similar functions users may have (e.g., down_cast). The internal
1500 // namespace alone is not enough because the function can be found by ADL.
1501 template<typename To, typename From>  // use like this: DownCast_<T*>(foo);
1502 inline To DownCast_(From* f) {  // so we only accept pointers
1503   // Ensures that To is a sub-type of From *.  This test is here only
1504   // for compile-time type checking, and has no overhead in an
1505   // optimized build at run-time, as it will be optimized away
1506   // completely.
1507   GTEST_INTENTIONAL_CONST_COND_PUSH_()
1508   if (false) {
1509   GTEST_INTENTIONAL_CONST_COND_POP_()
1510     const To to = NULL;
1511     ::testing::internal::ImplicitCast_<From*>(to);
1512   }
1513 
1514 #if GTEST_HAS_RTTI
1515   // RTTI: debug mode only!
1516   GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL);
1517 #endif
1518   return static_cast<To>(f);
1519 }
1520 
1521 // Downcasts the pointer of type Base to Derived.
1522 // Derived must be a subclass of Base. The parameter MUST
1523 // point to a class of type Derived, not any subclass of it.
1524 // When RTTI is available, the function performs a runtime
1525 // check to enforce this.
1526 template <class Derived, class Base>
1527 Derived* CheckedDowncastToActualType(Base* base) {
1528 #if GTEST_HAS_RTTI
1529   GTEST_CHECK_(typeid(*base) == typeid(Derived));
1530 #endif
1531 
1532 #if GTEST_HAS_DOWNCAST_
1533   return ::down_cast<Derived*>(base);
1534 #elif GTEST_HAS_RTTI
1535   return dynamic_cast<Derived*>(base);  // NOLINT
1536 #else
1537   return static_cast<Derived*>(base);  // Poor man's downcast.
1538 #endif
1539 }
1540 
1541 #if GTEST_HAS_STREAM_REDIRECTION
1542 
1543 // Defines the stderr capturer:
1544 //   CaptureStdout     - starts capturing stdout.
1545 //   GetCapturedStdout - stops capturing stdout and returns the captured string.
1546 //   CaptureStderr     - starts capturing stderr.
1547 //   GetCapturedStderr - stops capturing stderr and returns the captured string.
1548 //
1549 GTEST_API_ void CaptureStdout();
1550 GTEST_API_ std::string GetCapturedStdout();
1551 GTEST_API_ void CaptureStderr();
1552 GTEST_API_ std::string GetCapturedStderr();
1553 
1554 #endif  // GTEST_HAS_STREAM_REDIRECTION
1555 // Returns the size (in bytes) of a file.
1556 GTEST_API_ size_t GetFileSize(FILE* file);
1557 
1558 // Reads the entire content of a file as a string.
1559 GTEST_API_ std::string ReadEntireFile(FILE* file);
1560 
1561 // All command line arguments.
1562 GTEST_API_ std::vector<std::string> GetArgvs();
1563 
1564 #if GTEST_HAS_DEATH_TEST
1565 
1566 std::vector<std::string> GetInjectableArgvs();
1567 // Deprecated: pass the args vector by value instead.
1568 void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
1569 void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
1570 #if GTEST_HAS_GLOBAL_STRING
1571 void SetInjectableArgvs(const std::vector< ::string>& new_argvs);
1572 #endif  // GTEST_HAS_GLOBAL_STRING
1573 void ClearInjectableArgvs();
1574 
1575 #endif  // GTEST_HAS_DEATH_TEST
1576 
1577 // Defines synchronization primitives.
1578 #if GTEST_IS_THREADSAFE
1579 # if GTEST_HAS_PTHREAD
1580 // Sleeps for (roughly) n milliseconds.  This function is only for testing
1581 // Google Test's own constructs.  Don't use it in user tests, either
1582 // directly or indirectly.
1583 inline void SleepMilliseconds(int n) {
1584   const timespec time = {
1585     0,                  // 0 seconds.
1586     n * 1000L * 1000L,  // And n ms.
1587   };
1588   nanosleep(&time, NULL);
1589 }
1590 # endif  // GTEST_HAS_PTHREAD
1591 
1592 # if GTEST_HAS_NOTIFICATION_
1593 // Notification has already been imported into the namespace.
1594 // Nothing to do here.
1595 
1596 # elif GTEST_HAS_PTHREAD
1597 // Allows a controller thread to pause execution of newly created
1598 // threads until notified.  Instances of this class must be created
1599 // and destroyed in the controller thread.
1600 //
1601 // This class is only for testing Google Test's own constructs. Do not
1602 // use it in user tests, either directly or indirectly.
1603 class Notification {
1604  public:
1605   Notification() : notified_(false) {
1606     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
1607   }
1608   ~Notification() {
1609     pthread_mutex_destroy(&mutex_);
1610   }
1611 
1612   // Notifies all threads created with this notification to start. Must
1613   // be called from the controller thread.
1614   void Notify() {
1615     pthread_mutex_lock(&mutex_);
1616     notified_ = true;
1617     pthread_mutex_unlock(&mutex_);
1618   }
1619 
1620   // Blocks until the controller thread notifies. Must be called from a test
1621   // thread.
1622   void WaitForNotification() {
1623     for (;;) {
1624       pthread_mutex_lock(&mutex_);
1625       const bool notified = notified_;
1626       pthread_mutex_unlock(&mutex_);
1627       if (notified)
1628         break;
1629       SleepMilliseconds(10);
1630     }
1631   }
1632 
1633  private:
1634   pthread_mutex_t mutex_;
1635   bool notified_;
1636 
1637   GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1638 };
1639 
1640 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1641 
1642 GTEST_API_ void SleepMilliseconds(int n);
1643 
1644 // Provides leak-safe Windows kernel handle ownership.
1645 // Used in death tests and in threading support.
1646 class GTEST_API_ AutoHandle {
1647  public:
1648   // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
1649   // avoid including <windows.h> in this header file. Including <windows.h> is
1650   // undesirable because it defines a lot of symbols and macros that tend to
1651   // conflict with client code. This assumption is verified by
1652   // WindowsTypesTest.HANDLEIsVoidStar.
1653   typedef void* Handle;
1654   AutoHandle();
1655   explicit AutoHandle(Handle handle);
1656 
1657   ~AutoHandle();
1658 
1659   Handle Get() const;
1660   void Reset();
1661   void Reset(Handle handle);
1662 
1663  private:
1664   // Returns true iff the handle is a valid handle object that can be closed.
1665   bool IsCloseable() const;
1666 
1667   Handle handle_;
1668 
1669   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1670 };
1671 
1672 // Allows a controller thread to pause execution of newly created
1673 // threads until notified.  Instances of this class must be created
1674 // and destroyed in the controller thread.
1675 //
1676 // This class is only for testing Google Test's own constructs. Do not
1677 // use it in user tests, either directly or indirectly.
1678 class GTEST_API_ Notification {
1679  public:
1680   Notification();
1681   void Notify();
1682   void WaitForNotification();
1683 
1684  private:
1685   AutoHandle event_;
1686 
1687   GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1688 };
1689 # endif  // GTEST_HAS_NOTIFICATION_
1690 
1691 // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
1692 // defined, but we don't want to use MinGW's pthreads implementation, which
1693 // has conformance problems with some versions of the POSIX standard.
1694 # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1695 
1696 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
1697 // Consequently, it cannot select a correct instantiation of ThreadWithParam
1698 // in order to call its Run(). Introducing ThreadWithParamBase as a
1699 // non-templated base class for ThreadWithParam allows us to bypass this
1700 // problem.
1701 class ThreadWithParamBase {
1702  public:
1703   virtual ~ThreadWithParamBase() {}
1704   virtual void Run() = 0;
1705 };
1706 
1707 // pthread_create() accepts a pointer to a function type with the C linkage.
1708 // According to the Standard (7.5/1), function types with different linkages
1709 // are different even if they are otherwise identical.  Some compilers (for
1710 // example, SunStudio) treat them as different types.  Since class methods
1711 // cannot be defined with C-linkage we need to define a free C-function to
1712 // pass into pthread_create().
1713 extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
1714   static_cast<ThreadWithParamBase*>(thread)->Run();
1715   return NULL;
1716 }
1717 
1718 // Helper class for testing Google Test's multi-threading constructs.
1719 // To use it, write:
1720 //
1721 //   void ThreadFunc(int param) { /* Do things with param */ }
1722 //   Notification thread_can_start;
1723 //   ...
1724 //   // The thread_can_start parameter is optional; you can supply NULL.
1725 //   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
1726 //   thread_can_start.Notify();
1727 //
1728 // These classes are only for testing Google Test's own constructs. Do
1729 // not use them in user tests, either directly or indirectly.
1730 template <typename T>
1731 class ThreadWithParam : public ThreadWithParamBase {
1732  public:
1733   typedef void UserThreadFunc(T);
1734 
1735   ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1736       : func_(func),
1737         param_(param),
1738         thread_can_start_(thread_can_start),
1739         finished_(false) {
1740     ThreadWithParamBase* const base = this;
1741     // The thread can be created only after all fields except thread_
1742     // have been initialized.
1743     GTEST_CHECK_POSIX_SUCCESS_(
1744         pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
1745   }
1746   ~ThreadWithParam() { Join(); }
1747 
1748   void Join() {
1749     if (!finished_) {
1750       GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
1751       finished_ = true;
1752     }
1753   }
1754 
1755   virtual void Run() {
1756     if (thread_can_start_ != NULL)
1757       thread_can_start_->WaitForNotification();
1758     func_(param_);
1759   }
1760 
1761  private:
1762   UserThreadFunc* const func_;  // User-supplied thread function.
1763   const T param_;  // User-supplied parameter to the thread function.
1764   // When non-NULL, used to block execution until the controller thread
1765   // notifies.
1766   Notification* const thread_can_start_;
1767   bool finished_;  // true iff we know that the thread function has finished.
1768   pthread_t thread_;  // The native thread object.
1769 
1770   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1771 };
1772 # endif  // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
1773          // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1774 
1775 # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1776 // Mutex and ThreadLocal have already been imported into the namespace.
1777 // Nothing to do here.
1778 
1779 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1780 
1781 // Mutex implements mutex on Windows platforms.  It is used in conjunction
1782 // with class MutexLock:
1783 //
1784 //   Mutex mutex;
1785 //   ...
1786 //   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the
1787 //                            // end of the current scope.
1788 //
1789 // A static Mutex *must* be defined or declared using one of the following
1790 // macros:
1791 //   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
1792 //   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
1793 //
1794 // (A non-static Mutex is defined/declared in the usual way).
1795 class GTEST_API_ Mutex {
1796  public:
1797   enum MutexType { kStatic = 0, kDynamic = 1 };
1798   // We rely on kStaticMutex being 0 as it is to what the linker initializes
1799   // type_ in static mutexes.  critical_section_ will be initialized lazily
1800   // in ThreadSafeLazyInit().
1801   enum StaticConstructorSelector { kStaticMutex = 0 };
1802 
1803   // This constructor intentionally does nothing.  It relies on type_ being
1804   // statically initialized to 0 (effectively setting it to kStatic) and on
1805   // ThreadSafeLazyInit() to lazily initialize the rest of the members.
1806   explicit Mutex(StaticConstructorSelector /*dummy*/) {}
1807 
1808   Mutex();
1809   ~Mutex();
1810 
1811   void Lock();
1812 
1813   void Unlock();
1814 
1815   // Does nothing if the current thread holds the mutex. Otherwise, crashes
1816   // with high probability.
1817   void AssertHeld();
1818 
1819  private:
1820   // Initializes owner_thread_id_ and critical_section_ in static mutexes.
1821   void ThreadSafeLazyInit();
1822 
1823   // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
1824   // we assume that 0 is an invalid value for thread IDs.
1825   unsigned int owner_thread_id_;
1826 
1827   // For static mutexes, we rely on these members being initialized to zeros
1828   // by the linker.
1829   MutexType type_;
1830   long critical_section_init_phase_;  // NOLINT
1831   GTEST_CRITICAL_SECTION* critical_section_;
1832 
1833   GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1834 };
1835 
1836 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1837     extern ::testing::internal::Mutex mutex
1838 
1839 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1840     ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
1841 
1842 // We cannot name this class MutexLock because the ctor declaration would
1843 // conflict with a macro named MutexLock, which is defined on some
1844 // platforms. That macro is used as a defensive measure to prevent against
1845 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1846 // "MutexLock l(&mu)".  Hence the typedef trick below.
1847 class GTestMutexLock {
1848  public:
1849   explicit GTestMutexLock(Mutex* mutex)
1850       : mutex_(mutex) { mutex_->Lock(); }
1851 
1852   ~GTestMutexLock() { mutex_->Unlock(); }
1853 
1854  private:
1855   Mutex* const mutex_;
1856 
1857   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1858 };
1859 
1860 typedef GTestMutexLock MutexLock;
1861 
1862 // Base class for ValueHolder<T>.  Allows a caller to hold and delete a value
1863 // without knowing its type.
1864 class ThreadLocalValueHolderBase {
1865  public:
1866   virtual ~ThreadLocalValueHolderBase() {}
1867 };
1868 
1869 // Provides a way for a thread to send notifications to a ThreadLocal
1870 // regardless of its parameter type.
1871 class ThreadLocalBase {
1872  public:
1873   // Creates a new ValueHolder<T> object holding a default value passed to
1874   // this ThreadLocal<T>'s constructor and returns it.  It is the caller's
1875   // responsibility not to call this when the ThreadLocal<T> instance already
1876   // has a value on the current thread.
1877   virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
1878 
1879  protected:
1880   ThreadLocalBase() {}
1881   virtual ~ThreadLocalBase() {}
1882 
1883  private:
1884   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
1885 };
1886 
1887 // Maps a thread to a set of ThreadLocals that have values instantiated on that
1888 // thread and notifies them when the thread exits.  A ThreadLocal instance is
1889 // expected to persist until all threads it has values on have terminated.
1890 class GTEST_API_ ThreadLocalRegistry {
1891  public:
1892   // Registers thread_local_instance as having value on the current thread.
1893   // Returns a value that can be used to identify the thread from other threads.
1894   static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
1895       const ThreadLocalBase* thread_local_instance);
1896 
1897   // Invoked when a ThreadLocal instance is destroyed.
1898   static void OnThreadLocalDestroyed(
1899       const ThreadLocalBase* thread_local_instance);
1900 };
1901 
1902 class GTEST_API_ ThreadWithParamBase {
1903  public:
1904   void Join();
1905 
1906  protected:
1907   class Runnable {
1908    public:
1909     virtual ~Runnable() {}
1910     virtual void Run() = 0;
1911   };
1912 
1913   ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
1914   virtual ~ThreadWithParamBase();
1915 
1916  private:
1917   AutoHandle thread_;
1918 };
1919 
1920 // Helper class for testing Google Test's multi-threading constructs.
1921 template <typename T>
1922 class ThreadWithParam : public ThreadWithParamBase {
1923  public:
1924   typedef void UserThreadFunc(T);
1925 
1926   ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1927       : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
1928   }
1929   virtual ~ThreadWithParam() {}
1930 
1931  private:
1932   class RunnableImpl : public Runnable {
1933    public:
1934     RunnableImpl(UserThreadFunc* func, T param)
1935         : func_(func),
1936           param_(param) {
1937     }
1938     virtual ~RunnableImpl() {}
1939     virtual void Run() {
1940       func_(param_);
1941     }
1942 
1943    private:
1944     UserThreadFunc* const func_;
1945     const T param_;
1946 
1947     GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
1948   };
1949 
1950   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1951 };
1952 
1953 // Implements thread-local storage on Windows systems.
1954 //
1955 //   // Thread 1
1956 //   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.
1957 //
1958 //   // Thread 2
1959 //   tl.set(150);  // Changes the value for thread 2 only.
1960 //   EXPECT_EQ(150, tl.get());
1961 //
1962 //   // Thread 1
1963 //   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.
1964 //   tl.set(200);
1965 //   EXPECT_EQ(200, tl.get());
1966 //
1967 // The template type argument T must have a public copy constructor.
1968 // In addition, the default ThreadLocal constructor requires T to have
1969 // a public default constructor.
1970 //
1971 // The users of a TheadLocal instance have to make sure that all but one
1972 // threads (including the main one) using that instance have exited before
1973 // destroying it. Otherwise, the per-thread objects managed for them by the
1974 // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
1975 //
1976 // Google Test only uses global ThreadLocal objects.  That means they
1977 // will die after main() has returned.  Therefore, no per-thread
1978 // object managed by Google Test will be leaked as long as all threads
1979 // using Google Test have exited when main() returns.
1980 template <typename T>
1981 class ThreadLocal : public ThreadLocalBase {
1982  public:
1983   ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
1984   explicit ThreadLocal(const T& value)
1985       : default_factory_(new InstanceValueHolderFactory(value)) {}
1986 
1987   ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
1988 
1989   T* pointer() { return GetOrCreateValue(); }
1990   const T* pointer() const { return GetOrCreateValue(); }
1991   const T& get() const { return *pointer(); }
1992   void set(const T& value) { *pointer() = value; }
1993 
1994  private:
1995   // Holds a value of T.  Can be deleted via its base class without the caller
1996   // knowing the type of T.
1997   class ValueHolder : public ThreadLocalValueHolderBase {
1998    public:
1999     ValueHolder() : value_() {}
2000     explicit ValueHolder(const T& value) : value_(value) {}
2001 
2002     T* pointer() { return &value_; }
2003 
2004    private:
2005     T value_;
2006     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
2007   };
2008 
2009 
2010   T* GetOrCreateValue() const {
2011     return static_cast<ValueHolder*>(
2012         ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
2013   }
2014 
2015   virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
2016     return default_factory_->MakeNewHolder();
2017   }
2018 
2019   class ValueHolderFactory {
2020    public:
2021     ValueHolderFactory() {}
2022     virtual ~ValueHolderFactory() {}
2023     virtual ValueHolder* MakeNewHolder() const = 0;
2024 
2025    private:
2026     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
2027   };
2028 
2029   class DefaultValueHolderFactory : public ValueHolderFactory {
2030    public:
2031     DefaultValueHolderFactory() {}
2032     virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
2033 
2034    private:
2035     GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
2036   };
2037 
2038   class InstanceValueHolderFactory : public ValueHolderFactory {
2039    public:
2040     explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
2041     virtual ValueHolder* MakeNewHolder() const {
2042       return new ValueHolder(value_);
2043     }
2044 
2045    private:
2046     const T value_;  // The value for each thread.
2047 
2048     GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
2049   };
2050 
2051   scoped_ptr<ValueHolderFactory> default_factory_;
2052 
2053   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
2054 };
2055 
2056 # elif GTEST_HAS_PTHREAD
2057 
2058 // MutexBase and Mutex implement mutex on pthreads-based platforms.
2059 class MutexBase {
2060  public:
2061   // Acquires this mutex.
2062   void Lock() {
2063     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
2064     owner_ = pthread_self();
2065     has_owner_ = true;
2066   }
2067 
2068   // Releases this mutex.
2069   void Unlock() {
2070     // Since the lock is being released the owner_ field should no longer be
2071     // considered valid. We don't protect writing to has_owner_ here, as it's
2072     // the caller's responsibility to ensure that the current thread holds the
2073     // mutex when this is called.
2074     has_owner_ = false;
2075     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
2076   }
2077 
2078   // Does nothing if the current thread holds the mutex. Otherwise, crashes
2079   // with high probability.
2080   void AssertHeld() const {
2081     GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
2082         << "The current thread is not holding the mutex @" << this;
2083   }
2084 
2085   // A static mutex may be used before main() is entered.  It may even
2086   // be used before the dynamic initialization stage.  Therefore we
2087   // must be able to initialize a static mutex object at link time.
2088   // This means MutexBase has to be a POD and its member variables
2089   // have to be public.
2090  public:
2091   pthread_mutex_t mutex_;  // The underlying pthread mutex.
2092   // has_owner_ indicates whether the owner_ field below contains a valid thread
2093   // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
2094   // accesses to the owner_ field should be protected by a check of this field.
2095   // An alternative might be to memset() owner_ to all zeros, but there's no
2096   // guarantee that a zero'd pthread_t is necessarily invalid or even different
2097   // from pthread_self().
2098   bool has_owner_;
2099   pthread_t owner_;  // The thread holding the mutex.
2100 };
2101 
2102 // Forward-declares a static mutex.
2103 #  define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2104      extern ::testing::internal::MutexBase mutex
2105 
2106 // Defines and statically (i.e. at link time) initializes a static mutex.
2107 // The initialization list here does not explicitly initialize each field,
2108 // instead relying on default initialization for the unspecified fields. In
2109 // particular, the owner_ field (a pthread_t) is not explicitly initialized.
2110 // This allows initialization to work whether pthread_t is a scalar or struct.
2111 // The flag -Wmissing-field-initializers must not be specified for this to work.
2112 #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
2113   ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}
2114 
2115 // The Mutex class can only be used for mutexes created at runtime. It
2116 // shares its API with MutexBase otherwise.
2117 class Mutex : public MutexBase {
2118  public:
2119   Mutex() {
2120     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
2121     has_owner_ = false;
2122   }
2123   ~Mutex() {
2124     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
2125   }
2126 
2127  private:
2128   GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
2129 };
2130 
2131 // We cannot name this class MutexLock because the ctor declaration would
2132 // conflict with a macro named MutexLock, which is defined on some
2133 // platforms. That macro is used as a defensive measure to prevent against
2134 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2135 // "MutexLock l(&mu)".  Hence the typedef trick below.
2136 class GTestMutexLock {
2137  public:
2138   explicit GTestMutexLock(MutexBase* mutex)
2139       : mutex_(mutex) { mutex_->Lock(); }
2140 
2141   ~GTestMutexLock() { mutex_->Unlock(); }
2142 
2143  private:
2144   MutexBase* const mutex_;
2145 
2146   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
2147 };
2148 
2149 typedef GTestMutexLock MutexLock;
2150 
2151 // Helpers for ThreadLocal.
2152 
2153 // pthread_key_create() requires DeleteThreadLocalValue() to have
2154 // C-linkage.  Therefore it cannot be templatized to access
2155 // ThreadLocal<T>.  Hence the need for class
2156 // ThreadLocalValueHolderBase.
2157 class ThreadLocalValueHolderBase {
2158  public:
2159   virtual ~ThreadLocalValueHolderBase() {}
2160 };
2161 
2162 // Called by pthread to delete thread-local data stored by
2163 // pthread_setspecific().
2164 extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
2165   delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
2166 }
2167 
2168 // Implements thread-local storage on pthreads-based systems.
2169 template <typename T>
2170 class GTEST_API_ ThreadLocal {
2171  public:
2172   ThreadLocal()
2173       : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
2174   explicit ThreadLocal(const T& value)
2175       : key_(CreateKey()),
2176         default_factory_(new InstanceValueHolderFactory(value)) {}
2177 
2178   ~ThreadLocal() {
2179     // Destroys the managed object for the current thread, if any.
2180     DeleteThreadLocalValue(pthread_getspecific(key_));
2181 
2182     // Releases resources associated with the key.  This will *not*
2183     // delete managed objects for other threads.
2184     GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
2185   }
2186 
2187   T* pointer() { return GetOrCreateValue(); }
2188   const T* pointer() const { return GetOrCreateValue(); }
2189   const T& get() const { return *pointer(); }
2190   void set(const T& value) { *pointer() = value; }
2191 
2192  private:
2193   // Holds a value of type T.
2194   class ValueHolder : public ThreadLocalValueHolderBase {
2195    public:
2196     ValueHolder() : value_() {}
2197     explicit ValueHolder(const T& value) : value_(value) {}
2198 
2199     T* pointer() { return &value_; }
2200 
2201    private:
2202     T value_;
2203     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
2204   };
2205 
2206   static pthread_key_t CreateKey() {
2207     pthread_key_t key;
2208     // When a thread exits, DeleteThreadLocalValue() will be called on
2209     // the object managed for that thread.
2210     GTEST_CHECK_POSIX_SUCCESS_(
2211         pthread_key_create(&key, &DeleteThreadLocalValue));
2212     return key;
2213   }
2214 
2215   T* GetOrCreateValue() const {
2216     ThreadLocalValueHolderBase* const holder =
2217         static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
2218     if (holder != NULL) {
2219       return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
2220     }
2221 
2222     ValueHolder* const new_holder = default_factory_->MakeNewHolder();
2223     ThreadLocalValueHolderBase* const holder_base = new_holder;
2224     GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
2225     return new_holder->pointer();
2226   }
2227 
2228   class ValueHolderFactory {
2229    public:
2230     ValueHolderFactory() {}
2231     virtual ~ValueHolderFactory() {}
2232     virtual ValueHolder* MakeNewHolder() const = 0;
2233 
2234    private:
2235     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
2236   };
2237 
2238   class DefaultValueHolderFactory : public ValueHolderFactory {
2239    public:
2240     DefaultValueHolderFactory() {}
2241     virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
2242 
2243    private:
2244     GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
2245   };
2246 
2247   class InstanceValueHolderFactory : public ValueHolderFactory {
2248    public:
2249     explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
2250     virtual ValueHolder* MakeNewHolder() const {
2251       return new ValueHolder(value_);
2252     }
2253 
2254    private:
2255     const T value_;  // The value for each thread.
2256 
2257     GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
2258   };
2259 
2260   // A key pthreads uses for looking up per-thread values.
2261   const pthread_key_t key_;
2262   scoped_ptr<ValueHolderFactory> default_factory_;
2263 
2264   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
2265 };
2266 
2267 # endif  // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
2268 
2269 #else  // GTEST_IS_THREADSAFE
2270 
2271 // A dummy implementation of synchronization primitives (mutex, lock,
2272 // and thread-local variable).  Necessary for compiling Google Test where
2273 // mutex is not supported - using Google Test in multiple threads is not
2274 // supported on such platforms.
2275 
2276 class Mutex {
2277  public:
2278   Mutex() {}
2279   void Lock() {}
2280   void Unlock() {}
2281   void AssertHeld() const {}
2282 };
2283 
2284 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2285   extern ::testing::internal::Mutex mutex
2286 
2287 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
2288 
2289 // We cannot name this class MutexLock because the ctor declaration would
2290 // conflict with a macro named MutexLock, which is defined on some
2291 // platforms. That macro is used as a defensive measure to prevent against
2292 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2293 // "MutexLock l(&mu)".  Hence the typedef trick below.
2294 class GTestMutexLock {
2295  public:
2296   explicit GTestMutexLock(Mutex*) {}  // NOLINT
2297 };
2298 
2299 typedef GTestMutexLock MutexLock;
2300 
2301 template <typename T>
2302 class GTEST_API_ ThreadLocal {
2303  public:
2304   ThreadLocal() : value_() {}
2305   explicit ThreadLocal(const T& value) : value_(value) {}
2306   T* pointer() { return &value_; }
2307   const T* pointer() const { return &value_; }
2308   const T& get() const { return value_; }
2309   void set(const T& value) { value_ = value; }
2310  private:
2311   T value_;
2312 };
2313 
2314 #endif  // GTEST_IS_THREADSAFE
2315 
2316 // Returns the number of threads running in the process, or 0 to indicate that
2317 // we cannot detect it.
2318 GTEST_API_ size_t GetThreadCount();
2319 
2320 // Passing non-POD classes through ellipsis (...) crashes the ARM
2321 // compiler and generates a warning in Sun Studio before 12u4. The Nokia Symbian
2322 // and the IBM XL C/C++ compiler try to instantiate a copy constructor
2323 // for objects passed through ellipsis (...), failing for uncopyable
2324 // objects.  We define this to ensure that only POD is passed through
2325 // ellipsis on these systems.
2326 #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || \
2327      (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x5130)
2328 // We lose support for NULL detection where the compiler doesn't like
2329 // passing non-POD classes through ellipsis (...).
2330 # define GTEST_ELLIPSIS_NEEDS_POD_ 1
2331 #else
2332 # define GTEST_CAN_COMPARE_NULL 1
2333 #endif
2334 
2335 // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
2336 // const T& and const T* in a function template.  These compilers
2337 // _can_ decide between class template specializations for T and T*,
2338 // so a tr1::type_traits-like is_pointer works.
2339 #if defined(__SYMBIAN32__) || defined(__IBMCPP__)
2340 # define GTEST_NEEDS_IS_POINTER_ 1
2341 #endif
2342 
2343 template <bool bool_value>
2344 struct bool_constant {
2345   typedef bool_constant<bool_value> type;
2346   static const bool value = bool_value;
2347 };
2348 template <bool bool_value> const bool bool_constant<bool_value>::value;
2349 
2350 typedef bool_constant<false> false_type;
2351 typedef bool_constant<true> true_type;
2352 
2353 template <typename T, typename U>
2354 struct is_same : public false_type {};
2355 
2356 template <typename T>
2357 struct is_same<T, T> : public true_type {};
2358 
2359 
2360 template <typename T>
2361 struct is_pointer : public false_type {};
2362 
2363 template <typename T>
2364 struct is_pointer<T*> : public true_type {};
2365 
2366 template <typename Iterator>
2367 struct IteratorTraits {
2368   typedef typename Iterator::value_type value_type;
2369 };
2370 
2371 
2372 template <typename T>
2373 struct IteratorTraits<T*> {
2374   typedef T value_type;
2375 };
2376 
2377 template <typename T>
2378 struct IteratorTraits<const T*> {
2379   typedef T value_type;
2380 };
2381 
2382 #if GTEST_OS_WINDOWS
2383 # define GTEST_PATH_SEP_ "\\"
2384 # define GTEST_HAS_ALT_PATH_SEP_ 1
2385 // The biggest signed integer type the compiler supports.
2386 typedef __int64 BiggestInt;
2387 #else
2388 # define GTEST_PATH_SEP_ "/"
2389 # define GTEST_HAS_ALT_PATH_SEP_ 0
2390 typedef long long BiggestInt;  // NOLINT
2391 #endif  // GTEST_OS_WINDOWS
2392 
2393 // Utilities for char.
2394 
2395 // isspace(int ch) and friends accept an unsigned char or EOF.  char
2396 // may be signed, depending on the compiler (or compiler flags).
2397 // Therefore we need to cast a char to unsigned char before calling
2398 // isspace(), etc.
2399 
2400 inline bool IsAlpha(char ch) {
2401   return isalpha(static_cast<unsigned char>(ch)) != 0;
2402 }
2403 inline bool IsAlNum(char ch) {
2404   return isalnum(static_cast<unsigned char>(ch)) != 0;
2405 }
2406 inline bool IsDigit(char ch) {
2407   return isdigit(static_cast<unsigned char>(ch)) != 0;
2408 }
2409 inline bool IsLower(char ch) {
2410   return islower(static_cast<unsigned char>(ch)) != 0;
2411 }
2412 inline bool IsSpace(char ch) {
2413   return isspace(static_cast<unsigned char>(ch)) != 0;
2414 }
2415 inline bool IsUpper(char ch) {
2416   return isupper(static_cast<unsigned char>(ch)) != 0;
2417 }
2418 inline bool IsXDigit(char ch) {
2419   return isxdigit(static_cast<unsigned char>(ch)) != 0;
2420 }
2421 inline bool IsXDigit(wchar_t ch) {
2422   const unsigned char low_byte = static_cast<unsigned char>(ch);
2423   return ch == low_byte && isxdigit(low_byte) != 0;
2424 }
2425 
2426 inline char ToLower(char ch) {
2427   return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
2428 }
2429 inline char ToUpper(char ch) {
2430   return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
2431 }
2432 
2433 inline std::string StripTrailingSpaces(std::string str) {
2434   std::string::iterator it = str.end();
2435   while (it != str.begin() && IsSpace(*--it))
2436     it = str.erase(it);
2437   return str;
2438 }
2439 
2440 // The testing::internal::posix namespace holds wrappers for common
2441 // POSIX functions.  These wrappers hide the differences between
2442 // Windows/MSVC and POSIX systems.  Since some compilers define these
2443 // standard functions as macros, the wrapper cannot have the same name
2444 // as the wrapped function.
2445 
2446 namespace posix {
2447 
2448 // Functions with a different name on Windows.
2449 
2450 #if GTEST_OS_WINDOWS
2451 
2452 typedef struct _stat StatStruct;
2453 
2454 # ifdef __BORLANDC__
2455 inline int IsATTY(int fd) { return isatty(fd); }
2456 inline int StrCaseCmp(const char* s1, const char* s2) {
2457   return stricmp(s1, s2);
2458 }
2459 inline char* StrDup(const char* src) { return strdup(src); }
2460 # else  // !__BORLANDC__
2461 #  if GTEST_OS_WINDOWS_MOBILE
2462 inline int IsATTY(int /* fd */) { return 0; }
2463 #  else
2464 inline int IsATTY(int fd) { return _isatty(fd); }
2465 #  endif  // GTEST_OS_WINDOWS_MOBILE
2466 inline int StrCaseCmp(const char* s1, const char* s2) {
2467   return _stricmp(s1, s2);
2468 }
2469 inline char* StrDup(const char* src) { return _strdup(src); }
2470 # endif  // __BORLANDC__
2471 
2472 # if GTEST_OS_WINDOWS_MOBILE
2473 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
2474 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
2475 // time and thus not defined there.
2476 # else
2477 inline int FileNo(FILE* file) { return _fileno(file); }
2478 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
2479 inline int RmDir(const char* dir) { return _rmdir(dir); }
2480 inline bool IsDir(const StatStruct& st) {
2481   return (_S_IFDIR & st.st_mode) != 0;
2482 }
2483 # endif  // GTEST_OS_WINDOWS_MOBILE
2484 
2485 #else
2486 
2487 typedef struct stat StatStruct;
2488 
2489 inline int FileNo(FILE* file) { return fileno(file); }
2490 inline int IsATTY(int fd) { return isatty(fd); }
2491 inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
2492 inline int StrCaseCmp(const char* s1, const char* s2) {
2493   return strcasecmp(s1, s2);
2494 }
2495 inline char* StrDup(const char* src) { return strdup(src); }
2496 inline int RmDir(const char* dir) { return rmdir(dir); }
2497 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2498 
2499 #endif  // GTEST_OS_WINDOWS
2500 
2501 // Functions deprecated by MSVC 8.0.
2502 
2503 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
2504 
2505 inline const char* StrNCpy(char* dest, const char* src, size_t n) {
2506   return strncpy(dest, src, n);
2507 }
2508 
2509 // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
2510 // StrError() aren't needed on Windows CE at this time and thus not
2511 // defined there.
2512 
2513 #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
2514 inline int ChDir(const char* dir) { return chdir(dir); }
2515 #endif
2516 inline FILE* FOpen(const char* path, const char* mode) {
2517   return fopen(path, mode);
2518 }
2519 #if !GTEST_OS_WINDOWS_MOBILE
2520 inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
2521   return freopen(path, mode, stream);
2522 }
2523 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
2524 #endif
2525 inline int FClose(FILE* fp) { return fclose(fp); }
2526 #if !GTEST_OS_WINDOWS_MOBILE
2527 inline int Read(int fd, void* buf, unsigned int count) {
2528   return static_cast<int>(read(fd, buf, count));
2529 }
2530 inline int Write(int fd, const void* buf, unsigned int count) {
2531   return static_cast<int>(write(fd, buf, count));
2532 }
2533 inline int Close(int fd) { return close(fd); }
2534 inline const char* StrError(int errnum) { return strerror(errnum); }
2535 #endif
2536 inline const char* GetEnv(const char* name) {
2537 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
2538   // We are on Windows CE, which has no environment variables.
2539   static_cast<void>(name);  // To prevent 'unused argument' warning.
2540   return NULL;
2541 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
2542   // Environment variables which we programmatically clear will be set to the
2543   // empty string rather than unset (NULL).  Handle that case.
2544   const char* const env = getenv(name);
2545   return (env != NULL && env[0] != '\0') ? env : NULL;
2546 #else
2547   return getenv(name);
2548 #endif
2549 }
2550 
2551 GTEST_DISABLE_MSC_DEPRECATED_POP_()
2552 
2553 #if GTEST_OS_WINDOWS_MOBILE
2554 // Windows CE has no C library. The abort() function is used in
2555 // several places in Google Test. This implementation provides a reasonable
2556 // imitation of standard behaviour.
2557 void Abort();
2558 #else
2559 inline void Abort() { abort(); }
2560 #endif  // GTEST_OS_WINDOWS_MOBILE
2561 
2562 }  // namespace posix
2563 
2564 // MSVC "deprecates" snprintf and issues warnings wherever it is used.  In
2565 // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
2566 // MSVC-based platforms.  We map the GTEST_SNPRINTF_ macro to the appropriate
2567 // function in order to achieve that.  We use macro definition here because
2568 // snprintf is a variadic function.
2569 #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
2570 // MSVC 2005 and above support variadic macros.
2571 # define GTEST_SNPRINTF_(buffer, size, format, ...) \
2572      _snprintf_s(buffer, size, size, format, __VA_ARGS__)
2573 #elif defined(_MSC_VER)
2574 // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't
2575 // complain about _snprintf.
2576 # define GTEST_SNPRINTF_ _snprintf
2577 #else
2578 # define GTEST_SNPRINTF_ snprintf
2579 #endif
2580 
2581 // The maximum number a BiggestInt can represent.  This definition
2582 // works no matter BiggestInt is represented in one's complement or
2583 // two's complement.
2584 //
2585 // We cannot rely on numeric_limits in STL, as __int64 and long long
2586 // are not part of standard C++ and numeric_limits doesn't need to be
2587 // defined for them.
2588 const BiggestInt kMaxBiggestInt =
2589     ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
2590 
2591 // This template class serves as a compile-time function from size to
2592 // type.  It maps a size in bytes to a primitive type with that
2593 // size. e.g.
2594 //
2595 //   TypeWithSize<4>::UInt
2596 //
2597 // is typedef-ed to be unsigned int (unsigned integer made up of 4
2598 // bytes).
2599 //
2600 // Such functionality should belong to STL, but I cannot find it
2601 // there.
2602 //
2603 // Google Test uses this class in the implementation of floating-point
2604 // comparison.
2605 //
2606 // For now it only handles UInt (unsigned int) as that's all Google Test
2607 // needs.  Other types can be easily added in the future if need
2608 // arises.
2609 template <size_t size>
2610 class TypeWithSize {
2611  public:
2612   // This prevents the user from using TypeWithSize<N> with incorrect
2613   // values of N.
2614   typedef void UInt;
2615 };
2616 
2617 // The specialization for size 4.
2618 template <>
2619 class TypeWithSize<4> {
2620  public:
2621   // unsigned int has size 4 in both gcc and MSVC.
2622   //
2623   // As base/basictypes.h doesn't compile on Windows, we cannot use
2624   // uint32, uint64, and etc here.
2625   typedef int Int;
2626   typedef unsigned int UInt;
2627 };
2628 
2629 // The specialization for size 8.
2630 template <>
2631 class TypeWithSize<8> {
2632  public:
2633 #if GTEST_OS_WINDOWS
2634   typedef __int64 Int;
2635   typedef unsigned __int64 UInt;
2636 #else
2637   typedef long long Int;  // NOLINT
2638   typedef unsigned long long UInt;  // NOLINT
2639 #endif  // GTEST_OS_WINDOWS
2640 };
2641 
2642 // Integer types of known sizes.
2643 typedef TypeWithSize<4>::Int Int32;
2644 typedef TypeWithSize<4>::UInt UInt32;
2645 typedef TypeWithSize<8>::Int Int64;
2646 typedef TypeWithSize<8>::UInt UInt64;
2647 typedef TypeWithSize<8>::Int TimeInMillis;  // Represents time in milliseconds.
2648 
2649 // Utilities for command line flags and environment variables.
2650 
2651 // Macro for referencing flags.
2652 #if !defined(GTEST_FLAG)
2653 # define GTEST_FLAG(name) FLAGS_gtest_##name
2654 #endif  // !defined(GTEST_FLAG)
2655 
2656 #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2657 # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
2658 #endif  // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2659 
2660 #if !defined(GTEST_DECLARE_bool_)
2661 # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
2662 
2663 // Macros for declaring flags.
2664 # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
2665 # define GTEST_DECLARE_int32_(name) \
2666     GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
2667 # define GTEST_DECLARE_string_(name) \
2668     GTEST_API_ extern ::std::string GTEST_FLAG(name)
2669 
2670 // Macros for defining flags.
2671 # define GTEST_DEFINE_bool_(name, default_val, doc) \
2672     GTEST_API_ bool GTEST_FLAG(name) = (default_val)
2673 # define GTEST_DEFINE_int32_(name, default_val, doc) \
2674     GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
2675 # define GTEST_DEFINE_string_(name, default_val, doc) \
2676     GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
2677 
2678 #endif  // !defined(GTEST_DECLARE_bool_)
2679 
2680 // Thread annotations
2681 #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2682 # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
2683 # define GTEST_LOCK_EXCLUDED_(locks)
2684 #endif  // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2685 
2686 // Parses 'str' for a 32-bit signed integer.  If successful, writes the result
2687 // to *value and returns true; otherwise leaves *value unchanged and returns
2688 // false.
2689 // FIXME: Find a better way to refactor flag and environment parsing
2690 // out of both gtest-port.cc and gtest.cc to avoid exporting this utility
2691 // function.
2692 bool ParseInt32(const Message& src_text, const char* str, Int32* value);
2693 
2694 // Parses a bool/Int32/string from the environment variable
2695 // corresponding to the given Google Test flag.
2696 bool BoolFromGTestEnv(const char* flag, bool default_val);
2697 GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
2698 std::string OutputFlagAlsoCheckEnvVar();
2699 const char* StringFromGTestEnv(const char* flag, const char* default_val);
2700 
2701 }  // namespace internal
2702 }  // namespace testing
2703 
2704 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
2705