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