]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - utils/unittest/googletest/include/gtest/internal/gtest-port.h
Update LLVM to r108243.
[FreeBSD/FreeBSD.git] / utils / unittest / googletest / include / gtest / internal / gtest-port.h
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 // Authors: wan@google.com (Zhanyong Wan)
31 //
32 // Low-level types and utilities for porting Google Test to various
33 // platforms.  They are subject to change without notice.  DO NOT USE
34 // THEM IN USER CODE.
35
36 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
37 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
38
39 // The user can define the following macros in the build script to
40 // control Google Test's behavior.  If the user doesn't define a macro
41 // in this list, Google Test will define it.
42 //
43 //   GTEST_HAS_CLONE          - Define it to 1/0 to indicate that clone(2)
44 //                              is/isn't available.
45 //   GTEST_HAS_EXCEPTIONS     - Define it to 1/0 to indicate that exceptions
46 //                              are enabled.
47 //   GTEST_HAS_GLOBAL_STRING  - Define it to 1/0 to indicate that ::string
48 //                              is/isn't available (some systems define
49 //                              ::string, which is different to std::string).
50 //   GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
51 //                              is/isn't available (some systems define
52 //                              ::wstring, which is different to std::wstring).
53 //   GTEST_HAS_PTHREAD        - Define it to 1/0 to indicate that <pthread.h>
54 //                              is/isn't available.
55 //   GTEST_HAS_RTTI           - Define it to 1/0 to indicate that RTTI is/isn't
56 //                              enabled.
57 //   GTEST_HAS_STD_WSTRING    - Define it to 1/0 to indicate that
58 //                              std::wstring does/doesn't work (Google Test can
59 //                              be used where std::wstring is unavailable).
60 //   GTEST_HAS_TR1_TUPLE      - Define it to 1/0 to indicate tr1::tuple
61 //                              is/isn't available.
62 //   GTEST_HAS_SEH            - Define it to 1/0 to indicate whether the
63 //                              compiler supports Microsoft's "Structured
64 //                              Exception Handling".
65 //   GTEST_USE_OWN_TR1_TUPLE  - Define it to 1/0 to indicate whether Google
66 //                              Test's own tr1 tuple implementation should be
67 //                              used.  Unused when the user sets
68 //                              GTEST_HAS_TR1_TUPLE to 0.
69 //   GTEST_LINKED_AS_SHARED_LIBRARY
70 //                            - Define to 1 when compiling tests that use
71 //                              Google Test as a shared library (known as
72 //                              DLL on Windows).
73 //   GTEST_CREATE_SHARED_LIBRARY
74 //                            - Define to 1 when compiling Google Test itself
75 //                              as a shared library.
76
77 // This header defines the following utilities:
78 //
79 // Macros indicating the current platform (defined to 1 if compiled on
80 // the given platform; otherwise undefined):
81 //   GTEST_OS_AIX      - IBM AIX
82 //   GTEST_OS_CYGWIN   - Cygwin
83 //   GTEST_OS_HAIKU    - Haiku
84 //   GTEST_OS_LINUX    - Linux
85 //   GTEST_OS_MAC      - Mac OS X
86 //   GTEST_OS_SOLARIS  - Sun Solaris
87 //   GTEST_OS_SYMBIAN  - Symbian
88 //   GTEST_OS_WINDOWS  - Windows (Desktop, MinGW, or Mobile)
89 //     GTEST_OS_WINDOWS_DESKTOP  - Windows Desktop
90 //     GTEST_OS_WINDOWS_MINGW    - MinGW
91 //     GTEST_OS_WINDOWS_MOBILE   - Windows Mobile
92 //   GTEST_OS_ZOS      - z/OS
93 //
94 // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
95 // most stable support.  Since core members of the Google Test project
96 // don't have access to other platforms, support for them may be less
97 // stable.  If you notice any problems on your platform, please notify
98 // googletestframework@googlegroups.com (patches for fixing them are
99 // even more welcome!).
100 //
101 // Note that it is possible that none of the GTEST_OS_* macros are defined.
102 //
103 // Macros indicating available Google Test features (defined to 1 if
104 // the corresponding feature is supported; otherwise undefined):
105 //   GTEST_HAS_COMBINE      - the Combine() function (for value-parameterized
106 //                            tests)
107 //   GTEST_HAS_DEATH_TEST   - death tests
108 //   GTEST_HAS_PARAM_TEST   - value-parameterized tests
109 //   GTEST_HAS_TYPED_TEST   - typed tests
110 //   GTEST_HAS_TYPED_TEST_P - type-parameterized tests
111 //   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used.
112 //   GTEST_USES_SIMPLE_RE   - our own simple regex is used;
113 //                            the above two are mutually exclusive.
114 //   GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
115 //
116 // Macros for basic C++ coding:
117 //   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
118 //   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a
119 //                              variable don't have to be used.
120 //   GTEST_DISALLOW_ASSIGN_   - disables operator=.
121 //   GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
122 //   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.
123 //
124 // Synchronization:
125 //   Mutex, MutexLock, ThreadLocal, GetThreadCount()
126 //                  - synchronization primitives.
127 //   GTEST_IS_THREADSAFE - defined to 1 to indicate that the above
128 //                         synchronization primitives have real implementations
129 //                         and Google Test is thread-safe; or 0 otherwise.
130 //
131 // Template meta programming:
132 //   is_pointer     - as in TR1; needed on Symbian and IBM XL C/C++ only.
133 //
134 // Smart pointers:
135 //   scoped_ptr     - as in TR2.
136 //
137 // Regular expressions:
138 //   RE             - a simple regular expression class using the POSIX
139 //                    Extended Regular Expression syntax.  Not available on
140 //                    Windows.
141 //
142 // Logging:
143 //   GTEST_LOG_()   - logs messages at the specified severity level.
144 //   LogToStderr()  - directs all log messages to stderr.
145 //   FlushInfoLog() - flushes informational log messages.
146 //
147 // Stdout and stderr capturing:
148 //   CaptureStdout()     - starts capturing stdout.
149 //   GetCapturedStdout() - stops capturing stdout and returns the captured
150 //                         string.
151 //   CaptureStderr()     - starts capturing stderr.
152 //   GetCapturedStderr() - stops capturing stderr and returns the captured
153 //                         string.
154 //
155 // Integer types:
156 //   TypeWithSize   - maps an integer to a int type.
157 //   Int32, UInt32, Int64, UInt64, TimeInMillis
158 //                  - integers of known sizes.
159 //   BiggestInt     - the biggest signed integer type.
160 //
161 // Command-line utilities:
162 //   GTEST_FLAG()       - references a flag.
163 //   GTEST_DECLARE_*()  - declares a flag.
164 //   GTEST_DEFINE_*()   - defines a flag.
165 //   GetArgvs()         - returns the command line as a vector of strings.
166 //
167 // Environment variable utilities:
168 //   GetEnv()             - gets the value of an environment variable.
169 //   BoolFromGTestEnv()   - parses a bool environment variable.
170 //   Int32FromGTestEnv()  - parses an Int32 environment variable.
171 //   StringFromGTestEnv() - parses a string environment variable.
172
173 #include <stddef.h>  // For ptrdiff_t
174 #include <stdlib.h>
175 #include <stdio.h>
176 #include <string.h>
177 #ifndef _WIN32_WCE
178 #include <sys/stat.h>
179 #endif  // !_WIN32_WCE
180
181 #include <iostream>  // NOLINT
182 #include <sstream>  // NOLINT
183 #include <string>  // NOLINT
184
185 #define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
186 #define GTEST_FLAG_PREFIX_ "gtest_"
187 #define GTEST_FLAG_PREFIX_DASH_ "gtest-"
188 #define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
189 #define GTEST_NAME_ "Google Test"
190 #define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/"
191
192 // Determines the version of gcc that is used to compile this.
193 #ifdef __GNUC__
194 // 40302 means version 4.3.2.
195 #define GTEST_GCC_VER_ \
196     (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
197 #endif  // __GNUC__
198
199 // Determines the platform on which Google Test is compiled.
200 #ifdef __CYGWIN__
201 #define GTEST_OS_CYGWIN 1
202 #elif defined __SYMBIAN32__
203 #define GTEST_OS_SYMBIAN 1
204 #elif defined _WIN32
205 #define GTEST_OS_WINDOWS 1
206 #ifdef _WIN32_WCE
207 #define GTEST_OS_WINDOWS_MOBILE 1
208 #elif defined(__MINGW__) || defined(__MINGW32__)
209 #define GTEST_OS_WINDOWS_MINGW 1
210 #else
211 #define GTEST_OS_WINDOWS_DESKTOP 1
212 #endif  // _WIN32_WCE
213 #elif defined __APPLE__
214 #define GTEST_OS_MAC 1
215 #elif defined __linux__
216 #define GTEST_OS_LINUX 1
217 #elif defined __MVS__
218 #define GTEST_OS_ZOS 1
219 #elif defined(__sun) && defined(__SVR4)
220 #define GTEST_OS_SOLARIS 1
221 #elif defined(_AIX)
222 #define GTEST_OS_AIX 1
223 #elif defined(__HAIKU__)
224 #define GTEST_OS_HAIKU 1
225 #endif  // __CYGWIN__
226
227 #if GTEST_OS_CYGWIN || GTEST_OS_HAIKU || GTEST_OS_LINUX || GTEST_OS_MAC || \
228     GTEST_OS_SYMBIAN || GTEST_OS_SOLARIS || GTEST_OS_AIX
229
230 // On some platforms, <regex.h> needs someone to define size_t, and
231 // won't compile otherwise.  We can #include it here as we already
232 // included <stdlib.h>, which is guaranteed to define size_t through
233 // <stddef.h>.
234 #include <regex.h>  // NOLINT
235 #include <strings.h>  // NOLINT
236 #include <sys/types.h>  // NOLINT
237 #include <time.h>  // NOLINT
238 #include <unistd.h>  // NOLINT
239
240 #define GTEST_USES_POSIX_RE 1
241
242 #elif GTEST_OS_WINDOWS
243
244 #if !GTEST_OS_WINDOWS_MOBILE
245 #include <direct.h>  // NOLINT
246 #include <io.h>  // NOLINT
247 #endif
248
249 // <regex.h> is not available on Windows.  Use our own simple regex
250 // implementation instead.
251 #define GTEST_USES_SIMPLE_RE 1
252
253 #else
254
255 // <regex.h> may not be available on this platform.  Use our own
256 // simple regex implementation instead.
257 #define GTEST_USES_SIMPLE_RE 1
258
259 #endif  // GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC ||
260         // GTEST_OS_SYMBIAN || GTEST_OS_SOLARIS || GTEST_OS_AIX
261
262 #ifndef GTEST_HAS_EXCEPTIONS
263 // The user didn't tell us whether exceptions are enabled, so we need
264 // to figure it out.
265 #if defined(_MSC_VER) || defined(__BORLANDC__)
266 // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
267 // macro to enable exceptions, so we'll do the same.
268 // Assumes that exceptions are enabled by default.
269 #ifndef _HAS_EXCEPTIONS
270 #define _HAS_EXCEPTIONS 1
271 #endif  // _HAS_EXCEPTIONS
272 #define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
273 #elif defined(__GNUC__) && __EXCEPTIONS
274 // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
275 #define GTEST_HAS_EXCEPTIONS 1
276 #elif defined(__SUNPRO_CC)
277 // Sun Pro CC supports exceptions.  However, there is no compile-time way of
278 // detecting whether they are enabled or not.  Therefore, we assume that
279 // they are enabled unless the user tells us otherwise.
280 #define GTEST_HAS_EXCEPTIONS 1
281 #elif defined(__IBMCPP__) && __EXCEPTIONS
282 // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
283 #define GTEST_HAS_EXCEPTIONS 1
284 #else
285 // For other compilers, we assume exceptions are disabled to be
286 // conservative.
287 #define GTEST_HAS_EXCEPTIONS 0
288 #endif  // defined(_MSC_VER) || defined(__BORLANDC__)
289 #endif  // GTEST_HAS_EXCEPTIONS
290
291 #if !defined(GTEST_HAS_STD_STRING)
292 // Even though we don't use this macro any longer, we keep it in case
293 // some clients still depend on it.
294 #define GTEST_HAS_STD_STRING 1
295 #elif !GTEST_HAS_STD_STRING
296 // The user told us that ::std::string isn't available.
297 #error "Google Test cannot be used where ::std::string isn't available."
298 #endif  // !defined(GTEST_HAS_STD_STRING)
299
300 #ifndef GTEST_HAS_GLOBAL_STRING
301 // The user didn't tell us whether ::string is available, so we need
302 // to figure it out.
303
304 #define GTEST_HAS_GLOBAL_STRING 0
305
306 #endif  // GTEST_HAS_GLOBAL_STRING
307
308 #ifndef GTEST_HAS_STD_WSTRING
309 // The user didn't tell us whether ::std::wstring is available, so we need
310 // to figure it out.
311 // TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
312 //   is available.
313
314 // Cygwin 1.5 and below doesn't support ::std::wstring.
315 // Cygwin 1.7 might add wstring support; this should be updated when clear.
316 // Solaris' libc++ doesn't support it either.
317 // Minix currently doesn't support it either.
318 #define GTEST_HAS_STD_WSTRING (!(GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || GTEST_OS_HAIKU || defined(_MINIX)))
319
320 #endif  // GTEST_HAS_STD_WSTRING
321
322 #ifndef GTEST_HAS_GLOBAL_WSTRING
323 // The user didn't tell us whether ::wstring is available, so we need
324 // to figure it out.
325 #define GTEST_HAS_GLOBAL_WSTRING \
326     (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
327 #endif  // GTEST_HAS_GLOBAL_WSTRING
328
329 // Determines whether RTTI is available.
330 #ifndef GTEST_HAS_RTTI
331 // The user didn't tell us whether RTTI is enabled, so we need to
332 // figure it out.
333
334 #ifdef _MSC_VER
335
336 #ifdef _CPPRTTI  // MSVC defines this macro iff RTTI is enabled.
337 #define GTEST_HAS_RTTI 1
338 #else
339 #define GTEST_HAS_RTTI 0
340 #endif
341
342 // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
343 #elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
344
345 #ifdef __GXX_RTTI
346 #define GTEST_HAS_RTTI 1
347 #else
348 #define GTEST_HAS_RTTI 0
349 #endif  // __GXX_RTTI
350
351 // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
352 // both the typeid and dynamic_cast features are present.
353 #elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
354
355 #ifdef __RTTI_ALL__
356 #define GTEST_HAS_RTTI 1
357 #else
358 #define GTEST_HAS_RTTI 0
359 #endif
360
361 #else
362
363 // For all other compilers, we assume RTTI is enabled.
364 #define GTEST_HAS_RTTI 1
365
366 #endif  // _MSC_VER
367
368 #endif  // GTEST_HAS_RTTI
369
370 // It's this header's responsibility to #include <typeinfo> when RTTI
371 // is enabled.
372 #if GTEST_HAS_RTTI
373 #include <typeinfo>
374 #endif
375
376 // Determines whether Google Test can use the pthreads library.
377 #ifndef GTEST_HAS_PTHREAD
378 // The user didn't tell us explicitly, so we assume pthreads support is
379 // available on Linux and Mac.
380 //
381 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
382 // to your compiler flags.
383 #define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC)
384 #endif  // GTEST_HAS_PTHREAD
385
386 // Determines whether Google Test can use tr1/tuple.  You can define
387 // this macro to 0 to prevent Google Test from using tuple (any
388 // feature depending on tuple with be disabled in this mode).
389 #ifndef GTEST_HAS_TR1_TUPLE
390 // The user didn't tell us not to do it, so we assume it's OK.
391 #define GTEST_HAS_TR1_TUPLE 1
392 #endif  // GTEST_HAS_TR1_TUPLE
393
394 // Determines whether Google Test's own tr1 tuple implementation
395 // should be used.
396 #ifndef GTEST_USE_OWN_TR1_TUPLE
397 // The user didn't tell us, so we need to figure it out.
398
399 // We use our own TR1 tuple if we aren't sure the user has an
400 // implementation of it already.  At this time, GCC 4.0.0+ and MSVC
401 // 2010 are the only mainstream compilers that come with a TR1 tuple
402 // implementation.  NVIDIA's CUDA NVCC compiler pretends to be GCC by
403 // defining __GNUC__ and friends, but cannot compile GCC's tuple
404 // implementation.  MSVC 2008 (9.0) provides TR1 tuple in a 323 MB
405 // Feature Pack download, which we cannot assume the user has.
406 #if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000)) \
407     || _MSC_VER >= 1600
408 #define GTEST_USE_OWN_TR1_TUPLE 0
409 #else
410 #define GTEST_USE_OWN_TR1_TUPLE 1
411 #endif
412
413 #endif  // GTEST_USE_OWN_TR1_TUPLE
414
415 // To avoid conditional compilation everywhere, we make it
416 // gtest-port.h's responsibility to #include the header implementing
417 // tr1/tuple.
418 #if GTEST_HAS_TR1_TUPLE
419
420 #if GTEST_USE_OWN_TR1_TUPLE
421 #include <gtest/internal/gtest-tuple.h>
422 #elif GTEST_OS_SYMBIAN
423
424 // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
425 // use STLport's tuple implementation, which unfortunately doesn't
426 // work as the copy of STLport distributed with Symbian is incomplete.
427 // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
428 // use its own tuple implementation.
429 #ifdef BOOST_HAS_TR1_TUPLE
430 #undef BOOST_HAS_TR1_TUPLE
431 #endif  // BOOST_HAS_TR1_TUPLE
432
433 // This prevents <boost/tr1/detail/config.hpp>, which defines
434 // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
435 #define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
436 #include <tuple>
437
438 #elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
439 // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header.  This does
440 // not conform to the TR1 spec, which requires the header to be <tuple>.
441
442 #if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
443 // Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
444 // which is #included by <tr1/tuple>, to not compile when RTTI is
445 // disabled.  _TR1_FUNCTIONAL is the header guard for
446 // <tr1/functional>.  Hence the following #define is a hack to prevent
447 // <tr1/functional> from being included.
448 #define _TR1_FUNCTIONAL 1
449 #include <tr1/tuple>
450 #undef _TR1_FUNCTIONAL  // Allows the user to #include
451                         // <tr1/functional> if he chooses to.
452 #else
453 #include <tr1/tuple>  // NOLINT
454 #endif  // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
455
456 #else
457 // If the compiler is not GCC 4.0+, we assume the user is using a
458 // spec-conforming TR1 implementation.
459 #include <tuple>  // NOLINT
460 #endif  // GTEST_USE_OWN_TR1_TUPLE
461
462 #endif  // GTEST_HAS_TR1_TUPLE
463
464 // Determines whether clone(2) is supported.
465 // Usually it will only be available on Linux, excluding
466 // Linux on the Itanium architecture.
467 // Also see http://linux.die.net/man/2/clone.
468 #ifndef GTEST_HAS_CLONE
469 // The user didn't tell us, so we need to figure it out.
470
471 #if GTEST_OS_LINUX && !defined(__ia64__)
472 #define GTEST_HAS_CLONE 1
473 #else
474 #define GTEST_HAS_CLONE 0
475 #endif  // GTEST_OS_LINUX && !defined(__ia64__)
476
477 #endif  // GTEST_HAS_CLONE
478
479 // Determines whether to support stream redirection. This is used to test
480 // output correctness and to implement death tests.
481 #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
482 #define GTEST_HAS_STREAM_REDIRECTION_ 1
483 #endif  // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
484
485 // Determines whether to support death tests.
486 // Google Test does not support death tests for VC 7.1 and earlier as
487 // abort() in a VC 7.1 application compiled as GUI in debug config
488 // pops up a dialog window that cannot be suppressed programmatically.
489 #if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
490      (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
491      GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX)
492 #define GTEST_HAS_DEATH_TEST 1
493 #include <vector>  // NOLINT
494 #endif
495
496 // We don't support MSVC 7.1 with exceptions disabled now.  Therefore
497 // all the compilers we care about are adequate for supporting
498 // value-parameterized tests.
499 #define GTEST_HAS_PARAM_TEST 1
500
501 // Determines whether to support type-driven tests.
502
503 // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
504 // Sun Pro CC, and IBM Visual Age support.
505 #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
506     defined(__IBMCPP__)
507 #define GTEST_HAS_TYPED_TEST 1
508 #define GTEST_HAS_TYPED_TEST_P 1
509 #endif
510
511 // Determines whether to support Combine(). This only makes sense when
512 // value-parameterized tests are enabled.  The implementation doesn't
513 // work on Sun Studio since it doesn't understand templated conversion
514 // operators.
515 #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
516 #define GTEST_HAS_COMBINE 1
517 #endif
518
519 // Determines whether the system compiler uses UTF-16 for encoding wide strings.
520 #define GTEST_WIDE_STRING_USES_UTF16_ \
521     (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
522
523 // Defines some utility macros.
524
525 // The GNU compiler emits a warning if nested "if" statements are followed by
526 // an "else" statement and braces are not used to explicitly disambiguate the
527 // "else" binding.  This leads to problems with code like:
528 //
529 //   if (gate)
530 //     ASSERT_*(condition) << "Some message";
531 //
532 // The "switch (0) case 0:" idiom is used to suppress this.
533 #ifdef __INTEL_COMPILER
534 #define GTEST_AMBIGUOUS_ELSE_BLOCKER_
535 #else
536 #define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0:  // NOLINT
537 #endif
538
539 // Use this annotation at the end of a struct/class definition to
540 // prevent the compiler from optimizing away instances that are never
541 // used.  This is useful when all interesting logic happens inside the
542 // c'tor and / or d'tor.  Example:
543 //
544 //   struct Foo {
545 //     Foo() { ... }
546 //   } GTEST_ATTRIBUTE_UNUSED_;
547 //
548 // Also use it after a variable or parameter declaration to tell the
549 // compiler the variable/parameter does not have to be used.
550 #if defined(__GNUC__) && !defined(COMPILER_ICC)
551 #define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
552 #else
553 #define GTEST_ATTRIBUTE_UNUSED_
554 #endif
555
556 // A macro to disallow operator=
557 // This should be used in the private: declarations for a class.
558 #define GTEST_DISALLOW_ASSIGN_(type)\
559   void operator=(type const &)
560
561 // A macro to disallow copy constructor and operator=
562 // This should be used in the private: declarations for a class.
563 #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
564   type(type const &);\
565   GTEST_DISALLOW_ASSIGN_(type)
566
567 // Tell the compiler to warn about unused return values for functions declared
568 // with this macro.  The macro should be used on function declarations
569 // following the argument list:
570 //
571 //   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
572 #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
573 #define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
574 #else
575 #define GTEST_MUST_USE_RESULT_
576 #endif  // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
577
578 // Determine whether the compiler supports Microsoft's Structured Exception
579 // Handling.  This is supported by several Windows compilers but generally
580 // does not exist on any other system.
581 #ifndef GTEST_HAS_SEH
582 // The user didn't tell us, so we need to figure it out.
583
584 #if defined(_MSC_VER) || defined(__BORLANDC__)
585 // These two compilers are known to support SEH.
586 #define GTEST_HAS_SEH 1
587 #else
588 // Assume no SEH.
589 #define GTEST_HAS_SEH 0
590 #endif
591
592 #endif  // GTEST_HAS_SEH
593
594 #ifdef _MSC_VER
595
596 #if GTEST_LINKED_AS_SHARED_LIBRARY
597 #define GTEST_API_ __declspec(dllimport)
598 #elif GTEST_CREATE_SHARED_LIBRARY
599 #define GTEST_API_ __declspec(dllexport)
600 #endif
601
602 #endif  // _MSC_VER
603
604 #ifndef GTEST_API_
605 #define GTEST_API_
606 #endif
607
608 namespace testing {
609
610 class Message;
611
612 namespace internal {
613
614 class String;
615
616 typedef ::std::stringstream StrStream;
617
618 // A helper for suppressing warnings on constant condition.  It just
619 // returns 'condition'.
620 GTEST_API_ bool IsTrue(bool condition);
621
622 // Defines scoped_ptr.
623
624 // This implementation of scoped_ptr is PARTIAL - it only contains
625 // enough stuff to satisfy Google Test's need.
626 template <typename T>
627 class scoped_ptr {
628  public:
629   typedef T element_type;
630
631   explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
632   ~scoped_ptr() { reset(); }
633
634   T& operator*() const { return *ptr_; }
635   T* operator->() const { return ptr_; }
636   T* get() const { return ptr_; }
637
638   T* release() {
639     T* const ptr = ptr_;
640     ptr_ = NULL;
641     return ptr;
642   }
643
644   void reset(T* p = NULL) {
645     if (p != ptr_) {
646       if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
647         delete ptr_;
648       }
649       ptr_ = p;
650     }
651   }
652  private:
653   T* ptr_;
654
655   GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
656 };
657
658 // Defines RE.
659
660 // A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
661 // Regular Expression syntax.
662 class GTEST_API_ RE {
663  public:
664   // A copy constructor is required by the Standard to initialize object
665   // references from r-values.
666   RE(const RE& other) { Init(other.pattern()); }
667
668   // Constructs an RE from a string.
669   RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
670
671 #if GTEST_HAS_GLOBAL_STRING
672   RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
673 #endif  // GTEST_HAS_GLOBAL_STRING
674
675   RE(const char* regex) { Init(regex); }  // NOLINT
676   ~RE();
677
678   // Returns the string representation of the regex.
679   const char* pattern() const { return pattern_; }
680
681   // FullMatch(str, re) returns true iff regular expression re matches
682   // the entire str.
683   // PartialMatch(str, re) returns true iff regular expression re
684   // matches a substring of str (including str itself).
685   //
686   // TODO(wan@google.com): make FullMatch() and PartialMatch() work
687   // when str contains NUL characters.
688   static bool FullMatch(const ::std::string& str, const RE& re) {
689     return FullMatch(str.c_str(), re);
690   }
691   static bool PartialMatch(const ::std::string& str, const RE& re) {
692     return PartialMatch(str.c_str(), re);
693   }
694
695 #if GTEST_HAS_GLOBAL_STRING
696   static bool FullMatch(const ::string& str, const RE& re) {
697     return FullMatch(str.c_str(), re);
698   }
699   static bool PartialMatch(const ::string& str, const RE& re) {
700     return PartialMatch(str.c_str(), re);
701   }
702 #endif  // GTEST_HAS_GLOBAL_STRING
703
704   static bool FullMatch(const char* str, const RE& re);
705   static bool PartialMatch(const char* str, const RE& re);
706
707  private:
708   void Init(const char* regex);
709
710   // We use a const char* instead of a string, as Google Test may be used
711   // where string is not available.  We also do not use Google Test's own
712   // String type here, in order to simplify dependencies between the
713   // files.
714   const char* pattern_;
715   bool is_valid_;
716 #if GTEST_USES_POSIX_RE
717   regex_t full_regex_;     // For FullMatch().
718   regex_t partial_regex_;  // For PartialMatch().
719 #else  // GTEST_USES_SIMPLE_RE
720   const char* full_pattern_;  // For FullMatch();
721 #endif
722
723   GTEST_DISALLOW_ASSIGN_(RE);
724 };
725
726 // Defines logging utilities:
727 //   GTEST_LOG_(severity) - logs messages at the specified severity level. The
728 //                          message itself is streamed into the macro.
729 //   LogToStderr()  - directs all log messages to stderr.
730 //   FlushInfoLog() - flushes informational log messages.
731
732 enum GTestLogSeverity {
733   GTEST_INFO,
734   GTEST_WARNING,
735   GTEST_ERROR,
736   GTEST_FATAL
737 };
738
739 // Formats log entry severity, provides a stream object for streaming the
740 // log message, and terminates the message with a newline when going out of
741 // scope.
742 class GTEST_API_ GTestLog {
743  public:
744   GTestLog(GTestLogSeverity severity, const char* file, int line);
745
746   // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
747   ~GTestLog();
748
749   ::std::ostream& GetStream() { return ::std::cerr; }
750
751  private:
752   const GTestLogSeverity severity_;
753
754   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
755 };
756
757 #define GTEST_LOG_(severity) \
758     ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
759                                   __FILE__, __LINE__).GetStream()
760
761 inline void LogToStderr() {}
762 inline void FlushInfoLog() { fflush(NULL); }
763
764 // INTERNAL IMPLEMENTATION - DO NOT USE.
765 //
766 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
767 // is not satisfied.
768 //  Synopsys:
769 //    GTEST_CHECK_(boolean_condition);
770 //     or
771 //    GTEST_CHECK_(boolean_condition) << "Additional message";
772 //
773 //    This checks the condition and if the condition is not satisfied
774 //    it prints message about the condition violation, including the
775 //    condition itself, plus additional message streamed into it, if any,
776 //    and then it aborts the program. It aborts the program irrespective of
777 //    whether it is built in the debug mode or not.
778 #define GTEST_CHECK_(condition) \
779     GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
780     if (::testing::internal::IsTrue(condition)) \
781       ; \
782     else \
783       GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
784
785 // An all-mode assert to verify that the given POSIX-style function
786 // call returns 0 (indicating success).  Known limitation: this
787 // doesn't expand to a balanced 'if' statement, so enclose the macro
788 // in {} if you need to use it as the only statement in an 'if'
789 // branch.
790 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
791   if (const int gtest_error = (posix_call)) \
792     GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
793                       << gtest_error
794
795 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
796 //
797 // Downcasts the pointer of type Base to Derived.
798 // Derived must be a subclass of Base. The parameter MUST
799 // point to a class of type Derived, not any subclass of it.
800 // When RTTI is available, the function performs a runtime
801 // check to enforce this.
802 template <class Derived, class Base>
803 Derived* CheckedDowncastToActualType(Base* base) {
804 #if GTEST_HAS_RTTI
805   GTEST_CHECK_(typeid(*base) == typeid(Derived));
806   return dynamic_cast<Derived*>(base);  // NOLINT
807 #else
808   return static_cast<Derived*>(base);  // Poor man's downcast.
809 #endif
810 }
811
812 #if GTEST_HAS_STREAM_REDIRECTION_
813
814 // Defines the stderr capturer:
815 //   CaptureStdout     - starts capturing stdout.
816 //   GetCapturedStdout - stops capturing stdout and returns the captured string.
817 //   CaptureStderr     - starts capturing stderr.
818 //   GetCapturedStderr - stops capturing stderr and returns the captured string.
819 //
820 GTEST_API_ void CaptureStdout();
821 GTEST_API_ String GetCapturedStdout();
822 GTEST_API_ void CaptureStderr();
823 GTEST_API_ String GetCapturedStderr();
824
825 #endif  // GTEST_HAS_STREAM_REDIRECTION_
826
827
828 #if GTEST_HAS_DEATH_TEST
829
830 // A copy of all command line arguments.  Set by InitGoogleTest().
831 extern ::std::vector<String> g_argvs;
832
833 // GTEST_HAS_DEATH_TEST implies we have ::std::string.
834 const ::std::vector<String>& GetArgvs();
835
836 #endif  // GTEST_HAS_DEATH_TEST
837
838 // Defines synchronization primitives.
839
840 #if GTEST_HAS_PTHREAD
841
842 // Sleeps for (roughly) n milli-seconds.  This function is only for
843 // testing Google Test's own constructs.  Don't use it in user tests,
844 // either directly or indirectly.
845 inline void SleepMilliseconds(int n) {
846   const timespec time = {
847     0,                  // 0 seconds.
848     n * 1000L * 1000L,  // And n ms.
849   };
850   nanosleep(&time, NULL);
851 }
852
853 // Allows a controller thread to pause execution of newly created
854 // threads until notified.  Instances of this class must be created
855 // and destroyed in the controller thread.
856 //
857 // This class is only for testing Google Test's own constructs. Do not
858 // use it in user tests, either directly or indirectly.
859 class Notification {
860  public:
861   Notification() : notified_(false) {}
862
863   // Notifies all threads created with this notification to start. Must
864   // be called from the controller thread.
865   void Notify() { notified_ = true; }
866
867   // Blocks until the controller thread notifies. Must be called from a test
868   // thread.
869   void WaitForNotification() {
870     while(!notified_) {
871       SleepMilliseconds(10);
872     }
873   }
874
875  private:
876   volatile bool notified_;
877
878   GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
879 };
880
881 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
882 // Consequently, it cannot select a correct instantiation of ThreadWithParam
883 // in order to call its Run(). Introducing ThreadWithParamBase as a
884 // non-templated base class for ThreadWithParam allows us to bypass this
885 // problem.
886 class ThreadWithParamBase {
887  public:
888   virtual ~ThreadWithParamBase() {}
889   virtual void Run() = 0;
890 };
891
892 // pthread_create() accepts a pointer to a function type with the C linkage.
893 // According to the Standard (7.5/1), function types with different linkages
894 // are different even if they are otherwise identical.  Some compilers (for
895 // example, SunStudio) treat them as different types.  Since class methods
896 // cannot be defined with C-linkage we need to define a free C-function to
897 // pass into pthread_create().
898 extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
899   static_cast<ThreadWithParamBase*>(thread)->Run();
900   return NULL;
901 }
902
903 // Helper class for testing Google Test's multi-threading constructs.
904 // To use it, write:
905 //
906 //   void ThreadFunc(int param) { /* Do things with param */ }
907 //   Notification thread_can_start;
908 //   ...
909 //   // The thread_can_start parameter is optional; you can supply NULL.
910 //   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
911 //   thread_can_start.Notify();
912 //
913 // These classes are only for testing Google Test's own constructs. Do
914 // not use them in user tests, either directly or indirectly.
915 template <typename T>
916 class ThreadWithParam : public ThreadWithParamBase {
917  public:
918   typedef void (*UserThreadFunc)(T);
919
920   ThreadWithParam(
921       UserThreadFunc func, T param, Notification* thread_can_start)
922       : func_(func),
923         param_(param),
924         thread_can_start_(thread_can_start),
925         finished_(false) {
926     ThreadWithParamBase* const base = this;
927     // The thread can be created only after all fields except thread_
928     // have been initialized.
929     GTEST_CHECK_POSIX_SUCCESS_(
930         pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
931   }
932   ~ThreadWithParam() { Join(); }
933
934   void Join() {
935     if (!finished_) {
936       GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
937       finished_ = true;
938     }
939   }
940
941   virtual void Run() {
942     if (thread_can_start_ != NULL)
943       thread_can_start_->WaitForNotification();
944     func_(param_);
945   }
946
947  private:
948   const UserThreadFunc func_;  // User-supplied thread function.
949   const T param_;  // User-supplied parameter to the thread function.
950   // When non-NULL, used to block execution until the controller thread
951   // notifies.
952   Notification* const thread_can_start_;
953   bool finished_;  // true iff we know that the thread function has finished.
954   pthread_t thread_;  // The native thread object.
955
956   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
957 };
958
959 // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
960 // true.
961 #include <pthread.h>
962
963 // MutexBase and Mutex implement mutex on pthreads-based platforms. They
964 // are used in conjunction with class MutexLock:
965 //
966 //   Mutex mutex;
967 //   ...
968 //   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the end
969 //                            // of the current scope.
970 //
971 // MutexBase implements behavior for both statically and dynamically
972 // allocated mutexes.  Do not use MutexBase directly.  Instead, write
973 // the following to define a static mutex:
974 //
975 //   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
976 //
977 // You can forward declare a static mutex like this:
978 //
979 //   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
980 //
981 // To create a dynamic mutex, just define an object of type Mutex.
982 class MutexBase {
983  public:
984   // Acquires this mutex.
985   void Lock() {
986     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
987     owner_ = pthread_self();
988   }
989
990   // Releases this mutex.
991   void Unlock() {
992     // We don't protect writing to owner_ here, as it's the caller's
993     // responsibility to ensure that the current thread holds the
994     // mutex when this is called.
995     owner_ = 0;
996     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
997   }
998
999   // Does nothing if the current thread holds the mutex. Otherwise, crashes
1000   // with high probability.
1001   void AssertHeld() const {
1002     GTEST_CHECK_(owner_ == pthread_self())
1003         << "The current thread is not holding the mutex @" << this;
1004   }
1005
1006   // A static mutex may be used before main() is entered.  It may even
1007   // be used before the dynamic initialization stage.  Therefore we
1008   // must be able to initialize a static mutex object at link time.
1009   // This means MutexBase has to be a POD and its member variables
1010   // have to be public.
1011  public:
1012   pthread_mutex_t mutex_;  // The underlying pthread mutex.
1013   pthread_t owner_;  // The thread holding the mutex; 0 means no one holds it.
1014 };
1015
1016 // Forward-declares a static mutex.
1017 #define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1018     extern ::testing::internal::MutexBase mutex
1019
1020 // Defines and statically (i.e. at link time) initializes a static mutex.
1021 #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1022     ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, 0 }
1023
1024 // The Mutex class can only be used for mutexes created at runtime. It
1025 // shares its API with MutexBase otherwise.
1026 class Mutex : public MutexBase {
1027  public:
1028   Mutex() {
1029     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
1030     owner_ = 0;
1031   }
1032   ~Mutex() {
1033     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
1034   }
1035
1036  private:
1037   GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1038 };
1039
1040 // We cannot name this class MutexLock as the ctor declaration would
1041 // conflict with a macro named MutexLock, which is defined on some
1042 // platforms.  Hence the typedef trick below.
1043 class GTestMutexLock {
1044  public:
1045   explicit GTestMutexLock(MutexBase* mutex)
1046       : mutex_(mutex) { mutex_->Lock(); }
1047
1048   ~GTestMutexLock() { mutex_->Unlock(); }
1049
1050  private:
1051   MutexBase* const mutex_;
1052
1053   GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1054 };
1055
1056 typedef GTestMutexLock MutexLock;
1057
1058 // Helpers for ThreadLocal.
1059
1060 // pthread_key_create() requires DeleteThreadLocalValue() to have
1061 // C-linkage.  Therefore it cannot be templatized to access
1062 // ThreadLocal<T>.  Hence the need for class
1063 // ThreadLocalValueHolderBase.
1064 class ThreadLocalValueHolderBase {
1065  public:
1066   virtual ~ThreadLocalValueHolderBase() {}
1067 };
1068
1069 // Called by pthread to delete thread-local data stored by
1070 // pthread_setspecific().
1071 extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
1072   delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
1073 }
1074
1075 // Implements thread-local storage on pthreads-based systems.
1076 //
1077 //   // Thread 1
1078 //   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.
1079 //
1080 //   // Thread 2
1081 //   tl.set(150);  // Changes the value for thread 2 only.
1082 //   EXPECT_EQ(150, tl.get());
1083 //
1084 //   // Thread 1
1085 //   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.
1086 //   tl.set(200);
1087 //   EXPECT_EQ(200, tl.get());
1088 //
1089 // The template type argument T must have a public copy constructor.
1090 // In addition, the default ThreadLocal constructor requires T to have
1091 // a public default constructor.
1092 //
1093 // An object managed for a thread by a ThreadLocal instance is deleted
1094 // when the thread exits.  Or, if the ThreadLocal instance dies in
1095 // that thread, when the ThreadLocal dies.  It's the user's
1096 // responsibility to ensure that all other threads using a ThreadLocal
1097 // have exited when it dies, or the per-thread objects for those
1098 // threads will not be deleted.
1099 //
1100 // Google Test only uses global ThreadLocal objects.  That means they
1101 // will die after main() has returned.  Therefore, no per-thread
1102 // object managed by Google Test will be leaked as long as all threads
1103 // using Google Test have exited when main() returns.
1104 template <typename T>
1105 class ThreadLocal {
1106  public:
1107   ThreadLocal() : key_(CreateKey()),
1108                   default_() {}
1109   explicit ThreadLocal(const T& value) : key_(CreateKey()),
1110                                          default_(value) {}
1111
1112   ~ThreadLocal() {
1113     // Destroys the managed object for the current thread, if any.
1114     DeleteThreadLocalValue(pthread_getspecific(key_));
1115
1116     // Releases resources associated with the key.  This will *not*
1117     // delete managed objects for other threads.
1118     GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
1119   }
1120
1121   T* pointer() { return GetOrCreateValue(); }
1122   const T* pointer() const { return GetOrCreateValue(); }
1123   const T& get() const { return *pointer(); }
1124   void set(const T& value) { *pointer() = value; }
1125
1126  private:
1127   // Holds a value of type T.
1128   class ValueHolder : public ThreadLocalValueHolderBase {
1129    public:
1130     explicit ValueHolder(const T& value) : value_(value) {}
1131
1132     T* pointer() { return &value_; }
1133
1134    private:
1135     T value_;
1136     GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1137   };
1138
1139   static pthread_key_t CreateKey() {
1140     pthread_key_t key;
1141     // When a thread exits, DeleteThreadLocalValue() will be called on
1142     // the object managed for that thread.
1143     GTEST_CHECK_POSIX_SUCCESS_(
1144         pthread_key_create(&key, &DeleteThreadLocalValue));
1145     return key;
1146   }
1147
1148   T* GetOrCreateValue() const {
1149     ThreadLocalValueHolderBase* const holder =
1150         static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
1151     if (holder != NULL) {
1152       return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
1153     }
1154
1155     ValueHolder* const new_holder = new ValueHolder(default_);
1156     ThreadLocalValueHolderBase* const holder_base = new_holder;
1157     GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
1158     return new_holder->pointer();
1159   }
1160
1161   // A key pthreads uses for looking up per-thread values.
1162   const pthread_key_t key_;
1163   const T default_;  // The default value for each thread.
1164
1165   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1166 };
1167
1168 #define GTEST_IS_THREADSAFE 1
1169
1170 #else  // GTEST_HAS_PTHREAD
1171
1172 // A dummy implementation of synchronization primitives (mutex, lock,
1173 // and thread-local variable).  Necessary for compiling Google Test where
1174 // mutex is not supported - using Google Test in multiple threads is not
1175 // supported on such platforms.
1176
1177 class Mutex {
1178  public:
1179   Mutex() {}
1180   void AssertHeld() const {}
1181 };
1182
1183 #define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1184   extern ::testing::internal::Mutex mutex
1185
1186 #define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
1187
1188 class GTestMutexLock {
1189  public:
1190   explicit GTestMutexLock(Mutex*) {}  // NOLINT
1191 };
1192
1193 typedef GTestMutexLock MutexLock;
1194
1195 template <typename T>
1196 class ThreadLocal {
1197  public:
1198   ThreadLocal() : value_() {}
1199   explicit ThreadLocal(const T& value) : value_(value) {}
1200   T* pointer() { return &value_; }
1201   const T* pointer() const { return &value_; }
1202   const T& get() const { return value_; }
1203   void set(const T& value) { value_ = value; }
1204  private:
1205   T value_;
1206 };
1207
1208 // The above synchronization primitives have dummy implementations.
1209 // Therefore Google Test is not thread-safe.
1210 #define GTEST_IS_THREADSAFE 0
1211
1212 #endif  // GTEST_HAS_PTHREAD
1213
1214 // Returns the number of threads running in the process, or 0 to indicate that
1215 // we cannot detect it.
1216 GTEST_API_ size_t GetThreadCount();
1217
1218 // Passing non-POD classes through ellipsis (...) crashes the ARM
1219 // compiler and generates a warning in Sun Studio.  The Nokia Symbian
1220 // and the IBM XL C/C++ compiler try to instantiate a copy constructor
1221 // for objects passed through ellipsis (...), failing for uncopyable
1222 // objects.  We define this to ensure that only POD is passed through
1223 // ellipsis on these systems.
1224 #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC)
1225 // We lose support for NULL detection where the compiler doesn't like
1226 // passing non-POD classes through ellipsis (...).
1227 #define GTEST_ELLIPSIS_NEEDS_POD_ 1
1228 #else
1229 #define GTEST_CAN_COMPARE_NULL 1
1230 #endif
1231
1232 // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
1233 // const T& and const T* in a function template.  These compilers
1234 // _can_ decide between class template specializations for T and T*,
1235 // so a tr1::type_traits-like is_pointer works.
1236 #if defined(__SYMBIAN32__) || defined(__IBMCPP__)
1237 #define GTEST_NEEDS_IS_POINTER_ 1
1238 #endif
1239
1240 template <bool bool_value>
1241 struct bool_constant {
1242   typedef bool_constant<bool_value> type;
1243   static const bool value = bool_value;
1244 };
1245 template <bool bool_value> const bool bool_constant<bool_value>::value;
1246
1247 typedef bool_constant<false> false_type;
1248 typedef bool_constant<true> true_type;
1249
1250 template <typename T>
1251 struct is_pointer : public false_type {};
1252
1253 template <typename T>
1254 struct is_pointer<T*> : public true_type {};
1255
1256 #if GTEST_OS_WINDOWS
1257 #define GTEST_PATH_SEP_ "\\"
1258 #define GTEST_HAS_ALT_PATH_SEP_ 1
1259 // The biggest signed integer type the compiler supports.
1260 typedef __int64 BiggestInt;
1261 #else
1262 #define GTEST_PATH_SEP_ "/"
1263 #define GTEST_HAS_ALT_PATH_SEP_ 0
1264 typedef long long BiggestInt;  // NOLINT
1265 #endif  // GTEST_OS_WINDOWS
1266
1267 // The testing::internal::posix namespace holds wrappers for common
1268 // POSIX functions.  These wrappers hide the differences between
1269 // Windows/MSVC and POSIX systems.  Since some compilers define these
1270 // standard functions as macros, the wrapper cannot have the same name
1271 // as the wrapped function.
1272
1273 namespace posix {
1274
1275 // Functions with a different name on Windows.
1276
1277 #if GTEST_OS_WINDOWS
1278
1279 typedef struct _stat StatStruct;
1280
1281 #ifdef __BORLANDC__
1282 inline int IsATTY(int fd) { return isatty(fd); }
1283 inline int StrCaseCmp(const char* s1, const char* s2) {
1284   return stricmp(s1, s2);
1285 }
1286 inline char* StrDup(const char* src) { return strdup(src); }
1287 #else  // !__BORLANDC__
1288 #if GTEST_OS_WINDOWS_MOBILE
1289 inline int IsATTY(int /* fd */) { return 0; }
1290 #else
1291 inline int IsATTY(int fd) { return _isatty(fd); }
1292 #endif  // GTEST_OS_WINDOWS_MOBILE
1293 inline int StrCaseCmp(const char* s1, const char* s2) {
1294   return _stricmp(s1, s2);
1295 }
1296 inline char* StrDup(const char* src) { return _strdup(src); }
1297 #endif  // __BORLANDC__
1298
1299 #if GTEST_OS_WINDOWS_MOBILE
1300 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
1301 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
1302 // time and thus not defined there.
1303 #else
1304 inline int FileNo(FILE* file) { return _fileno(file); }
1305 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
1306 inline int RmDir(const char* dir) { return _rmdir(dir); }
1307 inline bool IsDir(const StatStruct& st) {
1308   return (_S_IFDIR & st.st_mode) != 0;
1309 }
1310 #endif  // GTEST_OS_WINDOWS_MOBILE
1311
1312 #else
1313
1314 typedef struct stat StatStruct;
1315
1316 inline int FileNo(FILE* file) { return fileno(file); }
1317 inline int IsATTY(int fd) { return isatty(fd); }
1318 inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
1319 inline int StrCaseCmp(const char* s1, const char* s2) {
1320   return strcasecmp(s1, s2);
1321 }
1322 inline char* StrDup(const char* src) { return strdup(src); }
1323 inline int RmDir(const char* dir) { return rmdir(dir); }
1324 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
1325
1326 #endif  // GTEST_OS_WINDOWS
1327
1328 // Functions deprecated by MSVC 8.0.
1329
1330 #ifdef _MSC_VER
1331 // Temporarily disable warning 4996 (deprecated function).
1332 #pragma warning(push)
1333 #pragma warning(disable:4996)
1334 #endif
1335
1336 inline const char* StrNCpy(char* dest, const char* src, size_t n) {
1337   return strncpy(dest, src, n);
1338 }
1339
1340 // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
1341 // StrError() aren't needed on Windows CE at this time and thus not
1342 // defined there.
1343
1344 #if !GTEST_OS_WINDOWS_MOBILE
1345 inline int ChDir(const char* dir) { return chdir(dir); }
1346 #endif
1347 inline FILE* FOpen(const char* path, const char* mode) {
1348   return fopen(path, mode);
1349 }
1350 #if !GTEST_OS_WINDOWS_MOBILE
1351 inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
1352   return freopen(path, mode, stream);
1353 }
1354 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
1355 #endif
1356 inline int FClose(FILE* fp) { return fclose(fp); }
1357 #if !GTEST_OS_WINDOWS_MOBILE
1358 inline int Read(int fd, void* buf, unsigned int count) {
1359   return static_cast<int>(read(fd, buf, count));
1360 }
1361 inline int Write(int fd, const void* buf, unsigned int count) {
1362   return static_cast<int>(write(fd, buf, count));
1363 }
1364 inline int Close(int fd) { return close(fd); }
1365 inline const char* StrError(int errnum) { return strerror(errnum); }
1366 #endif
1367 inline const char* GetEnv(const char* name) {
1368 #if GTEST_OS_WINDOWS_MOBILE
1369   // We are on Windows CE, which has no environment variables.
1370   return NULL;
1371 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1372   // Environment variables which we programmatically clear will be set to the
1373   // empty string rather than unset (NULL).  Handle that case.
1374   const char* const env = getenv(name);
1375   return (env != NULL && env[0] != '\0') ? env : NULL;
1376 #else
1377   return getenv(name);
1378 #endif
1379 }
1380
1381 #ifdef _MSC_VER
1382 #pragma warning(pop)  // Restores the warning state.
1383 #endif
1384
1385 #if GTEST_OS_WINDOWS_MOBILE
1386 // Windows CE has no C library. The abort() function is used in
1387 // several places in Google Test. This implementation provides a reasonable
1388 // imitation of standard behaviour.
1389 void Abort();
1390 #else
1391 inline void Abort() { abort(); }
1392 #endif  // GTEST_OS_WINDOWS_MOBILE
1393
1394 }  // namespace posix
1395
1396 // The maximum number a BiggestInt can represent.  This definition
1397 // works no matter BiggestInt is represented in one's complement or
1398 // two's complement.
1399 //
1400 // We cannot rely on numeric_limits in STL, as __int64 and long long
1401 // are not part of standard C++ and numeric_limits doesn't need to be
1402 // defined for them.
1403 const BiggestInt kMaxBiggestInt =
1404     ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
1405
1406 // This template class serves as a compile-time function from size to
1407 // type.  It maps a size in bytes to a primitive type with that
1408 // size. e.g.
1409 //
1410 //   TypeWithSize<4>::UInt
1411 //
1412 // is typedef-ed to be unsigned int (unsigned integer made up of 4
1413 // bytes).
1414 //
1415 // Such functionality should belong to STL, but I cannot find it
1416 // there.
1417 //
1418 // Google Test uses this class in the implementation of floating-point
1419 // comparison.
1420 //
1421 // For now it only handles UInt (unsigned int) as that's all Google Test
1422 // needs.  Other types can be easily added in the future if need
1423 // arises.
1424 template <size_t size>
1425 class TypeWithSize {
1426  public:
1427   // This prevents the user from using TypeWithSize<N> with incorrect
1428   // values of N.
1429   typedef void UInt;
1430 };
1431
1432 // The specialization for size 4.
1433 template <>
1434 class TypeWithSize<4> {
1435  public:
1436   // unsigned int has size 4 in both gcc and MSVC.
1437   //
1438   // As base/basictypes.h doesn't compile on Windows, we cannot use
1439   // uint32, uint64, and etc here.
1440   typedef int Int;
1441   typedef unsigned int UInt;
1442 };
1443
1444 // The specialization for size 8.
1445 template <>
1446 class TypeWithSize<8> {
1447  public:
1448 #if GTEST_OS_WINDOWS
1449   typedef __int64 Int;
1450   typedef unsigned __int64 UInt;
1451 #else
1452   typedef long long Int;  // NOLINT
1453   typedef unsigned long long UInt;  // NOLINT
1454 #endif  // GTEST_OS_WINDOWS
1455 };
1456
1457 // Integer types of known sizes.
1458 typedef TypeWithSize<4>::Int Int32;
1459 typedef TypeWithSize<4>::UInt UInt32;
1460 typedef TypeWithSize<8>::Int Int64;
1461 typedef TypeWithSize<8>::UInt UInt64;
1462 typedef TypeWithSize<8>::Int TimeInMillis;  // Represents time in milliseconds.
1463
1464 // Utilities for command line flags and environment variables.
1465
1466 // Macro for referencing flags.
1467 #define GTEST_FLAG(name) FLAGS_gtest_##name
1468
1469 // Macros for declaring flags.
1470 #define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
1471 #define GTEST_DECLARE_int32_(name) \
1472     GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
1473 #define GTEST_DECLARE_string_(name) \
1474     GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name)
1475
1476 // Macros for defining flags.
1477 #define GTEST_DEFINE_bool_(name, default_val, doc) \
1478     GTEST_API_ bool GTEST_FLAG(name) = (default_val)
1479 #define GTEST_DEFINE_int32_(name, default_val, doc) \
1480     GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
1481 #define GTEST_DEFINE_string_(name, default_val, doc) \
1482     GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val)
1483
1484 // Parses 'str' for a 32-bit signed integer.  If successful, writes the result
1485 // to *value and returns true; otherwise leaves *value unchanged and returns
1486 // false.
1487 // TODO(chandlerc): Find a better way to refactor flag and environment parsing
1488 // out of both gtest-port.cc and gtest.cc to avoid exporting this utility
1489 // function.
1490 bool ParseInt32(const Message& src_text, const char* str, Int32* value);
1491
1492 // Parses a bool/Int32/string from the environment variable
1493 // corresponding to the given Google Test flag.
1494 bool BoolFromGTestEnv(const char* flag, bool default_val);
1495 GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
1496 const char* StringFromGTestEnv(const char* flag, const char* default_val);
1497
1498 }  // namespace internal
1499 }  // namespace testing
1500
1501 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_