Update GoogleTest to v1.8.1
[gromacs.git] / src / external / googletest / googletest / src / gtest-port.cc
blobfecb5d11c21296a9181a11280226067b643edd05
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.
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.
31 #include "gtest/internal/gtest-port.h"
33 #include <limits.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <fstream>
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
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
54 #if GTEST_OS_QNX
55 # include <devctl.h>
56 # include <fcntl.h>
57 # include <sys/procfs.h>
58 #endif // GTEST_OS_QNX
60 #if GTEST_OS_AIX
61 # include <procinfo.h>
62 # include <sys/types.h>
63 #endif // GTEST_OS_AIX
65 #if GTEST_OS_FUCHSIA
66 # include <zircon/process.h>
67 # include <zircon/syscalls.h>
68 #endif // GTEST_OS_FUCHSIA
70 #include "gtest/gtest-spi.h"
71 #include "gtest/gtest-message.h"
72 #include "gtest/internal/gtest-internal.h"
73 #include "gtest/internal/gtest-string.h"
74 #include "src/gtest-internal-inl.h"
76 namespace testing {
77 namespace internal {
79 #if defined(_MSC_VER) || defined(__BORLANDC__)
80 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
81 const int kStdOutFileno = 1;
82 const int kStdErrFileno = 2;
83 #else
84 const int kStdOutFileno = STDOUT_FILENO;
85 const int kStdErrFileno = STDERR_FILENO;
86 #endif // _MSC_VER
88 #if GTEST_OS_LINUX
90 namespace {
91 template <typename T>
92 T ReadProcFileField(const std::string& filename, int field) {
93 std::string dummy;
94 std::ifstream file(filename.c_str());
95 while (field-- > 0) {
96 file >> dummy;
98 T output = 0;
99 file >> output;
100 return output;
102 } // namespace
104 // Returns the number of active threads, or 0 when there is an error.
105 size_t GetThreadCount() {
106 const std::string filename =
107 (Message() << "/proc/" << getpid() << "/stat").GetString();
108 return ReadProcFileField<int>(filename, 19);
111 #elif GTEST_OS_MAC
113 size_t GetThreadCount() {
114 const task_t task = mach_task_self();
115 mach_msg_type_number_t thread_count;
116 thread_act_array_t thread_list;
117 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
118 if (status == KERN_SUCCESS) {
119 // task_threads allocates resources in thread_list and we need to free them
120 // to avoid leaks.
121 vm_deallocate(task,
122 reinterpret_cast<vm_address_t>(thread_list),
123 sizeof(thread_t) * thread_count);
124 return static_cast<size_t>(thread_count);
125 } else {
126 return 0;
130 #elif GTEST_OS_QNX
132 // Returns the number of threads running in the process, or 0 to indicate that
133 // we cannot detect it.
134 size_t GetThreadCount() {
135 const int fd = open("/proc/self/as", O_RDONLY);
136 if (fd < 0) {
137 return 0;
139 procfs_info process_info;
140 const int status =
141 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
142 close(fd);
143 if (status == EOK) {
144 return static_cast<size_t>(process_info.num_threads);
145 } else {
146 return 0;
150 #elif GTEST_OS_AIX
152 size_t GetThreadCount() {
153 struct procentry64 entry;
154 pid_t pid = getpid();
155 int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
156 if (status == 1) {
157 return entry.pi_thcount;
158 } else {
159 return 0;
163 #elif GTEST_OS_FUCHSIA
165 size_t GetThreadCount() {
166 int dummy_buffer;
167 size_t avail;
168 zx_status_t status = zx_object_get_info(
169 zx_process_self(),
170 ZX_INFO_PROCESS_THREADS,
171 &dummy_buffer,
173 nullptr,
174 &avail);
175 if (status == ZX_OK) {
176 return avail;
177 } else {
178 return 0;
182 #else
184 size_t GetThreadCount() {
185 // There's no portable way to detect the number of threads, so we just
186 // return 0 to indicate that we cannot detect it.
187 return 0;
190 #endif // GTEST_OS_LINUX
192 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
194 void SleepMilliseconds(int n) {
195 ::Sleep(n);
198 AutoHandle::AutoHandle()
199 : handle_(INVALID_HANDLE_VALUE) {}
201 AutoHandle::AutoHandle(Handle handle)
202 : handle_(handle) {}
204 AutoHandle::~AutoHandle() {
205 Reset();
208 AutoHandle::Handle AutoHandle::Get() const {
209 return handle_;
212 void AutoHandle::Reset() {
213 Reset(INVALID_HANDLE_VALUE);
216 void AutoHandle::Reset(HANDLE handle) {
217 // Resetting with the same handle we already own is invalid.
218 if (handle_ != handle) {
219 if (IsCloseable()) {
220 ::CloseHandle(handle_);
222 handle_ = handle;
223 } else {
224 GTEST_CHECK_(!IsCloseable())
225 << "Resetting a valid handle to itself is likely a programmer error "
226 "and thus not allowed.";
230 bool AutoHandle::IsCloseable() const {
231 // Different Windows APIs may use either of these values to represent an
232 // invalid handle.
233 return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
236 Notification::Notification()
237 : event_(::CreateEvent(NULL, // Default security attributes.
238 TRUE, // Do not reset automatically.
239 FALSE, // Initially unset.
240 NULL)) { // Anonymous event.
241 GTEST_CHECK_(event_.Get() != NULL);
244 void Notification::Notify() {
245 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
248 void Notification::WaitForNotification() {
249 GTEST_CHECK_(
250 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
253 Mutex::Mutex()
254 : owner_thread_id_(0),
255 type_(kDynamic),
256 critical_section_init_phase_(0),
257 critical_section_(new CRITICAL_SECTION) {
258 ::InitializeCriticalSection(critical_section_);
261 Mutex::~Mutex() {
262 // Static mutexes are leaked intentionally. It is not thread-safe to try
263 // to clean them up.
264 // FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires
265 // nothing to clean it up but is available only on Vista and later.
266 // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks
267 if (type_ == kDynamic) {
268 ::DeleteCriticalSection(critical_section_);
269 delete critical_section_;
270 critical_section_ = NULL;
274 void Mutex::Lock() {
275 ThreadSafeLazyInit();
276 ::EnterCriticalSection(critical_section_);
277 owner_thread_id_ = ::GetCurrentThreadId();
280 void Mutex::Unlock() {
281 ThreadSafeLazyInit();
282 // We don't protect writing to owner_thread_id_ here, as it's the
283 // caller's responsibility to ensure that the current thread holds the
284 // mutex when this is called.
285 owner_thread_id_ = 0;
286 ::LeaveCriticalSection(critical_section_);
289 // Does nothing if the current thread holds the mutex. Otherwise, crashes
290 // with high probability.
291 void Mutex::AssertHeld() {
292 ThreadSafeLazyInit();
293 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
294 << "The current thread is not holding the mutex @" << this;
297 namespace {
299 // Use the RAII idiom to flag mem allocs that are intentionally never
300 // deallocated. The motivation is to silence the false positive mem leaks
301 // that are reported by the debug version of MS's CRT which can only detect
302 // if an alloc is missing a matching deallocation.
303 // Example:
304 // MemoryIsNotDeallocated memory_is_not_deallocated;
305 // critical_section_ = new CRITICAL_SECTION;
307 class MemoryIsNotDeallocated
309 public:
310 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
311 #ifdef _MSC_VER
312 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
313 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
314 // doesn't report mem leak if there's no matching deallocation.
315 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
316 #endif // _MSC_VER
319 ~MemoryIsNotDeallocated() {
320 #ifdef _MSC_VER
321 // Restore the original _CRTDBG_ALLOC_MEM_DF flag
322 _CrtSetDbgFlag(old_crtdbg_flag_);
323 #endif // _MSC_VER
326 private:
327 int old_crtdbg_flag_;
329 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
332 } // namespace
334 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
335 void Mutex::ThreadSafeLazyInit() {
336 // Dynamic mutexes are initialized in the constructor.
337 if (type_ == kStatic) {
338 switch (
339 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
340 case 0:
341 // If critical_section_init_phase_ was 0 before the exchange, we
342 // are the first to test it and need to perform the initialization.
343 owner_thread_id_ = 0;
345 // Use RAII to flag that following mem alloc is never deallocated.
346 MemoryIsNotDeallocated memory_is_not_deallocated;
347 critical_section_ = new CRITICAL_SECTION;
349 ::InitializeCriticalSection(critical_section_);
350 // Updates the critical_section_init_phase_ to 2 to signal
351 // initialization complete.
352 GTEST_CHECK_(::InterlockedCompareExchange(
353 &critical_section_init_phase_, 2L, 1L) ==
354 1L);
355 break;
356 case 1:
357 // Somebody else is already initializing the mutex; spin until they
358 // are done.
359 while (::InterlockedCompareExchange(&critical_section_init_phase_,
361 2L) != 2L) {
362 // Possibly yields the rest of the thread's time slice to other
363 // threads.
364 ::Sleep(0);
366 break;
368 case 2:
369 break; // The mutex is already initialized and ready for use.
371 default:
372 GTEST_CHECK_(false)
373 << "Unexpected value of critical_section_init_phase_ "
374 << "while initializing a static mutex.";
379 namespace {
381 class ThreadWithParamSupport : public ThreadWithParamBase {
382 public:
383 static HANDLE CreateThread(Runnable* runnable,
384 Notification* thread_can_start) {
385 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
386 DWORD thread_id;
387 // FIXME: Consider to use _beginthreadex instead.
388 HANDLE thread_handle = ::CreateThread(
389 NULL, // Default security.
390 0, // Default stack size.
391 &ThreadWithParamSupport::ThreadMain,
392 param, // Parameter to ThreadMainStatic
393 0x0, // Default creation flags.
394 &thread_id); // Need a valid pointer for the call to work under Win98.
395 GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
396 << ::GetLastError() << ".";
397 if (thread_handle == NULL) {
398 delete param;
400 return thread_handle;
403 private:
404 struct ThreadMainParam {
405 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
406 : runnable_(runnable),
407 thread_can_start_(thread_can_start) {
409 scoped_ptr<Runnable> runnable_;
410 // Does not own.
411 Notification* thread_can_start_;
414 static DWORD WINAPI ThreadMain(void* ptr) {
415 // Transfers ownership.
416 scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
417 if (param->thread_can_start_ != NULL)
418 param->thread_can_start_->WaitForNotification();
419 param->runnable_->Run();
420 return 0;
423 // Prohibit instantiation.
424 ThreadWithParamSupport();
426 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
429 } // namespace
431 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
432 Notification* thread_can_start)
433 : thread_(ThreadWithParamSupport::CreateThread(runnable,
434 thread_can_start)) {
437 ThreadWithParamBase::~ThreadWithParamBase() {
438 Join();
441 void ThreadWithParamBase::Join() {
442 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
443 << "Failed to join the thread with error " << ::GetLastError() << ".";
446 // Maps a thread to a set of ThreadIdToThreadLocals that have values
447 // instantiated on that thread and notifies them when the thread exits. A
448 // ThreadLocal instance is expected to persist until all threads it has
449 // values on have terminated.
450 class ThreadLocalRegistryImpl {
451 public:
452 // Registers thread_local_instance as having value on the current thread.
453 // Returns a value that can be used to identify the thread from other threads.
454 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
455 const ThreadLocalBase* thread_local_instance) {
456 DWORD current_thread = ::GetCurrentThreadId();
457 MutexLock lock(&mutex_);
458 ThreadIdToThreadLocals* const thread_to_thread_locals =
459 GetThreadLocalsMapLocked();
460 ThreadIdToThreadLocals::iterator thread_local_pos =
461 thread_to_thread_locals->find(current_thread);
462 if (thread_local_pos == thread_to_thread_locals->end()) {
463 thread_local_pos = thread_to_thread_locals->insert(
464 std::make_pair(current_thread, ThreadLocalValues())).first;
465 StartWatcherThreadFor(current_thread);
467 ThreadLocalValues& thread_local_values = thread_local_pos->second;
468 ThreadLocalValues::iterator value_pos =
469 thread_local_values.find(thread_local_instance);
470 if (value_pos == thread_local_values.end()) {
471 value_pos =
472 thread_local_values
473 .insert(std::make_pair(
474 thread_local_instance,
475 linked_ptr<ThreadLocalValueHolderBase>(
476 thread_local_instance->NewValueForCurrentThread())))
477 .first;
479 return value_pos->second.get();
482 static void OnThreadLocalDestroyed(
483 const ThreadLocalBase* thread_local_instance) {
484 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
485 // Clean up the ThreadLocalValues data structure while holding the lock, but
486 // defer the destruction of the ThreadLocalValueHolderBases.
488 MutexLock lock(&mutex_);
489 ThreadIdToThreadLocals* const thread_to_thread_locals =
490 GetThreadLocalsMapLocked();
491 for (ThreadIdToThreadLocals::iterator it =
492 thread_to_thread_locals->begin();
493 it != thread_to_thread_locals->end();
494 ++it) {
495 ThreadLocalValues& thread_local_values = it->second;
496 ThreadLocalValues::iterator value_pos =
497 thread_local_values.find(thread_local_instance);
498 if (value_pos != thread_local_values.end()) {
499 value_holders.push_back(value_pos->second);
500 thread_local_values.erase(value_pos);
501 // This 'if' can only be successful at most once, so theoretically we
502 // could break out of the loop here, but we don't bother doing so.
506 // Outside the lock, let the destructor for 'value_holders' deallocate the
507 // ThreadLocalValueHolderBases.
510 static void OnThreadExit(DWORD thread_id) {
511 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
512 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
513 // Clean up the ThreadIdToThreadLocals data structure while holding the
514 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
516 MutexLock lock(&mutex_);
517 ThreadIdToThreadLocals* const thread_to_thread_locals =
518 GetThreadLocalsMapLocked();
519 ThreadIdToThreadLocals::iterator thread_local_pos =
520 thread_to_thread_locals->find(thread_id);
521 if (thread_local_pos != thread_to_thread_locals->end()) {
522 ThreadLocalValues& thread_local_values = thread_local_pos->second;
523 for (ThreadLocalValues::iterator value_pos =
524 thread_local_values.begin();
525 value_pos != thread_local_values.end();
526 ++value_pos) {
527 value_holders.push_back(value_pos->second);
529 thread_to_thread_locals->erase(thread_local_pos);
532 // Outside the lock, let the destructor for 'value_holders' deallocate the
533 // ThreadLocalValueHolderBases.
536 private:
537 // In a particular thread, maps a ThreadLocal object to its value.
538 typedef std::map<const ThreadLocalBase*,
539 linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
540 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
541 // thread's ID.
542 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
544 // Holds the thread id and thread handle that we pass from
545 // StartWatcherThreadFor to WatcherThreadFunc.
546 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
548 static void StartWatcherThreadFor(DWORD thread_id) {
549 // The returned handle will be kept in thread_map and closed by
550 // watcher_thread in WatcherThreadFunc.
551 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
552 FALSE,
553 thread_id);
554 GTEST_CHECK_(thread != NULL);
555 // We need to pass a valid thread ID pointer into CreateThread for it
556 // to work correctly under Win98.
557 DWORD watcher_thread_id;
558 HANDLE watcher_thread = ::CreateThread(
559 NULL, // Default security.
560 0, // Default stack size
561 &ThreadLocalRegistryImpl::WatcherThreadFunc,
562 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
563 CREATE_SUSPENDED,
564 &watcher_thread_id);
565 GTEST_CHECK_(watcher_thread != NULL);
566 // Give the watcher thread the same priority as ours to avoid being
567 // blocked by it.
568 ::SetThreadPriority(watcher_thread,
569 ::GetThreadPriority(::GetCurrentThread()));
570 ::ResumeThread(watcher_thread);
571 ::CloseHandle(watcher_thread);
574 // Monitors exit from a given thread and notifies those
575 // ThreadIdToThreadLocals about thread termination.
576 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
577 const ThreadIdAndHandle* tah =
578 reinterpret_cast<const ThreadIdAndHandle*>(param);
579 GTEST_CHECK_(
580 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
581 OnThreadExit(tah->first);
582 ::CloseHandle(tah->second);
583 delete tah;
584 return 0;
587 // Returns map of thread local instances.
588 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
589 mutex_.AssertHeld();
590 MemoryIsNotDeallocated memory_is_not_deallocated;
591 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
592 return map;
595 // Protects access to GetThreadLocalsMapLocked() and its return value.
596 static Mutex mutex_;
597 // Protects access to GetThreadMapLocked() and its return value.
598 static Mutex thread_map_mutex_;
601 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
602 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
604 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
605 const ThreadLocalBase* thread_local_instance) {
606 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
607 thread_local_instance);
610 void ThreadLocalRegistry::OnThreadLocalDestroyed(
611 const ThreadLocalBase* thread_local_instance) {
612 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
615 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
617 #if GTEST_USES_POSIX_RE
619 // Implements RE. Currently only needed for death tests.
621 RE::~RE() {
622 if (is_valid_) {
623 // regfree'ing an invalid regex might crash because the content
624 // of the regex is undefined. Since the regex's are essentially
625 // the same, one cannot be valid (or invalid) without the other
626 // being so too.
627 regfree(&partial_regex_);
628 regfree(&full_regex_);
630 free(const_cast<char*>(pattern_));
633 // Returns true iff regular expression re matches the entire str.
634 bool RE::FullMatch(const char* str, const RE& re) {
635 if (!re.is_valid_) return false;
637 regmatch_t match;
638 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
641 // Returns true iff regular expression re matches a substring of str
642 // (including str itself).
643 bool RE::PartialMatch(const char* str, const RE& re) {
644 if (!re.is_valid_) return false;
646 regmatch_t match;
647 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
650 // Initializes an RE from its string representation.
651 void RE::Init(const char* regex) {
652 pattern_ = posix::StrDup(regex);
654 // Reserves enough bytes to hold the regular expression used for a
655 // full match.
656 const size_t full_regex_len = strlen(regex) + 10;
657 char* const full_pattern = new char[full_regex_len];
659 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
660 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
661 // We want to call regcomp(&partial_regex_, ...) even if the
662 // previous expression returns false. Otherwise partial_regex_ may
663 // not be properly initialized can may cause trouble when it's
664 // freed.
666 // Some implementation of POSIX regex (e.g. on at least some
667 // versions of Cygwin) doesn't accept the empty string as a valid
668 // regex. We change it to an equivalent form "()" to be safe.
669 if (is_valid_) {
670 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
671 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
673 EXPECT_TRUE(is_valid_)
674 << "Regular expression \"" << regex
675 << "\" is not a valid POSIX Extended regular expression.";
677 delete[] full_pattern;
680 #elif GTEST_USES_SIMPLE_RE
682 // Returns true iff ch appears anywhere in str (excluding the
683 // terminating '\0' character).
684 bool IsInSet(char ch, const char* str) {
685 return ch != '\0' && strchr(str, ch) != NULL;
688 // Returns true iff ch belongs to the given classification. Unlike
689 // similar functions in <ctype.h>, these aren't affected by the
690 // current locale.
691 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
692 bool IsAsciiPunct(char ch) {
693 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
695 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
696 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
697 bool IsAsciiWordChar(char ch) {
698 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
699 ('0' <= ch && ch <= '9') || ch == '_';
702 // Returns true iff "\\c" is a supported escape sequence.
703 bool IsValidEscape(char c) {
704 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
707 // Returns true iff the given atom (specified by escaped and pattern)
708 // matches ch. The result is undefined if the atom is invalid.
709 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
710 if (escaped) { // "\\p" where p is pattern_char.
711 switch (pattern_char) {
712 case 'd': return IsAsciiDigit(ch);
713 case 'D': return !IsAsciiDigit(ch);
714 case 'f': return ch == '\f';
715 case 'n': return ch == '\n';
716 case 'r': return ch == '\r';
717 case 's': return IsAsciiWhiteSpace(ch);
718 case 'S': return !IsAsciiWhiteSpace(ch);
719 case 't': return ch == '\t';
720 case 'v': return ch == '\v';
721 case 'w': return IsAsciiWordChar(ch);
722 case 'W': return !IsAsciiWordChar(ch);
724 return IsAsciiPunct(pattern_char) && pattern_char == ch;
727 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
730 // Helper function used by ValidateRegex() to format error messages.
731 static std::string FormatRegexSyntaxError(const char* regex, int index) {
732 return (Message() << "Syntax error at index " << index
733 << " in simple regular expression \"" << regex << "\": ").GetString();
736 // Generates non-fatal failures and returns false if regex is invalid;
737 // otherwise returns true.
738 bool ValidateRegex(const char* regex) {
739 if (regex == NULL) {
740 // FIXME: fix the source file location in the
741 // assertion failures to match where the regex is used in user
742 // code.
743 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
744 return false;
747 bool is_valid = true;
749 // True iff ?, *, or + can follow the previous atom.
750 bool prev_repeatable = false;
751 for (int i = 0; regex[i]; i++) {
752 if (regex[i] == '\\') { // An escape sequence
753 i++;
754 if (regex[i] == '\0') {
755 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
756 << "'\\' cannot appear at the end.";
757 return false;
760 if (!IsValidEscape(regex[i])) {
761 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
762 << "invalid escape sequence \"\\" << regex[i] << "\".";
763 is_valid = false;
765 prev_repeatable = true;
766 } else { // Not an escape sequence.
767 const char ch = regex[i];
769 if (ch == '^' && i > 0) {
770 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
771 << "'^' can only appear at the beginning.";
772 is_valid = false;
773 } else if (ch == '$' && regex[i + 1] != '\0') {
774 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
775 << "'$' can only appear at the end.";
776 is_valid = false;
777 } else if (IsInSet(ch, "()[]{}|")) {
778 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
779 << "'" << ch << "' is unsupported.";
780 is_valid = false;
781 } else if (IsRepeat(ch) && !prev_repeatable) {
782 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
783 << "'" << ch << "' can only follow a repeatable token.";
784 is_valid = false;
787 prev_repeatable = !IsInSet(ch, "^$?*+");
791 return is_valid;
794 // Matches a repeated regex atom followed by a valid simple regular
795 // expression. The regex atom is defined as c if escaped is false,
796 // or \c otherwise. repeat is the repetition meta character (?, *,
797 // or +). The behavior is undefined if str contains too many
798 // characters to be indexable by size_t, in which case the test will
799 // probably time out anyway. We are fine with this limitation as
800 // std::string has it too.
801 bool MatchRepetitionAndRegexAtHead(
802 bool escaped, char c, char repeat, const char* regex,
803 const char* str) {
804 const size_t min_count = (repeat == '+') ? 1 : 0;
805 const size_t max_count = (repeat == '?') ? 1 :
806 static_cast<size_t>(-1) - 1;
807 // We cannot call numeric_limits::max() as it conflicts with the
808 // max() macro on Windows.
810 for (size_t i = 0; i <= max_count; ++i) {
811 // We know that the atom matches each of the first i characters in str.
812 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
813 // We have enough matches at the head, and the tail matches too.
814 // Since we only care about *whether* the pattern matches str
815 // (as opposed to *how* it matches), there is no need to find a
816 // greedy match.
817 return true;
819 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
820 return false;
822 return false;
825 // Returns true iff regex matches a prefix of str. regex must be a
826 // valid simple regular expression and not start with "^", or the
827 // result is undefined.
828 bool MatchRegexAtHead(const char* regex, const char* str) {
829 if (*regex == '\0') // An empty regex matches a prefix of anything.
830 return true;
832 // "$" only matches the end of a string. Note that regex being
833 // valid guarantees that there's nothing after "$" in it.
834 if (*regex == '$')
835 return *str == '\0';
837 // Is the first thing in regex an escape sequence?
838 const bool escaped = *regex == '\\';
839 if (escaped)
840 ++regex;
841 if (IsRepeat(regex[1])) {
842 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
843 // here's an indirect recursion. It terminates as the regex gets
844 // shorter in each recursion.
845 return MatchRepetitionAndRegexAtHead(
846 escaped, regex[0], regex[1], regex + 2, str);
847 } else {
848 // regex isn't empty, isn't "$", and doesn't start with a
849 // repetition. We match the first atom of regex with the first
850 // character of str and recurse.
851 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
852 MatchRegexAtHead(regex + 1, str + 1);
856 // Returns true iff regex matches any substring of str. regex must be
857 // a valid simple regular expression, or the result is undefined.
859 // The algorithm is recursive, but the recursion depth doesn't exceed
860 // the regex length, so we won't need to worry about running out of
861 // stack space normally. In rare cases the time complexity can be
862 // exponential with respect to the regex length + the string length,
863 // but usually it's must faster (often close to linear).
864 bool MatchRegexAnywhere(const char* regex, const char* str) {
865 if (regex == NULL || str == NULL)
866 return false;
868 if (*regex == '^')
869 return MatchRegexAtHead(regex + 1, str);
871 // A successful match can be anywhere in str.
872 do {
873 if (MatchRegexAtHead(regex, str))
874 return true;
875 } while (*str++ != '\0');
876 return false;
879 // Implements the RE class.
881 RE::~RE() {
882 free(const_cast<char*>(pattern_));
883 free(const_cast<char*>(full_pattern_));
886 // Returns true iff regular expression re matches the entire str.
887 bool RE::FullMatch(const char* str, const RE& re) {
888 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
891 // Returns true iff regular expression re matches a substring of str
892 // (including str itself).
893 bool RE::PartialMatch(const char* str, const RE& re) {
894 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
897 // Initializes an RE from its string representation.
898 void RE::Init(const char* regex) {
899 pattern_ = full_pattern_ = NULL;
900 if (regex != NULL) {
901 pattern_ = posix::StrDup(regex);
904 is_valid_ = ValidateRegex(regex);
905 if (!is_valid_) {
906 // No need to calculate the full pattern when the regex is invalid.
907 return;
910 const size_t len = strlen(regex);
911 // Reserves enough bytes to hold the regular expression used for a
912 // full match: we need space to prepend a '^', append a '$', and
913 // terminate the string with '\0'.
914 char* buffer = static_cast<char*>(malloc(len + 3));
915 full_pattern_ = buffer;
917 if (*regex != '^')
918 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
920 // We don't use snprintf or strncpy, as they trigger a warning when
921 // compiled with VC++ 8.0.
922 memcpy(buffer, regex, len);
923 buffer += len;
925 if (len == 0 || regex[len - 1] != '$')
926 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
928 *buffer = '\0';
931 #endif // GTEST_USES_POSIX_RE
933 const char kUnknownFile[] = "unknown file";
935 // Formats a source file path and a line number as they would appear
936 // in an error message from the compiler used to compile this code.
937 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
938 const std::string file_name(file == NULL ? kUnknownFile : file);
940 if (line < 0) {
941 return file_name + ":";
943 #ifdef _MSC_VER
944 return file_name + "(" + StreamableToString(line) + "):";
945 #else
946 return file_name + ":" + StreamableToString(line) + ":";
947 #endif // _MSC_VER
950 // Formats a file location for compiler-independent XML output.
951 // Although this function is not platform dependent, we put it next to
952 // FormatFileLocation in order to contrast the two functions.
953 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
954 // to the file location it produces, unlike FormatFileLocation().
955 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
956 const char* file, int line) {
957 const std::string file_name(file == NULL ? kUnknownFile : file);
959 if (line < 0)
960 return file_name;
961 else
962 return file_name + ":" + StreamableToString(line);
965 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
966 : severity_(severity) {
967 const char* const marker =
968 severity == GTEST_INFO ? "[ INFO ]" :
969 severity == GTEST_WARNING ? "[WARNING]" :
970 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
971 GetStream() << ::std::endl << marker << " "
972 << FormatFileLocation(file, line).c_str() << ": ";
975 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
976 GTestLog::~GTestLog() {
977 GetStream() << ::std::endl;
978 if (severity_ == GTEST_FATAL) {
979 fflush(stderr);
980 posix::Abort();
984 // Disable Microsoft deprecation warnings for POSIX functions called from
985 // this class (creat, dup, dup2, and close)
986 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
988 #if GTEST_HAS_STREAM_REDIRECTION
990 // Object that captures an output stream (stdout/stderr).
991 class CapturedStream {
992 public:
993 // The ctor redirects the stream to a temporary file.
994 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
995 # if GTEST_OS_WINDOWS
996 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
997 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
999 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
1000 const UINT success = ::GetTempFileNameA(temp_dir_path,
1001 "gtest_redir",
1002 0, // Generate unique file name.
1003 temp_file_path);
1004 GTEST_CHECK_(success != 0)
1005 << "Unable to create a temporary file in " << temp_dir_path;
1006 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
1007 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
1008 << temp_file_path;
1009 filename_ = temp_file_path;
1010 # else
1011 // There's no guarantee that a test has write access to the current
1012 // directory, so we create the temporary file in the /tmp directory
1013 // instead. We use /tmp on most systems, and /sdcard on Android.
1014 // That's because Android doesn't have /tmp.
1015 # if GTEST_OS_LINUX_ANDROID
1016 // Note: Android applications are expected to call the framework's
1017 // Context.getExternalStorageDirectory() method through JNI to get
1018 // the location of the world-writable SD Card directory. However,
1019 // this requires a Context handle, which cannot be retrieved
1020 // globally from native code. Doing so also precludes running the
1021 // code as part of a regular standalone executable, which doesn't
1022 // run in a Dalvik process (e.g. when running it through 'adb shell').
1024 // The location /sdcard is directly accessible from native code
1025 // and is the only location (unofficially) supported by the Android
1026 // team. It's generally a symlink to the real SD Card mount point
1027 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
1028 // other OEM-customized locations. Never rely on these, and always
1029 // use /sdcard.
1030 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
1031 # else
1032 char name_template[] = "/tmp/captured_stream.XXXXXX";
1033 # endif // GTEST_OS_LINUX_ANDROID
1034 const int captured_fd = mkstemp(name_template);
1035 filename_ = name_template;
1036 # endif // GTEST_OS_WINDOWS
1037 fflush(NULL);
1038 dup2(captured_fd, fd_);
1039 close(captured_fd);
1042 ~CapturedStream() {
1043 remove(filename_.c_str());
1046 std::string GetCapturedString() {
1047 if (uncaptured_fd_ != -1) {
1048 // Restores the original stream.
1049 fflush(NULL);
1050 dup2(uncaptured_fd_, fd_);
1051 close(uncaptured_fd_);
1052 uncaptured_fd_ = -1;
1055 FILE* const file = posix::FOpen(filename_.c_str(), "r");
1056 const std::string content = ReadEntireFile(file);
1057 posix::FClose(file);
1058 return content;
1061 private:
1062 const int fd_; // A stream to capture.
1063 int uncaptured_fd_;
1064 // Name of the temporary file holding the stderr output.
1065 ::std::string filename_;
1067 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
1070 GTEST_DISABLE_MSC_DEPRECATED_POP_()
1072 static CapturedStream* g_captured_stderr = NULL;
1073 static CapturedStream* g_captured_stdout = NULL;
1075 // Starts capturing an output stream (stdout/stderr).
1076 static void CaptureStream(int fd, const char* stream_name,
1077 CapturedStream** stream) {
1078 if (*stream != NULL) {
1079 GTEST_LOG_(FATAL) << "Only one " << stream_name
1080 << " capturer can exist at a time.";
1082 *stream = new CapturedStream(fd);
1085 // Stops capturing the output stream and returns the captured string.
1086 static std::string GetCapturedStream(CapturedStream** captured_stream) {
1087 const std::string content = (*captured_stream)->GetCapturedString();
1089 delete *captured_stream;
1090 *captured_stream = NULL;
1092 return content;
1095 // Starts capturing stdout.
1096 void CaptureStdout() {
1097 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
1100 // Starts capturing stderr.
1101 void CaptureStderr() {
1102 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
1105 // Stops capturing stdout and returns the captured string.
1106 std::string GetCapturedStdout() {
1107 return GetCapturedStream(&g_captured_stdout);
1110 // Stops capturing stderr and returns the captured string.
1111 std::string GetCapturedStderr() {
1112 return GetCapturedStream(&g_captured_stderr);
1115 #endif // GTEST_HAS_STREAM_REDIRECTION
1121 size_t GetFileSize(FILE* file) {
1122 fseek(file, 0, SEEK_END);
1123 return static_cast<size_t>(ftell(file));
1126 std::string ReadEntireFile(FILE* file) {
1127 const size_t file_size = GetFileSize(file);
1128 char* const buffer = new char[file_size];
1130 size_t bytes_last_read = 0; // # of bytes read in the last fread()
1131 size_t bytes_read = 0; // # of bytes read so far
1133 fseek(file, 0, SEEK_SET);
1135 // Keeps reading the file until we cannot read further or the
1136 // pre-determined file size is reached.
1137 do {
1138 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
1139 bytes_read += bytes_last_read;
1140 } while (bytes_last_read > 0 && bytes_read < file_size);
1142 const std::string content(buffer, bytes_read);
1143 delete[] buffer;
1145 return content;
1148 #if GTEST_HAS_DEATH_TEST
1149 static const std::vector<std::string>* g_injected_test_argvs = NULL; // Owned.
1151 std::vector<std::string> GetInjectableArgvs() {
1152 if (g_injected_test_argvs != NULL) {
1153 return *g_injected_test_argvs;
1155 return GetArgvs();
1158 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
1159 if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
1160 g_injected_test_argvs = new_argvs;
1163 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
1164 SetInjectableArgvs(
1165 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
1168 #if GTEST_HAS_GLOBAL_STRING
1169 void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
1170 SetInjectableArgvs(
1171 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
1173 #endif // GTEST_HAS_GLOBAL_STRING
1175 void ClearInjectableArgvs() {
1176 delete g_injected_test_argvs;
1177 g_injected_test_argvs = NULL;
1179 #endif // GTEST_HAS_DEATH_TEST
1181 #if GTEST_OS_WINDOWS_MOBILE
1182 namespace posix {
1183 void Abort() {
1184 DebugBreak();
1185 TerminateProcess(GetCurrentProcess(), 1);
1187 } // namespace posix
1188 #endif // GTEST_OS_WINDOWS_MOBILE
1190 // Returns the name of the environment variable corresponding to the
1191 // given flag. For example, FlagToEnvVar("foo") will return
1192 // "GTEST_FOO" in the open-source version.
1193 static std::string FlagToEnvVar(const char* flag) {
1194 const std::string full_flag =
1195 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
1197 Message env_var;
1198 for (size_t i = 0; i != full_flag.length(); i++) {
1199 env_var << ToUpper(full_flag.c_str()[i]);
1202 return env_var.GetString();
1205 // Parses 'str' for a 32-bit signed integer. If successful, writes
1206 // the result to *value and returns true; otherwise leaves *value
1207 // unchanged and returns false.
1208 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
1209 // Parses the environment variable as a decimal integer.
1210 char* end = NULL;
1211 const long long_value = strtol(str, &end, 10); // NOLINT
1213 // Has strtol() consumed all characters in the string?
1214 if (*end != '\0') {
1215 // No - an invalid character was encountered.
1216 Message msg;
1217 msg << "WARNING: " << src_text
1218 << " is expected to be a 32-bit integer, but actually"
1219 << " has value \"" << str << "\".\n";
1220 printf("%s", msg.GetString().c_str());
1221 fflush(stdout);
1222 return false;
1225 // Is the parsed value in the range of an Int32?
1226 const Int32 result = static_cast<Int32>(long_value);
1227 if (long_value == LONG_MAX || long_value == LONG_MIN ||
1228 // The parsed value overflows as a long. (strtol() returns
1229 // LONG_MAX or LONG_MIN when the input overflows.)
1230 result != long_value
1231 // The parsed value overflows as an Int32.
1233 Message msg;
1234 msg << "WARNING: " << src_text
1235 << " is expected to be a 32-bit integer, but actually"
1236 << " has value " << str << ", which overflows.\n";
1237 printf("%s", msg.GetString().c_str());
1238 fflush(stdout);
1239 return false;
1242 *value = result;
1243 return true;
1246 // Reads and returns the Boolean environment variable corresponding to
1247 // the given flag; if it's not set, returns default_value.
1249 // The value is considered true iff it's not "0".
1250 bool BoolFromGTestEnv(const char* flag, bool default_value) {
1251 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1252 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1253 #else
1254 const std::string env_var = FlagToEnvVar(flag);
1255 const char* const string_value = posix::GetEnv(env_var.c_str());
1256 return string_value == NULL ?
1257 default_value : strcmp(string_value, "0") != 0;
1258 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1261 // Reads and returns a 32-bit integer stored in the environment
1262 // variable corresponding to the given flag; if it isn't set or
1263 // doesn't represent a valid 32-bit integer, returns default_value.
1264 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
1265 #if defined(GTEST_GET_INT32_FROM_ENV_)
1266 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1267 #else
1268 const std::string env_var = FlagToEnvVar(flag);
1269 const char* const string_value = posix::GetEnv(env_var.c_str());
1270 if (string_value == NULL) {
1271 // The environment variable is not set.
1272 return default_value;
1275 Int32 result = default_value;
1276 if (!ParseInt32(Message() << "Environment variable " << env_var,
1277 string_value, &result)) {
1278 printf("The default value %s is used.\n",
1279 (Message() << default_value).GetString().c_str());
1280 fflush(stdout);
1281 return default_value;
1284 return result;
1285 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1288 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
1289 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
1290 // system. The value of XML_OUTPUT_FILE is a filename without the
1291 // "xml:" prefix of GTEST_OUTPUT.
1292 // Note that this is meant to be called at the call site so it does
1293 // not check that the flag is 'output'
1294 // In essence this checks an env variable called XML_OUTPUT_FILE
1295 // and if it is set we prepend "xml:" to its value, if it not set we return ""
1296 std::string OutputFlagAlsoCheckEnvVar(){
1297 std::string default_value_for_output_flag = "";
1298 const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
1299 if (NULL != xml_output_file_env) {
1300 default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
1302 return default_value_for_output_flag;
1305 // Reads and returns the string environment variable corresponding to
1306 // the given flag; if it's not set, returns default_value.
1307 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
1308 #if defined(GTEST_GET_STRING_FROM_ENV_)
1309 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1310 #else
1311 const std::string env_var = FlagToEnvVar(flag);
1312 const char* const value = posix::GetEnv(env_var.c_str());
1313 return value == NULL ? default_value : value;
1314 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
1317 } // namespace internal
1318 } // namespace testing