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