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