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