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