Debian Codegraph @

LspCpp/third_party/uri/deps/googletest/include/gtest/internal/gtest-port.h

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