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