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