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