Debian Codegraph @

src/googletest/include/gtest/internal/gtest-port.h

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