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