1 // Copyright 2008, 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 // Author: wan@google.com (Zhanyong Wan)
31
32 #include "gtest/internal/gtest-port.h"
33
34 #include <limits.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <fstream>
39
40 #if GTEST_OS_WINDOWS
41 # include <windows.h>
42 # include <io.h>
43 # include <sys/stat.h>
44 # include <map> // Used in ThreadLocal.
45 #else
46 # include <unistd.h>
47 #endif // GTEST_OS_WINDOWS
48
49 #if GTEST_OS_MAC
50 # include <mach/mach_init.h>
51 # include <mach/task.h>
52 # include <mach/vm_map.h>
53 #endif // GTEST_OS_MAC
54
55 #if GTEST_OS_QNX
56 # include <devctl.h>
57 # include <fcntl.h>
58 # include <sys/procfs.h>
59 #endif // GTEST_OS_QNX
60
61 #include "gtest/gtest-spi.h"
62 #include "gtest/gtest-message.h"
63 #include "gtest/internal/gtest-internal.h"
64 #include "gtest/internal/gtest-string.h"
65
66 // Indicates that this translation unit is part of Google Test's
67 // implementation. It must come before gtest-internal-inl.h is
68 // included, or there will be a compiler error. This trick exists to
69 // prevent the accidental inclusion of gtest-internal-inl.h in the
70 // user's code.
71 #define GTEST_IMPLEMENTATION_ 1
72 #include "src/gtest-internal-inl.h"
73 #undef GTEST_IMPLEMENTATION_
74
75 namespace testing {
76 namespace internal {
77
78 #if defined(_MSC_VER) || defined(__BORLANDC__)
79 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
80 const int kStdOutFileno = 1;
81 const int kStdErrFileno = 2;
82 #else
83 const int kStdOutFileno = STDOUT_FILENO;
84 const int kStdErrFileno = STDERR_FILENO;
85 #endif // _MSC_VER
86
87 #if GTEST_OS_LINUX
88
89 namespace {
90 template <typename T>
ReadProcFileField(const string & filename,int field)91 T ReadProcFileField(const string& filename, int field) {
92 std::string dummy;
93 std::ifstream file(filename.c_str());
94 while (field-- > 0) {
95 file >> dummy;
96 }
97 T output = 0;
98 file >> output;
99 return output;
100 }
101 } // namespace
102
103 // Returns the number of active threads, or 0 when there is an error.
GetThreadCount()104 size_t GetThreadCount() {
105 const string filename =
106 (Message() << "/proc/" << getpid() << "/stat").GetString();
107 return ReadProcFileField<int>(filename, 19);
108 }
109
110 #elif GTEST_OS_MAC
111
GetThreadCount()112 size_t GetThreadCount() {
113 const task_t task = mach_task_self();
114 mach_msg_type_number_t thread_count;
115 thread_act_array_t thread_list;
116 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
117 if (status == KERN_SUCCESS) {
118 // task_threads allocates resources in thread_list and we need to free them
119 // to avoid leaks.
120 vm_deallocate(task,
121 reinterpret_cast<vm_address_t>(thread_list),
122 sizeof(thread_t) * thread_count);
123 return static_cast<size_t>(thread_count);
124 } else {
125 return 0;
126 }
127 }
128
129 #elif GTEST_OS_QNX
130
131 // Returns the number of threads running in the process, or 0 to indicate that
132 // we cannot detect it.
GetThreadCount()133 size_t GetThreadCount() {
134 const int fd = open("/proc/self/as", O_RDONLY);
135 if (fd < 0) {
136 return 0;
137 }
138 procfs_info process_info;
139 const int status =
140 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
141 close(fd);
142 if (status == EOK) {
143 return static_cast<size_t>(process_info.num_threads);
144 } else {
145 return 0;
146 }
147 }
148
149 #else
150
GetThreadCount()151 size_t GetThreadCount() {
152 // There's no portable way to detect the number of threads, so we just
153 // return 0 to indicate that we cannot detect it.
154 return 0;
155 }
156
157 #endif // GTEST_OS_LINUX
158
159 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
160
SleepMilliseconds(int n)161 void SleepMilliseconds(int n) {
162 ::Sleep(n);
163 }
164
AutoHandle()165 AutoHandle::AutoHandle()
166 : handle_(INVALID_HANDLE_VALUE) {}
167
AutoHandle(Handle handle)168 AutoHandle::AutoHandle(Handle handle)
169 : handle_(handle) {}
170
~AutoHandle()171 AutoHandle::~AutoHandle() {
172 Reset();
173 }
174
Get() const175 AutoHandle::Handle AutoHandle::Get() const {
176 return handle_;
177 }
178
Reset()179 void AutoHandle::Reset() {
180 Reset(INVALID_HANDLE_VALUE);
181 }
182
Reset(HANDLE handle)183 void AutoHandle::Reset(HANDLE handle) {
184 // Resetting with the same handle we already own is invalid.
185 if (handle_ != handle) {
186 if (IsCloseable()) {
187 ::CloseHandle(handle_);
188 }
189 handle_ = handle;
190 } else {
191 GTEST_CHECK_(!IsCloseable())
192 << "Resetting a valid handle to itself is likely a programmer error "
193 "and thus not allowed.";
194 }
195 }
196
IsCloseable() const197 bool AutoHandle::IsCloseable() const {
198 // Different Windows APIs may use either of these values to represent an
199 // invalid handle.
200 return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
201 }
202
Notification()203 Notification::Notification()
204 : event_(::CreateEvent(NULL, // Default security attributes.
205 TRUE, // Do not reset automatically.
206 FALSE, // Initially unset.
207 NULL)) { // Anonymous event.
208 GTEST_CHECK_(event_.Get() != NULL);
209 }
210
Notify()211 void Notification::Notify() {
212 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
213 }
214
WaitForNotification()215 void Notification::WaitForNotification() {
216 GTEST_CHECK_(
217 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
218 }
219
Mutex()220 Mutex::Mutex()
221 : owner_thread_id_(0),
222 type_(kDynamic),
223 critical_section_init_phase_(0),
224 critical_section_(new CRITICAL_SECTION) {
225 ::InitializeCriticalSection(critical_section_);
226 }
227
~Mutex()228 Mutex::~Mutex() {
229 // Static mutexes are leaked intentionally. It is not thread-safe to try
230 // to clean them up.
231 // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
232 // nothing to clean it up but is available only on Vista and later.
233 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
234 if (type_ == kDynamic) {
235 ::DeleteCriticalSection(critical_section_);
236 delete critical_section_;
237 critical_section_ = NULL;
238 }
239 }
240
Lock()241 void Mutex::Lock() {
242 ThreadSafeLazyInit();
243 ::EnterCriticalSection(critical_section_);
244 owner_thread_id_ = ::GetCurrentThreadId();
245 }
246
Unlock()247 void Mutex::Unlock() {
248 ThreadSafeLazyInit();
249 // We don't protect writing to owner_thread_id_ here, as it's the
250 // caller's responsibility to ensure that the current thread holds the
251 // mutex when this is called.
252 owner_thread_id_ = 0;
253 ::LeaveCriticalSection(critical_section_);
254 }
255
256 // Does nothing if the current thread holds the mutex. Otherwise, crashes
257 // with high probability.
AssertHeld()258 void Mutex::AssertHeld() {
259 ThreadSafeLazyInit();
260 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
261 << "The current thread is not holding the mutex @" << this;
262 }
263
264 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
ThreadSafeLazyInit()265 void Mutex::ThreadSafeLazyInit() {
266 // Dynamic mutexes are initialized in the constructor.
267 if (type_ == kStatic) {
268 switch (
269 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
270 case 0:
271 // If critical_section_init_phase_ was 0 before the exchange, we
272 // are the first to test it and need to perform the initialization.
273 owner_thread_id_ = 0;
274 critical_section_ = new CRITICAL_SECTION;
275 ::InitializeCriticalSection(critical_section_);
276 // Updates the critical_section_init_phase_ to 2 to signal
277 // initialization complete.
278 GTEST_CHECK_(::InterlockedCompareExchange(
279 &critical_section_init_phase_, 2L, 1L) ==
280 1L);
281 break;
282 case 1:
283 // Somebody else is already initializing the mutex; spin until they
284 // are done.
285 while (::InterlockedCompareExchange(&critical_section_init_phase_,
286 2L,
287 2L) != 2L) {
288 // Possibly yields the rest of the thread's time slice to other
289 // threads.
290 ::Sleep(0);
291 }
292 break;
293
294 case 2:
295 break; // The mutex is already initialized and ready for use.
296
297 default:
298 GTEST_CHECK_(false)
299 << "Unexpected value of critical_section_init_phase_ "
300 << "while initializing a static mutex.";
301 }
302 }
303 }
304
305 namespace {
306
307 class ThreadWithParamSupport : public ThreadWithParamBase {
308 public:
CreateThread(Runnable * runnable,Notification * thread_can_start)309 static HANDLE CreateThread(Runnable* runnable,
310 Notification* thread_can_start) {
311 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
312 DWORD thread_id;
313 // TODO(yukawa): Consider to use _beginthreadex instead.
314 HANDLE thread_handle = ::CreateThread(
315 NULL, // Default security.
316 0, // Default stack size.
317 &ThreadWithParamSupport::ThreadMain,
318 param, // Parameter to ThreadMainStatic
319 0x0, // Default creation flags.
320 &thread_id); // Need a valid pointer for the call to work under Win98.
321 GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
322 << ::GetLastError() << ".";
323 if (thread_handle == NULL) {
324 delete param;
325 }
326 return thread_handle;
327 }
328
329 private:
330 struct ThreadMainParam {
ThreadMainParamtesting::internal::__anonb603b6940211::ThreadWithParamSupport::ThreadMainParam331 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
332 : runnable_(runnable),
333 thread_can_start_(thread_can_start) {
334 }
335 scoped_ptr<Runnable> runnable_;
336 // Does not own.
337 Notification* thread_can_start_;
338 };
339
ThreadMain(void * ptr)340 static DWORD WINAPI ThreadMain(void* ptr) {
341 // Transfers ownership.
342 scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
343 if (param->thread_can_start_ != NULL)
344 param->thread_can_start_->WaitForNotification();
345 param->runnable_->Run();
346 return 0;
347 }
348
349 // Prohibit instantiation.
350 ThreadWithParamSupport();
351
352 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
353 };
354
355 } // namespace
356
ThreadWithParamBase(Runnable * runnable,Notification * thread_can_start)357 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
358 Notification* thread_can_start)
359 : thread_(ThreadWithParamSupport::CreateThread(runnable,
360 thread_can_start)) {
361 }
362
~ThreadWithParamBase()363 ThreadWithParamBase::~ThreadWithParamBase() {
364 Join();
365 }
366
Join()367 void ThreadWithParamBase::Join() {
368 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
369 << "Failed to join the thread with error " << ::GetLastError() << ".";
370 }
371
372 // Maps a thread to a set of ThreadIdToThreadLocals that have values
373 // instantiated on that thread and notifies them when the thread exits. A
374 // ThreadLocal instance is expected to persist until all threads it has
375 // values on have terminated.
376 class ThreadLocalRegistryImpl {
377 public:
378 // Registers thread_local_instance as having value on the current thread.
379 // Returns a value that can be used to identify the thread from other threads.
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)380 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
381 const ThreadLocalBase* thread_local_instance) {
382 DWORD current_thread = ::GetCurrentThreadId();
383 MutexLock lock(&mutex_);
384 ThreadIdToThreadLocals* const thread_to_thread_locals =
385 GetThreadLocalsMapLocked();
386 ThreadIdToThreadLocals::iterator thread_local_pos =
387 thread_to_thread_locals->find(current_thread);
388 if (thread_local_pos == thread_to_thread_locals->end()) {
389 thread_local_pos = thread_to_thread_locals->insert(
390 std::make_pair(current_thread, ThreadLocalValues())).first;
391 StartWatcherThreadFor(current_thread);
392 }
393 ThreadLocalValues& thread_local_values = thread_local_pos->second;
394 ThreadLocalValues::iterator value_pos =
395 thread_local_values.find(thread_local_instance);
396 if (value_pos == thread_local_values.end()) {
397 value_pos =
398 thread_local_values
399 .insert(std::make_pair(
400 thread_local_instance,
401 linked_ptr<ThreadLocalValueHolderBase>(
402 thread_local_instance->NewValueForCurrentThread())))
403 .first;
404 }
405 return value_pos->second.get();
406 }
407
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)408 static void OnThreadLocalDestroyed(
409 const ThreadLocalBase* thread_local_instance) {
410 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
411 // Clean up the ThreadLocalValues data structure while holding the lock, but
412 // defer the destruction of the ThreadLocalValueHolderBases.
413 {
414 MutexLock lock(&mutex_);
415 ThreadIdToThreadLocals* const thread_to_thread_locals =
416 GetThreadLocalsMapLocked();
417 for (ThreadIdToThreadLocals::iterator it =
418 thread_to_thread_locals->begin();
419 it != thread_to_thread_locals->end();
420 ++it) {
421 ThreadLocalValues& thread_local_values = it->second;
422 ThreadLocalValues::iterator value_pos =
423 thread_local_values.find(thread_local_instance);
424 if (value_pos != thread_local_values.end()) {
425 value_holders.push_back(value_pos->second);
426 thread_local_values.erase(value_pos);
427 // This 'if' can only be successful at most once, so theoretically we
428 // could break out of the loop here, but we don't bother doing so.
429 }
430 }
431 }
432 // Outside the lock, let the destructor for 'value_holders' deallocate the
433 // ThreadLocalValueHolderBases.
434 }
435
OnThreadExit(DWORD thread_id)436 static void OnThreadExit(DWORD thread_id) {
437 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
438 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
439 // Clean up the ThreadIdToThreadLocals data structure while holding the
440 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
441 {
442 MutexLock lock(&mutex_);
443 ThreadIdToThreadLocals* const thread_to_thread_locals =
444 GetThreadLocalsMapLocked();
445 ThreadIdToThreadLocals::iterator thread_local_pos =
446 thread_to_thread_locals->find(thread_id);
447 if (thread_local_pos != thread_to_thread_locals->end()) {
448 ThreadLocalValues& thread_local_values = thread_local_pos->second;
449 for (ThreadLocalValues::iterator value_pos =
450 thread_local_values.begin();
451 value_pos != thread_local_values.end();
452 ++value_pos) {
453 value_holders.push_back(value_pos->second);
454 }
455 thread_to_thread_locals->erase(thread_local_pos);
456 }
457 }
458 // Outside the lock, let the destructor for 'value_holders' deallocate the
459 // ThreadLocalValueHolderBases.
460 }
461
462 private:
463 // In a particular thread, maps a ThreadLocal object to its value.
464 typedef std::map<const ThreadLocalBase*,
465 linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
466 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
467 // thread's ID.
468 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
469
470 // Holds the thread id and thread handle that we pass from
471 // StartWatcherThreadFor to WatcherThreadFunc.
472 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
473
StartWatcherThreadFor(DWORD thread_id)474 static void StartWatcherThreadFor(DWORD thread_id) {
475 // The returned handle will be kept in thread_map and closed by
476 // watcher_thread in WatcherThreadFunc.
477 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
478 FALSE,
479 thread_id);
480 GTEST_CHECK_(thread != NULL);
481 // We need to to pass a valid thread ID pointer into CreateThread for it
482 // to work correctly under Win98.
483 DWORD watcher_thread_id;
484 HANDLE watcher_thread = ::CreateThread(
485 NULL, // Default security.
486 0, // Default stack size
487 &ThreadLocalRegistryImpl::WatcherThreadFunc,
488 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
489 CREATE_SUSPENDED,
490 &watcher_thread_id);
491 GTEST_CHECK_(watcher_thread != NULL);
492 // Give the watcher thread the same priority as ours to avoid being
493 // blocked by it.
494 ::SetThreadPriority(watcher_thread,
495 ::GetThreadPriority(::GetCurrentThread()));
496 ::ResumeThread(watcher_thread);
497 ::CloseHandle(watcher_thread);
498 }
499
500 // Monitors exit from a given thread and notifies those
501 // ThreadIdToThreadLocals about thread termination.
WatcherThreadFunc(LPVOID param)502 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
503 const ThreadIdAndHandle* tah =
504 reinterpret_cast<const ThreadIdAndHandle*>(param);
505 GTEST_CHECK_(
506 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
507 OnThreadExit(tah->first);
508 ::CloseHandle(tah->second);
509 delete tah;
510 return 0;
511 }
512
513 // Returns map of thread local instances.
GetThreadLocalsMapLocked()514 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
515 mutex_.AssertHeld();
516 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;
517 return map;
518 }
519
520 // Protects access to GetThreadLocalsMapLocked() and its return value.
521 static Mutex mutex_;
522 // Protects access to GetThreadMapLocked() and its return value.
523 static Mutex thread_map_mutex_;
524 };
525
526 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
527 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
528
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)529 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
530 const ThreadLocalBase* thread_local_instance) {
531 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
532 thread_local_instance);
533 }
534
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)535 void ThreadLocalRegistry::OnThreadLocalDestroyed(
536 const ThreadLocalBase* thread_local_instance) {
537 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
538 }
539
540 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
541
542 #if GTEST_USES_POSIX_RE
543
544 // Implements RE. Currently only needed for death tests.
545
~RE()546 RE::~RE() {
547 if (is_valid_) {
548 // regfree'ing an invalid regex might crash because the content
549 // of the regex is undefined. Since the regex's are essentially
550 // the same, one cannot be valid (or invalid) without the other
551 // being so too.
552 regfree(&partial_regex_);
553 regfree(&full_regex_);
554 }
555 free(const_cast<char*>(pattern_));
556 }
557
558 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)559 bool RE::FullMatch(const char* str, const RE& re) {
560 if (!re.is_valid_) return false;
561
562 regmatch_t match;
563 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
564 }
565
566 // Returns true iff regular expression re matches a substring of str
567 // (including str itself).
PartialMatch(const char * str,const RE & re)568 bool RE::PartialMatch(const char* str, const RE& re) {
569 if (!re.is_valid_) return false;
570
571 regmatch_t match;
572 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
573 }
574
575 // Initializes an RE from its string representation.
Init(const char * regex)576 void RE::Init(const char* regex) {
577 pattern_ = posix::StrDup(regex);
578
579 // Reserves enough bytes to hold the regular expression used for a
580 // full match.
581 const size_t full_regex_len = strlen(regex) + 10;
582 char* const full_pattern = new char[full_regex_len];
583
584 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
585 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
586 // We want to call regcomp(&partial_regex_, ...) even if the
587 // previous expression returns false. Otherwise partial_regex_ may
588 // not be properly initialized can may cause trouble when it's
589 // freed.
590 //
591 // Some implementation of POSIX regex (e.g. on at least some
592 // versions of Cygwin) doesn't accept the empty string as a valid
593 // regex. We change it to an equivalent form "()" to be safe.
594 if (is_valid_) {
595 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
596 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
597 }
598 EXPECT_TRUE(is_valid_)
599 << "Regular expression \"" << regex
600 << "\" is not a valid POSIX Extended regular expression.";
601
602 delete[] full_pattern;
603 }
604
605 #elif GTEST_USES_SIMPLE_RE
606
607 // Returns true iff ch appears anywhere in str (excluding the
608 // terminating '\0' character).
IsInSet(char ch,const char * str)609 bool IsInSet(char ch, const char* str) {
610 return ch != '\0' && strchr(str, ch) != NULL;
611 }
612
613 // Returns true iff ch belongs to the given classification. Unlike
614 // similar functions in <ctype.h>, these aren't affected by the
615 // current locale.
IsAsciiDigit(char ch)616 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)617 bool IsAsciiPunct(char ch) {
618 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
619 }
IsRepeat(char ch)620 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)621 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)622 bool IsAsciiWordChar(char ch) {
623 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
624 ('0' <= ch && ch <= '9') || ch == '_';
625 }
626
627 // Returns true iff "\\c" is a supported escape sequence.
IsValidEscape(char c)628 bool IsValidEscape(char c) {
629 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
630 }
631
632 // Returns true iff the given atom (specified by escaped and pattern)
633 // matches ch. The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)634 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
635 if (escaped) { // "\\p" where p is pattern_char.
636 switch (pattern_char) {
637 case 'd': return IsAsciiDigit(ch);
638 case 'D': return !IsAsciiDigit(ch);
639 case 'f': return ch == '\f';
640 case 'n': return ch == '\n';
641 case 'r': return ch == '\r';
642 case 's': return IsAsciiWhiteSpace(ch);
643 case 'S': return !IsAsciiWhiteSpace(ch);
644 case 't': return ch == '\t';
645 case 'v': return ch == '\v';
646 case 'w': return IsAsciiWordChar(ch);
647 case 'W': return !IsAsciiWordChar(ch);
648 }
649 return IsAsciiPunct(pattern_char) && pattern_char == ch;
650 }
651
652 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
653 }
654
655 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)656 std::string FormatRegexSyntaxError(const char* regex, int index) {
657 return (Message() << "Syntax error at index " << index
658 << " in simple regular expression \"" << regex << "\": ").GetString();
659 }
660
661 // Generates non-fatal failures and returns false if regex is invalid;
662 // otherwise returns true.
ValidateRegex(const char * regex)663 bool ValidateRegex(const char* regex) {
664 if (regex == NULL) {
665 // TODO(wan@google.com): fix the source file location in the
666 // assertion failures to match where the regex is used in user
667 // code.
668 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
669 return false;
670 }
671
672 bool is_valid = true;
673
674 // True iff ?, *, or + can follow the previous atom.
675 bool prev_repeatable = false;
676 for (int i = 0; regex[i]; i++) {
677 if (regex[i] == '\\') { // An escape sequence
678 i++;
679 if (regex[i] == '\0') {
680 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
681 << "'\\' cannot appear at the end.";
682 return false;
683 }
684
685 if (!IsValidEscape(regex[i])) {
686 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
687 << "invalid escape sequence \"\\" << regex[i] << "\".";
688 is_valid = false;
689 }
690 prev_repeatable = true;
691 } else { // Not an escape sequence.
692 const char ch = regex[i];
693
694 if (ch == '^' && i > 0) {
695 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
696 << "'^' can only appear at the beginning.";
697 is_valid = false;
698 } else if (ch == '$' && regex[i + 1] != '\0') {
699 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
700 << "'$' can only appear at the end.";
701 is_valid = false;
702 } else if (IsInSet(ch, "()[]{}|")) {
703 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
704 << "'" << ch << "' is unsupported.";
705 is_valid = false;
706 } else if (IsRepeat(ch) && !prev_repeatable) {
707 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
708 << "'" << ch << "' can only follow a repeatable token.";
709 is_valid = false;
710 }
711
712 prev_repeatable = !IsInSet(ch, "^$?*+");
713 }
714 }
715
716 return is_valid;
717 }
718
719 // Matches a repeated regex atom followed by a valid simple regular
720 // expression. The regex atom is defined as c if escaped is false,
721 // or \c otherwise. repeat is the repetition meta character (?, *,
722 // or +). The behavior is undefined if str contains too many
723 // characters to be indexable by size_t, in which case the test will
724 // probably time out anyway. We are fine with this limitation as
725 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)726 bool MatchRepetitionAndRegexAtHead(
727 bool escaped, char c, char repeat, const char* regex,
728 const char* str) {
729 const size_t min_count = (repeat == '+') ? 1 : 0;
730 const size_t max_count = (repeat == '?') ? 1 :
731 static_cast<size_t>(-1) - 1;
732 // We cannot call numeric_limits::max() as it conflicts with the
733 // max() macro on Windows.
734
735 for (size_t i = 0; i <= max_count; ++i) {
736 // We know that the atom matches each of the first i characters in str.
737 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
738 // We have enough matches at the head, and the tail matches too.
739 // Since we only care about *whether* the pattern matches str
740 // (as opposed to *how* it matches), there is no need to find a
741 // greedy match.
742 return true;
743 }
744 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
745 return false;
746 }
747 return false;
748 }
749
750 // Returns true iff regex matches a prefix of str. regex must be a
751 // valid simple regular expression and not start with "^", or the
752 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)753 bool MatchRegexAtHead(const char* regex, const char* str) {
754 if (*regex == '\0') // An empty regex matches a prefix of anything.
755 return true;
756
757 // "$" only matches the end of a string. Note that regex being
758 // valid guarantees that there's nothing after "$" in it.
759 if (*regex == '$')
760 return *str == '\0';
761
762 // Is the first thing in regex an escape sequence?
763 const bool escaped = *regex == '\\';
764 if (escaped)
765 ++regex;
766 if (IsRepeat(regex[1])) {
767 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
768 // here's an indirect recursion. It terminates as the regex gets
769 // shorter in each recursion.
770 return MatchRepetitionAndRegexAtHead(
771 escaped, regex[0], regex[1], regex + 2, str);
772 } else {
773 // regex isn't empty, isn't "$", and doesn't start with a
774 // repetition. We match the first atom of regex with the first
775 // character of str and recurse.
776 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
777 MatchRegexAtHead(regex + 1, str + 1);
778 }
779 }
780
781 // Returns true iff regex matches any substring of str. regex must be
782 // a valid simple regular expression, or the result is undefined.
783 //
784 // The algorithm is recursive, but the recursion depth doesn't exceed
785 // the regex length, so we won't need to worry about running out of
786 // stack space normally. In rare cases the time complexity can be
787 // exponential with respect to the regex length + the string length,
788 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)789 bool MatchRegexAnywhere(const char* regex, const char* str) {
790 if (regex == NULL || str == NULL)
791 return false;
792
793 if (*regex == '^')
794 return MatchRegexAtHead(regex + 1, str);
795
796 // A successful match can be anywhere in str.
797 do {
798 if (MatchRegexAtHead(regex, str))
799 return true;
800 } while (*str++ != '\0');
801 return false;
802 }
803
804 // Implements the RE class.
805
~RE()806 RE::~RE() {
807 free(const_cast<char*>(pattern_));
808 free(const_cast<char*>(full_pattern_));
809 }
810
811 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)812 bool RE::FullMatch(const char* str, const RE& re) {
813 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
814 }
815
816 // Returns true iff regular expression re matches a substring of str
817 // (including str itself).
PartialMatch(const char * str,const RE & re)818 bool RE::PartialMatch(const char* str, const RE& re) {
819 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
820 }
821
822 // Initializes an RE from its string representation.
Init(const char * regex)823 void RE::Init(const char* regex) {
824 pattern_ = full_pattern_ = NULL;
825 if (regex != NULL) {
826 pattern_ = posix::StrDup(regex);
827 }
828
829 is_valid_ = ValidateRegex(regex);
830 if (!is_valid_) {
831 // No need to calculate the full pattern when the regex is invalid.
832 return;
833 }
834
835 const size_t len = strlen(regex);
836 // Reserves enough bytes to hold the regular expression used for a
837 // full match: we need space to prepend a '^', append a '$', and
838 // terminate the string with '\0'.
839 char* buffer = static_cast<char*>(malloc(len + 3));
840 full_pattern_ = buffer;
841
842 if (*regex != '^')
843 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
844
845 // We don't use snprintf or strncpy, as they trigger a warning when
846 // compiled with VC++ 8.0.
847 memcpy(buffer, regex, len);
848 buffer += len;
849
850 if (len == 0 || regex[len - 1] != '$')
851 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
852
853 *buffer = '\0';
854 }
855
856 #endif // GTEST_USES_POSIX_RE
857
858 const char kUnknownFile[] = "unknown file";
859
860 // Formats a source file path and a line number as they would appear
861 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)862 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
863 const std::string file_name(file == NULL ? kUnknownFile : file);
864
865 if (line < 0) {
866 return file_name + ":";
867 }
868 #ifdef _MSC_VER
869 return file_name + "(" + StreamableToString(line) + "):";
870 #else
871 return file_name + ":" + StreamableToString(line) + ":";
872 #endif // _MSC_VER
873 }
874
875 // Formats a file location for compiler-independent XML output.
876 // Although this function is not platform dependent, we put it next to
877 // FormatFileLocation in order to contrast the two functions.
878 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
879 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)880 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
881 const char* file, int line) {
882 const std::string file_name(file == NULL ? kUnknownFile : file);
883
884 if (line < 0)
885 return file_name;
886 else
887 return file_name + ":" + StreamableToString(line);
888 }
889
GTestLog(GTestLogSeverity severity,const char * file,int line)890 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
891 : severity_(severity) {
892 const char* const marker =
893 severity == GTEST_INFO ? "[ INFO ]" :
894 severity == GTEST_WARNING ? "[WARNING]" :
895 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
896 GetStream() << ::std::endl << marker << " "
897 << FormatFileLocation(file, line).c_str() << ": ";
898 }
899
900 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()901 GTestLog::~GTestLog() {
902 GetStream() << ::std::endl;
903 if (severity_ == GTEST_FATAL) {
904 fflush(stderr);
905 posix::Abort();
906 }
907 }
908 // Disable Microsoft deprecation warnings for POSIX functions called from
909 // this class (creat, dup, dup2, and close)
910 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
911
912 #if GTEST_HAS_STREAM_REDIRECTION
913
914 // Object that captures an output stream (stdout/stderr).
915 class CapturedStream {
916 public:
917 // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)918 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
919 # if GTEST_OS_WINDOWS
920 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
921 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
922
923 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
924 const UINT success = ::GetTempFileNameA(temp_dir_path,
925 "gtest_redir",
926 0, // Generate unique file name.
927 temp_file_path);
928 GTEST_CHECK_(success != 0)
929 << "Unable to create a temporary file in " << temp_dir_path;
930 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
931 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
932 << temp_file_path;
933 filename_ = temp_file_path;
934 # else
935 // There's no guarantee that a test has write access to the current
936 // directory, so we create the temporary file in the /tmp directory
937 // instead. We use /tmp on most systems, and /sdcard on Android.
938 // That's because Android doesn't have /tmp.
939 # if GTEST_OS_LINUX_ANDROID
940 // Note: Android applications are expected to call the framework's
941 // Context.getExternalStorageDirectory() method through JNI to get
942 // the location of the world-writable SD Card directory. However,
943 // this requires a Context handle, which cannot be retrieved
944 // globally from native code. Doing so also precludes running the
945 // code as part of a regular standalone executable, which doesn't
946 // run in a Dalvik process (e.g. when running it through 'adb shell').
947 //
948 // The location /sdcard is directly accessible from native code
949 // and is the only location (unofficially) supported by the Android
950 // team. It's generally a symlink to the real SD Card mount point
951 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
952 // other OEM-customized locations. Never rely on these, and always
953 // use /sdcard.
954 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
955 # else
956 char name_template[] = "/tmp/captured_stream.XXXXXX";
957 # endif // GTEST_OS_LINUX_ANDROID
958 const int captured_fd = mkstemp(name_template);
959 filename_ = name_template;
960 # endif // GTEST_OS_WINDOWS
961 fflush(NULL);
962 dup2(captured_fd, fd_);
963 close(captured_fd);
964 }
965
~CapturedStream()966 ~CapturedStream() {
967 remove(filename_.c_str());
968 }
969
GetCapturedString()970 std::string GetCapturedString() {
971 if (uncaptured_fd_ != -1) {
972 // Restores the original stream.
973 fflush(NULL);
974 dup2(uncaptured_fd_, fd_);
975 close(uncaptured_fd_);
976 uncaptured_fd_ = -1;
977 }
978
979 FILE* const file = posix::FOpen(filename_.c_str(), "r");
980 const std::string content = ReadEntireFile(file);
981 posix::FClose(file);
982 return content;
983 }
984
985 private:
986 const int fd_; // A stream to capture.
987 int uncaptured_fd_;
988 // Name of the temporary file holding the stderr output.
989 ::std::string filename_;
990
991 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
992 };
993
994 GTEST_DISABLE_MSC_WARNINGS_POP_()
995
996 static CapturedStream* g_captured_stderr = NULL;
997 static CapturedStream* g_captured_stdout = NULL;
998
999 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)1000 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
1001 if (*stream != NULL) {
1002 GTEST_LOG_(FATAL) << "Only one " << stream_name
1003 << " capturer can exist at a time.";
1004 }
1005 *stream = new CapturedStream(fd);
1006 }
1007
1008 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)1009 std::string GetCapturedStream(CapturedStream** captured_stream) {
1010 const std::string content = (*captured_stream)->GetCapturedString();
1011
1012 delete *captured_stream;
1013 *captured_stream = NULL;
1014
1015 return content;
1016 }
1017
1018 // Starts capturing stdout.
CaptureStdout()1019 void CaptureStdout() {
1020 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
1021 }
1022
1023 // Starts capturing stderr.
CaptureStderr()1024 void CaptureStderr() {
1025 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
1026 }
1027
1028 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()1029 std::string GetCapturedStdout() {
1030 return GetCapturedStream(&g_captured_stdout);
1031 }
1032
1033 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()1034 std::string GetCapturedStderr() {
1035 return GetCapturedStream(&g_captured_stderr);
1036 }
1037
1038 #endif // GTEST_HAS_STREAM_REDIRECTION
1039
TempDir()1040 std::string TempDir() {
1041 #if GTEST_OS_WINDOWS_MOBILE
1042 return "\\temp\\";
1043 #elif GTEST_OS_WINDOWS
1044 const char* temp_dir = posix::GetEnv("TEMP");
1045 if (temp_dir == NULL || temp_dir[0] == '\0')
1046 return "\\temp\\";
1047 else if (temp_dir[strlen(temp_dir) - 1] == '\\')
1048 return temp_dir;
1049 else
1050 return std::string(temp_dir) + "\\";
1051 #elif GTEST_OS_LINUX_ANDROID
1052 return "/sdcard/";
1053 #else
1054 return "/tmp/";
1055 #endif // GTEST_OS_WINDOWS_MOBILE
1056 }
1057
GetFileSize(FILE * file)1058 size_t GetFileSize(FILE* file) {
1059 fseek(file, 0, SEEK_END);
1060 return static_cast<size_t>(ftell(file));
1061 }
1062
ReadEntireFile(FILE * file)1063 std::string ReadEntireFile(FILE* file) {
1064 const size_t file_size = GetFileSize(file);
1065 char* const buffer = new char[file_size];
1066
1067 size_t bytes_last_read = 0; // # of bytes read in the last fread()
1068 size_t bytes_read = 0; // # of bytes read so far
1069
1070 fseek(file, 0, SEEK_SET);
1071
1072 // Keeps reading the file until we cannot read further or the
1073 // pre-determined file size is reached.
1074 do {
1075 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
1076 bytes_read += bytes_last_read;
1077 } while (bytes_last_read > 0 && bytes_read < file_size);
1078
1079 const std::string content(buffer, bytes_read);
1080 delete[] buffer;
1081
1082 return content;
1083 }
1084
1085 #if GTEST_HAS_DEATH_TEST
1086
1087 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
1088 NULL; // Owned.
1089
SetInjectableArgvs(const::std::vector<testing::internal::string> * argvs)1090 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
1091 if (g_injected_test_argvs != argvs)
1092 delete g_injected_test_argvs;
1093 g_injected_test_argvs = argvs;
1094 }
1095
GetInjectableArgvs()1096 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
1097 if (g_injected_test_argvs != NULL) {
1098 return *g_injected_test_argvs;
1099 }
1100 return GetArgvs();
1101 }
1102 #endif // GTEST_HAS_DEATH_TEST
1103
1104 #if GTEST_OS_WINDOWS_MOBILE
1105 namespace posix {
Abort()1106 void Abort() {
1107 DebugBreak();
1108 TerminateProcess(GetCurrentProcess(), 1);
1109 }
1110 } // namespace posix
1111 #endif // GTEST_OS_WINDOWS_MOBILE
1112
1113 // Returns the name of the environment variable corresponding to the
1114 // given flag. For example, FlagToEnvVar("foo") will return
1115 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)1116 static std::string FlagToEnvVar(const char* flag) {
1117 const std::string full_flag =
1118 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
1119
1120 Message env_var;
1121 for (size_t i = 0; i != full_flag.length(); i++) {
1122 env_var << ToUpper(full_flag.c_str()[i]);
1123 }
1124
1125 return env_var.GetString();
1126 }
1127
1128 // Parses 'str' for a 32-bit signed integer. If successful, writes
1129 // the result to *value and returns true; otherwise leaves *value
1130 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)1131 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
1132 // Parses the environment variable as a decimal integer.
1133 char* end = NULL;
1134 const long long_value = strtol(str, &end, 10); // NOLINT
1135
1136 // Has strtol() consumed all characters in the string?
1137 if (*end != '\0') {
1138 // No - an invalid character was encountered.
1139 Message msg;
1140 msg << "WARNING: " << src_text
1141 << " is expected to be a 32-bit integer, but actually"
1142 << " has value \"" << str << "\".\n";
1143 printf("%s", msg.GetString().c_str());
1144 fflush(stdout);
1145 return false;
1146 }
1147
1148 // Is the parsed value in the range of an Int32?
1149 const Int32 result = static_cast<Int32>(long_value);
1150 if (long_value == LONG_MAX || long_value == LONG_MIN ||
1151 // The parsed value overflows as a long. (strtol() returns
1152 // LONG_MAX or LONG_MIN when the input overflows.)
1153 result != long_value
1154 // The parsed value overflows as an Int32.
1155 ) {
1156 Message msg;
1157 msg << "WARNING: " << src_text
1158 << " is expected to be a 32-bit integer, but actually"
1159 << " has value " << str << ", which overflows.\n";
1160 printf("%s", msg.GetString().c_str());
1161 fflush(stdout);
1162 return false;
1163 }
1164
1165 *value = result;
1166 return true;
1167 }
1168
1169 // Reads and returns the Boolean environment variable corresponding to
1170 // the given flag; if it's not set, returns default_value.
1171 //
1172 // The value is considered true iff it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)1173 bool BoolFromGTestEnv(const char* flag, bool default_value) {
1174 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1175 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1176 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1177 const std::string env_var = FlagToEnvVar(flag);
1178 const char* const string_value = posix::GetEnv(env_var.c_str());
1179 return string_value == NULL ?
1180 default_value : strcmp(string_value, "0") != 0;
1181 }
1182
1183 // Reads and returns a 32-bit integer stored in the environment
1184 // variable corresponding to the given flag; if it isn't set or
1185 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)1186 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
1187 #if defined(GTEST_GET_INT32_FROM_ENV_)
1188 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1189 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1190 const std::string env_var = FlagToEnvVar(flag);
1191 const char* const string_value = posix::GetEnv(env_var.c_str());
1192 if (string_value == NULL) {
1193 // The environment variable is not set.
1194 return default_value;
1195 }
1196
1197 Int32 result = default_value;
1198 if (!ParseInt32(Message() << "Environment variable " << env_var,
1199 string_value, &result)) {
1200 printf("The default value %s is used.\n",
1201 (Message() << default_value).GetString().c_str());
1202 fflush(stdout);
1203 return default_value;
1204 }
1205
1206 return result;
1207 }
1208
1209 // Reads and returns the string environment variable corresponding to
1210 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)1211 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
1212 #if defined(GTEST_GET_STRING_FROM_ENV_)
1213 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1214 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
1215 const std::string env_var = FlagToEnvVar(flag);
1216 const char* const value = posix::GetEnv(env_var.c_str());
1217 return value == NULL ? default_value : value;
1218 }
1219
1220 } // namespace internal
1221 } // namespace testing
1222