1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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"
44 # include <sys/stat.h>
45 # include <map> // Used in ThreadLocal.
51 #endif // GTEST_OS_WINDOWS
54 # include <mach/mach_init.h>
55 # include <mach/task.h>
56 # include <mach/vm_map.h>
57 #endif // GTEST_OS_MAC
59 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
60 GTEST_OS_NETBSD || GTEST_OS_OPENBSD
61 # include <sys/sysctl.h>
62 # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
63 # include <sys/user.h>
70 # include <sys/procfs.h>
71 #endif // GTEST_OS_QNX
74 # include <procinfo.h>
75 # include <sys/types.h>
76 #endif // GTEST_OS_AIX
79 # include <zircon/process.h>
80 # include <zircon/syscalls.h>
81 #endif // GTEST_OS_FUCHSIA
84 #import <Foundation/Foundation.h>
85 #endif // GTEST_OS_IOS
87 #include "gtest/gtest-spi.h"
88 #include "gtest/gtest-message.h"
89 #include "gtest/internal/gtest-internal.h"
90 #include "gtest/internal/gtest-string.h"
91 #include "src/gtest-internal-inl.h"
96 #if defined(_MSC_VER) || defined(__BORLANDC__)
97 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
98 const int kStdOutFileno = 1;
99 const int kStdErrFileno = 2;
101 const int kStdOutFileno = STDOUT_FILENO;
102 const int kStdErrFileno = STDERR_FILENO;
108 template <typename T>
109 T ReadProcFileField(const std::string& filename, int field) {
111 std::ifstream file(filename.c_str());
112 while (field-- > 0) {
121 // Returns the number of active threads, or 0 when there is an error.
122 size_t GetThreadCount() {
123 const std::string filename =
124 (Message() << "/proc/" << getpid() << "/stat").GetString();
125 return ReadProcFileField<size_t>(filename, 19);
130 size_t GetThreadCount() {
131 const task_t task = mach_task_self();
132 mach_msg_type_number_t thread_count;
133 thread_act_array_t thread_list;
134 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
135 if (status == KERN_SUCCESS) {
136 // task_threads allocates resources in thread_list and we need to free them
139 reinterpret_cast<vm_address_t>(thread_list),
140 sizeof(thread_t) * thread_count);
141 return static_cast<size_t>(thread_count);
147 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
152 #define KERN_PROC KERN_PROC2
153 #define kinfo_proc kinfo_proc2
156 #if GTEST_OS_DRAGONFLY
157 #define KP_NLWP(kp) (kp.kp_nthreads)
158 #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
159 #define KP_NLWP(kp) (kp.ki_numthreads)
160 #elif GTEST_OS_NETBSD
161 #define KP_NLWP(kp) (kp.p_nlwps)
164 // Returns the number of threads running in the process, or 0 to indicate that
165 // we cannot detect it.
166 size_t GetThreadCount() {
173 sizeof(struct kinfo_proc),
177 u_int miblen = sizeof(mib) / sizeof(mib[0]);
178 struct kinfo_proc info;
179 size_t size = sizeof(info);
180 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
183 return static_cast<size_t>(KP_NLWP(info));
185 #elif GTEST_OS_OPENBSD
187 // Returns the number of threads running in the process, or 0 to indicate that
188 // we cannot detect it.
189 size_t GetThreadCount() {
193 KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
195 sizeof(struct kinfo_proc),
198 u_int miblen = sizeof(mib) / sizeof(mib[0]);
200 // get number of structs
202 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
206 mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
208 // populate array of structs
209 struct kinfo_proc info[mib[5]];
210 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
214 // exclude empty members
216 for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
217 if (info[i].p_tid != -1)
225 // Returns the number of threads running in the process, or 0 to indicate that
226 // we cannot detect it.
227 size_t GetThreadCount() {
228 const int fd = open("/proc/self/as", O_RDONLY);
232 procfs_info process_info;
234 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
237 return static_cast<size_t>(process_info.num_threads);
245 size_t GetThreadCount() {
246 struct procentry64 entry;
247 pid_t pid = getpid();
248 int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
250 return entry.pi_thcount;
256 #elif GTEST_OS_FUCHSIA
258 size_t GetThreadCount() {
261 zx_status_t status = zx_object_get_info(
263 ZX_INFO_PROCESS_THREADS,
268 if (status == ZX_OK) {
277 size_t GetThreadCount() {
278 // There's no portable way to detect the number of threads, so we just
279 // return 0 to indicate that we cannot detect it.
283 #endif // GTEST_OS_LINUX
285 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
287 void SleepMilliseconds(int n) {
288 ::Sleep(static_cast<DWORD>(n));
291 AutoHandle::AutoHandle()
292 : handle_(INVALID_HANDLE_VALUE) {}
294 AutoHandle::AutoHandle(Handle handle)
297 AutoHandle::~AutoHandle() {
301 AutoHandle::Handle AutoHandle::Get() const {
305 void AutoHandle::Reset() {
306 Reset(INVALID_HANDLE_VALUE);
309 void AutoHandle::Reset(HANDLE handle) {
310 // Resetting with the same handle we already own is invalid.
311 if (handle_ != handle) {
313 ::CloseHandle(handle_);
317 GTEST_CHECK_(!IsCloseable())
318 << "Resetting a valid handle to itself is likely a programmer error "
319 "and thus not allowed.";
323 bool AutoHandle::IsCloseable() const {
324 // Different Windows APIs may use either of these values to represent an
326 return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
329 Notification::Notification()
330 : event_(::CreateEvent(nullptr, // Default security attributes.
331 TRUE, // Do not reset automatically.
332 FALSE, // Initially unset.
333 nullptr)) { // Anonymous event.
334 GTEST_CHECK_(event_.Get() != nullptr);
337 void Notification::Notify() {
338 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
341 void Notification::WaitForNotification() {
343 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
347 : owner_thread_id_(0),
349 critical_section_init_phase_(0),
350 critical_section_(new CRITICAL_SECTION) {
351 ::InitializeCriticalSection(critical_section_);
355 // Static mutexes are leaked intentionally. It is not thread-safe to try
357 if (type_ == kDynamic) {
358 ::DeleteCriticalSection(critical_section_);
359 delete critical_section_;
360 critical_section_ = nullptr;
365 ThreadSafeLazyInit();
366 ::EnterCriticalSection(critical_section_);
367 owner_thread_id_ = ::GetCurrentThreadId();
370 void Mutex::Unlock() {
371 ThreadSafeLazyInit();
372 // We don't protect writing to owner_thread_id_ here, as it's the
373 // caller's responsibility to ensure that the current thread holds the
374 // mutex when this is called.
375 owner_thread_id_ = 0;
376 ::LeaveCriticalSection(critical_section_);
379 // Does nothing if the current thread holds the mutex. Otherwise, crashes
380 // with high probability.
381 void Mutex::AssertHeld() {
382 ThreadSafeLazyInit();
383 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
384 << "The current thread is not holding the mutex @" << this;
390 // Use the RAII idiom to flag mem allocs that are intentionally never
391 // deallocated. The motivation is to silence the false positive mem leaks
392 // that are reported by the debug version of MS's CRT which can only detect
393 // if an alloc is missing a matching deallocation.
395 // MemoryIsNotDeallocated memory_is_not_deallocated;
396 // critical_section_ = new CRITICAL_SECTION;
398 class MemoryIsNotDeallocated
401 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
402 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
403 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
404 // doesn't report mem leak if there's no matching deallocation.
405 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
408 ~MemoryIsNotDeallocated() {
409 // Restore the original _CRTDBG_ALLOC_MEM_DF flag
410 _CrtSetDbgFlag(old_crtdbg_flag_);
414 int old_crtdbg_flag_;
416 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
422 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
423 void Mutex::ThreadSafeLazyInit() {
424 // Dynamic mutexes are initialized in the constructor.
425 if (type_ == kStatic) {
427 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
429 // If critical_section_init_phase_ was 0 before the exchange, we
430 // are the first to test it and need to perform the initialization.
431 owner_thread_id_ = 0;
433 // Use RAII to flag that following mem alloc is never deallocated.
435 MemoryIsNotDeallocated memory_is_not_deallocated;
437 critical_section_ = new CRITICAL_SECTION;
439 ::InitializeCriticalSection(critical_section_);
440 // Updates the critical_section_init_phase_ to 2 to signal
441 // initialization complete.
442 GTEST_CHECK_(::InterlockedCompareExchange(
443 &critical_section_init_phase_, 2L, 1L) ==
447 // Somebody else is already initializing the mutex; spin until they
449 while (::InterlockedCompareExchange(&critical_section_init_phase_,
452 // Possibly yields the rest of the thread's time slice to other
459 break; // The mutex is already initialized and ready for use.
463 << "Unexpected value of critical_section_init_phase_ "
464 << "while initializing a static mutex.";
471 class ThreadWithParamSupport : public ThreadWithParamBase {
473 static HANDLE CreateThread(Runnable* runnable,
474 Notification* thread_can_start) {
475 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
477 HANDLE thread_handle = ::CreateThread(
478 nullptr, // Default security.
479 0, // Default stack size.
480 &ThreadWithParamSupport::ThreadMain,
481 param, // Parameter to ThreadMainStatic
482 0x0, // Default creation flags.
483 &thread_id); // Need a valid pointer for the call to work under Win98.
484 GTEST_CHECK_(thread_handle != nullptr)
485 << "CreateThread failed with error " << ::GetLastError() << ".";
486 if (thread_handle == nullptr) {
489 return thread_handle;
493 struct ThreadMainParam {
494 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
495 : runnable_(runnable),
496 thread_can_start_(thread_can_start) {
498 std::unique_ptr<Runnable> runnable_;
500 Notification* thread_can_start_;
503 static DWORD WINAPI ThreadMain(void* ptr) {
504 // Transfers ownership.
505 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
506 if (param->thread_can_start_ != nullptr)
507 param->thread_can_start_->WaitForNotification();
508 param->runnable_->Run();
512 // Prohibit instantiation.
513 ThreadWithParamSupport();
515 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
520 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
521 Notification* thread_can_start)
522 : thread_(ThreadWithParamSupport::CreateThread(runnable,
526 ThreadWithParamBase::~ThreadWithParamBase() {
530 void ThreadWithParamBase::Join() {
531 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
532 << "Failed to join the thread with error " << ::GetLastError() << ".";
535 // Maps a thread to a set of ThreadIdToThreadLocals that have values
536 // instantiated on that thread and notifies them when the thread exits. A
537 // ThreadLocal instance is expected to persist until all threads it has
538 // values on have terminated.
539 class ThreadLocalRegistryImpl {
541 // Registers thread_local_instance as having value on the current thread.
542 // Returns a value that can be used to identify the thread from other threads.
543 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
544 const ThreadLocalBase* thread_local_instance) {
546 MemoryIsNotDeallocated memory_is_not_deallocated;
548 DWORD current_thread = ::GetCurrentThreadId();
549 MutexLock lock(&mutex_);
550 ThreadIdToThreadLocals* const thread_to_thread_locals =
551 GetThreadLocalsMapLocked();
552 ThreadIdToThreadLocals::iterator thread_local_pos =
553 thread_to_thread_locals->find(current_thread);
554 if (thread_local_pos == thread_to_thread_locals->end()) {
555 thread_local_pos = thread_to_thread_locals->insert(
556 std::make_pair(current_thread, ThreadLocalValues())).first;
557 StartWatcherThreadFor(current_thread);
559 ThreadLocalValues& thread_local_values = thread_local_pos->second;
560 ThreadLocalValues::iterator value_pos =
561 thread_local_values.find(thread_local_instance);
562 if (value_pos == thread_local_values.end()) {
565 .insert(std::make_pair(
566 thread_local_instance,
567 std::shared_ptr<ThreadLocalValueHolderBase>(
568 thread_local_instance->NewValueForCurrentThread())))
571 return value_pos->second.get();
574 static void OnThreadLocalDestroyed(
575 const ThreadLocalBase* thread_local_instance) {
576 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
577 // Clean up the ThreadLocalValues data structure while holding the lock, but
578 // defer the destruction of the ThreadLocalValueHolderBases.
580 MutexLock lock(&mutex_);
581 ThreadIdToThreadLocals* const thread_to_thread_locals =
582 GetThreadLocalsMapLocked();
583 for (ThreadIdToThreadLocals::iterator it =
584 thread_to_thread_locals->begin();
585 it != thread_to_thread_locals->end();
587 ThreadLocalValues& thread_local_values = it->second;
588 ThreadLocalValues::iterator value_pos =
589 thread_local_values.find(thread_local_instance);
590 if (value_pos != thread_local_values.end()) {
591 value_holders.push_back(value_pos->second);
592 thread_local_values.erase(value_pos);
593 // This 'if' can only be successful at most once, so theoretically we
594 // could break out of the loop here, but we don't bother doing so.
598 // Outside the lock, let the destructor for 'value_holders' deallocate the
599 // ThreadLocalValueHolderBases.
602 static void OnThreadExit(DWORD thread_id) {
603 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
604 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
605 // Clean up the ThreadIdToThreadLocals data structure while holding the
606 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
608 MutexLock lock(&mutex_);
609 ThreadIdToThreadLocals* const thread_to_thread_locals =
610 GetThreadLocalsMapLocked();
611 ThreadIdToThreadLocals::iterator thread_local_pos =
612 thread_to_thread_locals->find(thread_id);
613 if (thread_local_pos != thread_to_thread_locals->end()) {
614 ThreadLocalValues& thread_local_values = thread_local_pos->second;
615 for (ThreadLocalValues::iterator value_pos =
616 thread_local_values.begin();
617 value_pos != thread_local_values.end();
619 value_holders.push_back(value_pos->second);
621 thread_to_thread_locals->erase(thread_local_pos);
624 // Outside the lock, let the destructor for 'value_holders' deallocate the
625 // ThreadLocalValueHolderBases.
629 // In a particular thread, maps a ThreadLocal object to its value.
630 typedef std::map<const ThreadLocalBase*,
631 std::shared_ptr<ThreadLocalValueHolderBase> >
633 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
635 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
637 // Holds the thread id and thread handle that we pass from
638 // StartWatcherThreadFor to WatcherThreadFunc.
639 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
641 static void StartWatcherThreadFor(DWORD thread_id) {
642 // The returned handle will be kept in thread_map and closed by
643 // watcher_thread in WatcherThreadFunc.
644 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
647 GTEST_CHECK_(thread != nullptr);
648 // We need to pass a valid thread ID pointer into CreateThread for it
649 // to work correctly under Win98.
650 DWORD watcher_thread_id;
651 HANDLE watcher_thread = ::CreateThread(
652 nullptr, // Default security.
653 0, // Default stack size
654 &ThreadLocalRegistryImpl::WatcherThreadFunc,
655 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
656 CREATE_SUSPENDED, &watcher_thread_id);
657 GTEST_CHECK_(watcher_thread != nullptr);
658 // Give the watcher thread the same priority as ours to avoid being
660 ::SetThreadPriority(watcher_thread,
661 ::GetThreadPriority(::GetCurrentThread()));
662 ::ResumeThread(watcher_thread);
663 ::CloseHandle(watcher_thread);
666 // Monitors exit from a given thread and notifies those
667 // ThreadIdToThreadLocals about thread termination.
668 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
669 const ThreadIdAndHandle* tah =
670 reinterpret_cast<const ThreadIdAndHandle*>(param);
672 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
673 OnThreadExit(tah->first);
674 ::CloseHandle(tah->second);
679 // Returns map of thread local instances.
680 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
683 MemoryIsNotDeallocated memory_is_not_deallocated;
685 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
689 // Protects access to GetThreadLocalsMapLocked() and its return value.
691 // Protects access to GetThreadMapLocked() and its return value.
692 static Mutex thread_map_mutex_;
695 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
696 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
698 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
699 const ThreadLocalBase* thread_local_instance) {
700 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
701 thread_local_instance);
704 void ThreadLocalRegistry::OnThreadLocalDestroyed(
705 const ThreadLocalBase* thread_local_instance) {
706 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
709 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
711 #if GTEST_USES_POSIX_RE
713 // Implements RE. Currently only needed for death tests.
717 // regfree'ing an invalid regex might crash because the content
718 // of the regex is undefined. Since the regex's are essentially
719 // the same, one cannot be valid (or invalid) without the other
721 regfree(&partial_regex_);
722 regfree(&full_regex_);
724 free(const_cast<char*>(pattern_));
727 // Returns true if and only if regular expression re matches the entire str.
728 bool RE::FullMatch(const char* str, const RE& re) {
729 if (!re.is_valid_) return false;
732 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
735 // Returns true if and only if regular expression re matches a substring of
736 // str (including str itself).
737 bool RE::PartialMatch(const char* str, const RE& re) {
738 if (!re.is_valid_) return false;
741 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
744 // Initializes an RE from its string representation.
745 void RE::Init(const char* regex) {
746 pattern_ = posix::StrDup(regex);
748 // Reserves enough bytes to hold the regular expression used for a
750 const size_t full_regex_len = strlen(regex) + 10;
751 char* const full_pattern = new char[full_regex_len];
753 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
754 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
755 // We want to call regcomp(&partial_regex_, ...) even if the
756 // previous expression returns false. Otherwise partial_regex_ may
757 // not be properly initialized can may cause trouble when it's
760 // Some implementation of POSIX regex (e.g. on at least some
761 // versions of Cygwin) doesn't accept the empty string as a valid
762 // regex. We change it to an equivalent form "()" to be safe.
764 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
765 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
767 EXPECT_TRUE(is_valid_)
768 << "Regular expression \"" << regex
769 << "\" is not a valid POSIX Extended regular expression.";
771 delete[] full_pattern;
774 #elif GTEST_USES_SIMPLE_RE
776 // Returns true if and only if ch appears anywhere in str (excluding the
777 // terminating '\0' character).
778 bool IsInSet(char ch, const char* str) {
779 return ch != '\0' && strchr(str, ch) != nullptr;
782 // Returns true if and only if ch belongs to the given classification.
783 // Unlike similar functions in <ctype.h>, these aren't affected by the
785 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
786 bool IsAsciiPunct(char ch) {
787 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
789 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
790 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
791 bool IsAsciiWordChar(char ch) {
792 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
793 ('0' <= ch && ch <= '9') || ch == '_';
796 // Returns true if and only if "\\c" is a supported escape sequence.
797 bool IsValidEscape(char c) {
798 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
801 // Returns true if and only if the given atom (specified by escaped and
802 // pattern) matches ch. The result is undefined if the atom is invalid.
803 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
804 if (escaped) { // "\\p" where p is pattern_char.
805 switch (pattern_char) {
806 case 'd': return IsAsciiDigit(ch);
807 case 'D': return !IsAsciiDigit(ch);
808 case 'f': return ch == '\f';
809 case 'n': return ch == '\n';
810 case 'r': return ch == '\r';
811 case 's': return IsAsciiWhiteSpace(ch);
812 case 'S': return !IsAsciiWhiteSpace(ch);
813 case 't': return ch == '\t';
814 case 'v': return ch == '\v';
815 case 'w': return IsAsciiWordChar(ch);
816 case 'W': return !IsAsciiWordChar(ch);
818 return IsAsciiPunct(pattern_char) && pattern_char == ch;
821 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
824 // Helper function used by ValidateRegex() to format error messages.
825 static std::string FormatRegexSyntaxError(const char* regex, int index) {
826 return (Message() << "Syntax error at index " << index
827 << " in simple regular expression \"" << regex << "\": ").GetString();
830 // Generates non-fatal failures and returns false if regex is invalid;
831 // otherwise returns true.
832 bool ValidateRegex(const char* regex) {
833 if (regex == nullptr) {
834 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
838 bool is_valid = true;
840 // True if and only if ?, *, or + can follow the previous atom.
841 bool prev_repeatable = false;
842 for (int i = 0; regex[i]; i++) {
843 if (regex[i] == '\\') { // An escape sequence
845 if (regex[i] == '\0') {
846 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
847 << "'\\' cannot appear at the end.";
851 if (!IsValidEscape(regex[i])) {
852 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
853 << "invalid escape sequence \"\\" << regex[i] << "\".";
856 prev_repeatable = true;
857 } else { // Not an escape sequence.
858 const char ch = regex[i];
860 if (ch == '^' && i > 0) {
861 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
862 << "'^' can only appear at the beginning.";
864 } else if (ch == '$' && regex[i + 1] != '\0') {
865 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
866 << "'$' can only appear at the end.";
868 } else if (IsInSet(ch, "()[]{}|")) {
869 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
870 << "'" << ch << "' is unsupported.";
872 } else if (IsRepeat(ch) && !prev_repeatable) {
873 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
874 << "'" << ch << "' can only follow a repeatable token.";
878 prev_repeatable = !IsInSet(ch, "^$?*+");
885 // Matches a repeated regex atom followed by a valid simple regular
886 // expression. The regex atom is defined as c if escaped is false,
887 // or \c otherwise. repeat is the repetition meta character (?, *,
888 // or +). The behavior is undefined if str contains too many
889 // characters to be indexable by size_t, in which case the test will
890 // probably time out anyway. We are fine with this limitation as
891 // std::string has it too.
892 bool MatchRepetitionAndRegexAtHead(
893 bool escaped, char c, char repeat, const char* regex,
895 const size_t min_count = (repeat == '+') ? 1 : 0;
896 const size_t max_count = (repeat == '?') ? 1 :
897 static_cast<size_t>(-1) - 1;
898 // We cannot call numeric_limits::max() as it conflicts with the
899 // max() macro on Windows.
901 for (size_t i = 0; i <= max_count; ++i) {
902 // We know that the atom matches each of the first i characters in str.
903 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
904 // We have enough matches at the head, and the tail matches too.
905 // Since we only care about *whether* the pattern matches str
906 // (as opposed to *how* it matches), there is no need to find a
910 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
916 // Returns true if and only if regex matches a prefix of str. regex must
917 // be a valid simple regular expression and not start with "^", or the
918 // result is undefined.
919 bool MatchRegexAtHead(const char* regex, const char* str) {
920 if (*regex == '\0') // An empty regex matches a prefix of anything.
923 // "$" only matches the end of a string. Note that regex being
924 // valid guarantees that there's nothing after "$" in it.
928 // Is the first thing in regex an escape sequence?
929 const bool escaped = *regex == '\\';
932 if (IsRepeat(regex[1])) {
933 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
934 // here's an indirect recursion. It terminates as the regex gets
935 // shorter in each recursion.
936 return MatchRepetitionAndRegexAtHead(
937 escaped, regex[0], regex[1], regex + 2, str);
939 // regex isn't empty, isn't "$", and doesn't start with a
940 // repetition. We match the first atom of regex with the first
941 // character of str and recurse.
942 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
943 MatchRegexAtHead(regex + 1, str + 1);
947 // Returns true if and only if regex matches any substring of str. regex must
948 // be a valid simple regular expression, or the result is undefined.
950 // The algorithm is recursive, but the recursion depth doesn't exceed
951 // the regex length, so we won't need to worry about running out of
952 // stack space normally. In rare cases the time complexity can be
953 // exponential with respect to the regex length + the string length,
954 // but usually it's must faster (often close to linear).
955 bool MatchRegexAnywhere(const char* regex, const char* str) {
956 if (regex == nullptr || str == nullptr) return false;
959 return MatchRegexAtHead(regex + 1, str);
961 // A successful match can be anywhere in str.
963 if (MatchRegexAtHead(regex, str))
965 } while (*str++ != '\0');
969 // Implements the RE class.
972 free(const_cast<char*>(pattern_));
973 free(const_cast<char*>(full_pattern_));
976 // Returns true if and only if regular expression re matches the entire str.
977 bool RE::FullMatch(const char* str, const RE& re) {
978 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
981 // Returns true if and only if regular expression re matches a substring of
982 // str (including str itself).
983 bool RE::PartialMatch(const char* str, const RE& re) {
984 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
987 // Initializes an RE from its string representation.
988 void RE::Init(const char* regex) {
989 pattern_ = full_pattern_ = nullptr;
990 if (regex != nullptr) {
991 pattern_ = posix::StrDup(regex);
994 is_valid_ = ValidateRegex(regex);
996 // No need to calculate the full pattern when the regex is invalid.
1000 const size_t len = strlen(regex);
1001 // Reserves enough bytes to hold the regular expression used for a
1002 // full match: we need space to prepend a '^', append a '$', and
1003 // terminate the string with '\0'.
1004 char* buffer = static_cast<char*>(malloc(len + 3));
1005 full_pattern_ = buffer;
1008 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
1010 // We don't use snprintf or strncpy, as they trigger a warning when
1011 // compiled with VC++ 8.0.
1012 memcpy(buffer, regex, len);
1015 if (len == 0 || regex[len - 1] != '$')
1016 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
1021 #endif // GTEST_USES_POSIX_RE
1023 const char kUnknownFile[] = "unknown file";
1025 // Formats a source file path and a line number as they would appear
1026 // in an error message from the compiler used to compile this code.
1027 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
1028 const std::string file_name(file == nullptr ? kUnknownFile : file);
1031 return file_name + ":";
1034 return file_name + "(" + StreamableToString(line) + "):";
1036 return file_name + ":" + StreamableToString(line) + ":";
1040 // Formats a file location for compiler-independent XML output.
1041 // Although this function is not platform dependent, we put it next to
1042 // FormatFileLocation in order to contrast the two functions.
1043 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
1044 // to the file location it produces, unlike FormatFileLocation().
1045 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
1046 const char* file, int line) {
1047 const std::string file_name(file == nullptr ? kUnknownFile : file);
1052 return file_name + ":" + StreamableToString(line);
1055 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
1056 : severity_(severity) {
1057 const char* const marker =
1058 severity == GTEST_INFO ? "[ INFO ]" :
1059 severity == GTEST_WARNING ? "[WARNING]" :
1060 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
1061 GetStream() << ::std::endl << marker << " "
1062 << FormatFileLocation(file, line).c_str() << ": ";
1065 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1066 GTestLog::~GTestLog() {
1067 GetStream() << ::std::endl;
1068 if (severity_ == GTEST_FATAL) {
1074 // Disable Microsoft deprecation warnings for POSIX functions called from
1075 // this class (creat, dup, dup2, and close)
1076 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
1078 #if GTEST_HAS_STREAM_REDIRECTION
1080 // Object that captures an output stream (stdout/stderr).
1081 class CapturedStream {
1083 // The ctor redirects the stream to a temporary file.
1084 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
1085 # if GTEST_OS_WINDOWS
1086 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
1087 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
1089 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
1090 const UINT success = ::GetTempFileNameA(temp_dir_path,
1092 0, // Generate unique file name.
1094 GTEST_CHECK_(success != 0)
1095 << "Unable to create a temporary file in " << temp_dir_path;
1096 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
1097 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
1099 filename_ = temp_file_path;
1101 // There's no guarantee that a test has write access to the current
1102 // directory, so we create the temporary file in the /tmp directory
1104 # if GTEST_OS_LINUX_ANDROID
1105 // Note: Android applications are expected to call the framework's
1106 // Context.getExternalStorageDirectory() method through JNI to get
1107 // the location of the world-writable SD Card directory. However,
1108 // this requires a Context handle, which cannot be retrieved
1109 // globally from native code. Doing so also precludes running the
1110 // code as part of a regular standalone executable, which doesn't
1111 // run in a Dalvik process (e.g. when running it through 'adb shell').
1113 // The location /data/local/tmp is directly accessible from native code.
1114 // '/sdcard' and other variants cannot be relied on, as they are not
1115 // guaranteed to be mounted, or may have a delay in mounting.
1116 ::std::string name_template_buf = TempDir() + "gtest_captured_stream.XXXXXX";
1117 char* name_template = &name_template_buf[0];
1119 NSString* temp_path = [NSTemporaryDirectory()
1120 stringByAppendingPathComponent:@"gtest_captured_stream.XXXXXX"];
1122 char name_template[PATH_MAX + 1];
1123 strncpy(name_template, [temp_path UTF8String], PATH_MAX);
1125 char name_template[] = "/tmp/captured_stream.XXXXXX";
1127 const int captured_fd = mkstemp(name_template);
1128 if (captured_fd == -1) {
1130 << "Failed to create tmp file " << name_template
1131 << " for test; does the test have access to the /tmp directory?";
1133 filename_ = name_template;
1134 # endif // GTEST_OS_WINDOWS
1136 dup2(captured_fd, fd_);
1141 remove(filename_.c_str());
1144 std::string GetCapturedString() {
1145 if (uncaptured_fd_ != -1) {
1146 // Restores the original stream.
1148 dup2(uncaptured_fd_, fd_);
1149 close(uncaptured_fd_);
1150 uncaptured_fd_ = -1;
1153 FILE* const file = posix::FOpen(filename_.c_str(), "r");
1154 if (file == nullptr) {
1155 GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
1156 << " for capturing stream.";
1158 const std::string content = ReadEntireFile(file);
1159 posix::FClose(file);
1164 const int fd_; // A stream to capture.
1166 // Name of the temporary file holding the stderr output.
1167 ::std::string filename_;
1169 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
1172 GTEST_DISABLE_MSC_DEPRECATED_POP_()
1174 static CapturedStream* g_captured_stderr = nullptr;
1175 static CapturedStream* g_captured_stdout = nullptr;
1177 // Starts capturing an output stream (stdout/stderr).
1178 static void CaptureStream(int fd, const char* stream_name,
1179 CapturedStream** stream) {
1180 if (*stream != nullptr) {
1181 GTEST_LOG_(FATAL) << "Only one " << stream_name
1182 << " capturer can exist at a time.";
1184 *stream = new CapturedStream(fd);
1187 // Stops capturing the output stream and returns the captured string.
1188 static std::string GetCapturedStream(CapturedStream** captured_stream) {
1189 const std::string content = (*captured_stream)->GetCapturedString();
1191 delete *captured_stream;
1192 *captured_stream = nullptr;
1197 // Starts capturing stdout.
1198 void CaptureStdout() {
1199 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
1202 // Starts capturing stderr.
1203 void CaptureStderr() {
1204 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
1207 // Stops capturing stdout and returns the captured string.
1208 std::string GetCapturedStdout() {
1209 return GetCapturedStream(&g_captured_stdout);
1212 // Stops capturing stderr and returns the captured string.
1213 std::string GetCapturedStderr() {
1214 return GetCapturedStream(&g_captured_stderr);
1217 #endif // GTEST_HAS_STREAM_REDIRECTION
1223 size_t GetFileSize(FILE* file) {
1224 fseek(file, 0, SEEK_END);
1225 return static_cast<size_t>(ftell(file));
1228 std::string ReadEntireFile(FILE* file) {
1229 const size_t file_size = GetFileSize(file);
1230 char* const buffer = new char[file_size];
1232 size_t bytes_last_read = 0; // # of bytes read in the last fread()
1233 size_t bytes_read = 0; // # of bytes read so far
1235 fseek(file, 0, SEEK_SET);
1237 // Keeps reading the file until we cannot read further or the
1238 // pre-determined file size is reached.
1240 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
1241 bytes_read += bytes_last_read;
1242 } while (bytes_last_read > 0 && bytes_read < file_size);
1244 const std::string content(buffer, bytes_read);
1250 #if GTEST_HAS_DEATH_TEST
1251 static const std::vector<std::string>* g_injected_test_argvs =
1254 std::vector<std::string> GetInjectableArgvs() {
1255 if (g_injected_test_argvs != nullptr) {
1256 return *g_injected_test_argvs;
1261 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
1262 if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
1263 g_injected_test_argvs = new_argvs;
1266 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
1268 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
1271 void ClearInjectableArgvs() {
1272 delete g_injected_test_argvs;
1273 g_injected_test_argvs = nullptr;
1275 #endif // GTEST_HAS_DEATH_TEST
1277 #if GTEST_OS_WINDOWS_MOBILE
1281 TerminateProcess(GetCurrentProcess(), 1);
1283 } // namespace posix
1284 #endif // GTEST_OS_WINDOWS_MOBILE
1286 // Returns the name of the environment variable corresponding to the
1287 // given flag. For example, FlagToEnvVar("foo") will return
1288 // "GTEST_FOO" in the open-source version.
1289 static std::string FlagToEnvVar(const char* flag) {
1290 const std::string full_flag =
1291 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
1294 for (size_t i = 0; i != full_flag.length(); i++) {
1295 env_var << ToUpper(full_flag.c_str()[i]);
1298 return env_var.GetString();
1301 // Parses 'str' for a 32-bit signed integer. If successful, writes
1302 // the result to *value and returns true; otherwise leaves *value
1303 // unchanged and returns false.
1304 bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
1305 // Parses the environment variable as a decimal integer.
1306 char* end = nullptr;
1307 const long long_value = strtol(str, &end, 10); // NOLINT
1309 // Has strtol() consumed all characters in the string?
1311 // No - an invalid character was encountered.
1313 msg << "WARNING: " << src_text
1314 << " is expected to be a 32-bit integer, but actually"
1315 << " has value \"" << str << "\".\n";
1316 printf("%s", msg.GetString().c_str());
1321 // Is the parsed value in the range of an int32_t?
1322 const auto result = static_cast<int32_t>(long_value);
1323 if (long_value == LONG_MAX || long_value == LONG_MIN ||
1324 // The parsed value overflows as a long. (strtol() returns
1325 // LONG_MAX or LONG_MIN when the input overflows.)
1326 result != long_value
1327 // The parsed value overflows as an int32_t.
1330 msg << "WARNING: " << src_text
1331 << " is expected to be a 32-bit integer, but actually"
1332 << " has value " << str << ", which overflows.\n";
1333 printf("%s", msg.GetString().c_str());
1342 // Reads and returns the Boolean environment variable corresponding to
1343 // the given flag; if it's not set, returns default_value.
1345 // The value is considered true if and only if it's not "0".
1346 bool BoolFromGTestEnv(const char* flag, bool default_value) {
1347 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1348 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1350 const std::string env_var = FlagToEnvVar(flag);
1351 const char* const string_value = posix::GetEnv(env_var.c_str());
1352 return string_value == nullptr ? default_value
1353 : strcmp(string_value, "0") != 0;
1354 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1357 // Reads and returns a 32-bit integer stored in the environment
1358 // variable corresponding to the given flag; if it isn't set or
1359 // doesn't represent a valid 32-bit integer, returns default_value.
1360 int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
1361 #if defined(GTEST_GET_INT32_FROM_ENV_)
1362 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1364 const std::string env_var = FlagToEnvVar(flag);
1365 const char* const string_value = posix::GetEnv(env_var.c_str());
1366 if (string_value == nullptr) {
1367 // The environment variable is not set.
1368 return default_value;
1371 int32_t result = default_value;
1372 if (!ParseInt32(Message() << "Environment variable " << env_var,
1373 string_value, &result)) {
1374 printf("The default value %s is used.\n",
1375 (Message() << default_value).GetString().c_str());
1377 return default_value;
1381 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1384 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
1385 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
1386 // system. The value of XML_OUTPUT_FILE is a filename without the
1387 // "xml:" prefix of GTEST_OUTPUT.
1388 // Note that this is meant to be called at the call site so it does
1389 // not check that the flag is 'output'
1390 // In essence this checks an env variable called XML_OUTPUT_FILE
1391 // and if it is set we prepend "xml:" to its value, if it not set we return ""
1392 std::string OutputFlagAlsoCheckEnvVar(){
1393 std::string default_value_for_output_flag = "";
1394 const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
1395 if (nullptr != xml_output_file_env) {
1396 default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
1398 return default_value_for_output_flag;
1401 // Reads and returns the string environment variable corresponding to
1402 // the given flag; if it's not set, returns default_value.
1403 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
1404 #if defined(GTEST_GET_STRING_FROM_ENV_)
1405 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1407 const std::string env_var = FlagToEnvVar(flag);
1408 const char* const value = posix::GetEnv(env_var.c_str());
1409 return value == nullptr ? default_value : value;
1410 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
1413 } // namespace internal
1414 } // namespace testing