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
83 #include "gtest/gtest-spi.h"
84 #include "gtest/gtest-message.h"
85 #include "gtest/internal/gtest-internal.h"
86 #include "gtest/internal/gtest-string.h"
87 #include "src/gtest-internal-inl.h"
92 #if defined(_MSC_VER) || defined(__BORLANDC__)
93 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
94 const int kStdOutFileno = 1;
95 const int kStdErrFileno = 2;
97 const int kStdOutFileno = STDOUT_FILENO;
98 const int kStdErrFileno = STDERR_FILENO;
101 #if GTEST_OS_LINUX || GTEST_OS_GNU_HURD
104 template <typename T>
105 T ReadProcFileField(const std::string& filename, int field) {
107 std::ifstream file(filename.c_str());
108 while (field-- > 0) {
117 // Returns the number of active threads, or 0 when there is an error.
118 size_t GetThreadCount() {
119 const std::string filename =
120 (Message() << "/proc/" << getpid() << "/stat").GetString();
121 return ReadProcFileField<size_t>(filename, 19);
126 size_t GetThreadCount() {
127 const task_t task = mach_task_self();
128 mach_msg_type_number_t thread_count;
129 thread_act_array_t thread_list;
130 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
131 if (status == KERN_SUCCESS) {
132 // task_threads allocates resources in thread_list and we need to free them
135 reinterpret_cast<vm_address_t>(thread_list),
136 sizeof(thread_t) * thread_count);
137 return static_cast<size_t>(thread_count);
143 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
148 #define KERN_PROC KERN_PROC2
149 #define kinfo_proc kinfo_proc2
152 #if GTEST_OS_DRAGONFLY
153 #define KP_NLWP(kp) (kp.kp_nthreads)
154 #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
155 #define KP_NLWP(kp) (kp.ki_numthreads)
156 #elif GTEST_OS_NETBSD
157 #define KP_NLWP(kp) (kp.p_nlwps)
160 // Returns the number of threads running in the process, or 0 to indicate that
161 // we cannot detect it.
162 size_t GetThreadCount() {
169 sizeof(struct kinfo_proc),
173 u_int miblen = sizeof(mib) / sizeof(mib[0]);
174 struct kinfo_proc info;
175 size_t size = sizeof(info);
176 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
179 return static_cast<size_t>(KP_NLWP(info));
181 #elif GTEST_OS_OPENBSD
183 // Returns the number of threads running in the process, or 0 to indicate that
184 // we cannot detect it.
185 size_t GetThreadCount() {
189 KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
191 sizeof(struct kinfo_proc),
194 u_int miblen = sizeof(mib) / sizeof(mib[0]);
196 // get number of structs
198 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
202 mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
204 // populate array of structs
205 struct kinfo_proc info[mib[5]];
206 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
210 // exclude empty members
212 for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
213 if (info[i].p_tid != -1)
221 // Returns the number of threads running in the process, or 0 to indicate that
222 // we cannot detect it.
223 size_t GetThreadCount() {
224 const int fd = open("/proc/self/as", O_RDONLY);
228 procfs_info process_info;
230 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
233 return static_cast<size_t>(process_info.num_threads);
241 size_t GetThreadCount() {
242 struct procentry64 entry;
243 pid_t pid = getpid();
244 int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
246 return entry.pi_thcount;
252 #elif GTEST_OS_FUCHSIA
254 size_t GetThreadCount() {
257 zx_status_t status = zx_object_get_info(
259 ZX_INFO_PROCESS_THREADS,
264 if (status == ZX_OK) {
273 size_t GetThreadCount() {
274 // There's no portable way to detect the number of threads, so we just
275 // return 0 to indicate that we cannot detect it.
279 #endif // GTEST_OS_LINUX
281 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
283 void SleepMilliseconds(int n) {
284 ::Sleep(static_cast<DWORD>(n));
287 AutoHandle::AutoHandle()
288 : handle_(INVALID_HANDLE_VALUE) {}
290 AutoHandle::AutoHandle(Handle handle)
293 AutoHandle::~AutoHandle() {
297 AutoHandle::Handle AutoHandle::Get() const {
301 void AutoHandle::Reset() {
302 Reset(INVALID_HANDLE_VALUE);
305 void AutoHandle::Reset(HANDLE handle) {
306 // Resetting with the same handle we already own is invalid.
307 if (handle_ != handle) {
309 ::CloseHandle(handle_);
313 GTEST_CHECK_(!IsCloseable())
314 << "Resetting a valid handle to itself is likely a programmer error "
315 "and thus not allowed.";
319 bool AutoHandle::IsCloseable() const {
320 // Different Windows APIs may use either of these values to represent an
322 return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
325 Notification::Notification()
326 : event_(::CreateEvent(nullptr, // Default security attributes.
327 TRUE, // Do not reset automatically.
328 FALSE, // Initially unset.
329 nullptr)) { // Anonymous event.
330 GTEST_CHECK_(event_.Get() != nullptr);
333 void Notification::Notify() {
334 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
337 void Notification::WaitForNotification() {
339 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
343 : owner_thread_id_(0),
345 critical_section_init_phase_(0),
346 critical_section_(new CRITICAL_SECTION) {
347 ::InitializeCriticalSection(critical_section_);
351 // Static mutexes are leaked intentionally. It is not thread-safe to try
353 if (type_ == kDynamic) {
354 ::DeleteCriticalSection(critical_section_);
355 delete critical_section_;
356 critical_section_ = nullptr;
361 ThreadSafeLazyInit();
362 ::EnterCriticalSection(critical_section_);
363 owner_thread_id_ = ::GetCurrentThreadId();
366 void Mutex::Unlock() {
367 ThreadSafeLazyInit();
368 // We don't protect writing to owner_thread_id_ here, as it's the
369 // caller's responsibility to ensure that the current thread holds the
370 // mutex when this is called.
371 owner_thread_id_ = 0;
372 ::LeaveCriticalSection(critical_section_);
375 // Does nothing if the current thread holds the mutex. Otherwise, crashes
376 // with high probability.
377 void Mutex::AssertHeld() {
378 ThreadSafeLazyInit();
379 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
380 << "The current thread is not holding the mutex @" << this;
386 // Use the RAII idiom to flag mem allocs that are intentionally never
387 // deallocated. The motivation is to silence the false positive mem leaks
388 // that are reported by the debug version of MS's CRT which can only detect
389 // if an alloc is missing a matching deallocation.
391 // MemoryIsNotDeallocated memory_is_not_deallocated;
392 // critical_section_ = new CRITICAL_SECTION;
394 class MemoryIsNotDeallocated
397 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
398 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
399 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
400 // doesn't report mem leak if there's no matching deallocation.
401 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
404 ~MemoryIsNotDeallocated() {
405 // Restore the original _CRTDBG_ALLOC_MEM_DF flag
406 _CrtSetDbgFlag(old_crtdbg_flag_);
410 int old_crtdbg_flag_;
412 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
418 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
419 void Mutex::ThreadSafeLazyInit() {
420 // Dynamic mutexes are initialized in the constructor.
421 if (type_ == kStatic) {
423 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
425 // If critical_section_init_phase_ was 0 before the exchange, we
426 // are the first to test it and need to perform the initialization.
427 owner_thread_id_ = 0;
429 // Use RAII to flag that following mem alloc is never deallocated.
431 MemoryIsNotDeallocated memory_is_not_deallocated;
433 critical_section_ = new CRITICAL_SECTION;
435 ::InitializeCriticalSection(critical_section_);
436 // Updates the critical_section_init_phase_ to 2 to signal
437 // initialization complete.
438 GTEST_CHECK_(::InterlockedCompareExchange(
439 &critical_section_init_phase_, 2L, 1L) ==
443 // Somebody else is already initializing the mutex; spin until they
445 while (::InterlockedCompareExchange(&critical_section_init_phase_,
448 // Possibly yields the rest of the thread's time slice to other
455 break; // The mutex is already initialized and ready for use.
459 << "Unexpected value of critical_section_init_phase_ "
460 << "while initializing a static mutex.";
467 class ThreadWithParamSupport : public ThreadWithParamBase {
469 static HANDLE CreateThread(Runnable* runnable,
470 Notification* thread_can_start) {
471 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
473 HANDLE thread_handle = ::CreateThread(
474 nullptr, // Default security.
475 0, // Default stack size.
476 &ThreadWithParamSupport::ThreadMain,
477 param, // Parameter to ThreadMainStatic
478 0x0, // Default creation flags.
479 &thread_id); // Need a valid pointer for the call to work under Win98.
480 GTEST_CHECK_(thread_handle != nullptr)
481 << "CreateThread failed with error " << ::GetLastError() << ".";
482 if (thread_handle == nullptr) {
485 return thread_handle;
489 struct ThreadMainParam {
490 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
491 : runnable_(runnable),
492 thread_can_start_(thread_can_start) {
494 std::unique_ptr<Runnable> runnable_;
496 Notification* thread_can_start_;
499 static DWORD WINAPI ThreadMain(void* ptr) {
500 // Transfers ownership.
501 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
502 if (param->thread_can_start_ != nullptr)
503 param->thread_can_start_->WaitForNotification();
504 param->runnable_->Run();
508 // Prohibit instantiation.
509 ThreadWithParamSupport();
511 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
516 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
517 Notification* thread_can_start)
518 : thread_(ThreadWithParamSupport::CreateThread(runnable,
522 ThreadWithParamBase::~ThreadWithParamBase() {
526 void ThreadWithParamBase::Join() {
527 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
528 << "Failed to join the thread with error " << ::GetLastError() << ".";
531 // Maps a thread to a set of ThreadIdToThreadLocals that have values
532 // instantiated on that thread and notifies them when the thread exits. A
533 // ThreadLocal instance is expected to persist until all threads it has
534 // values on have terminated.
535 class ThreadLocalRegistryImpl {
537 // Registers thread_local_instance as having value on the current thread.
538 // Returns a value that can be used to identify the thread from other threads.
539 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
540 const ThreadLocalBase* thread_local_instance) {
542 MemoryIsNotDeallocated memory_is_not_deallocated;
544 DWORD current_thread = ::GetCurrentThreadId();
545 MutexLock lock(&mutex_);
546 ThreadIdToThreadLocals* const thread_to_thread_locals =
547 GetThreadLocalsMapLocked();
548 ThreadIdToThreadLocals::iterator thread_local_pos =
549 thread_to_thread_locals->find(current_thread);
550 if (thread_local_pos == thread_to_thread_locals->end()) {
551 thread_local_pos = thread_to_thread_locals->insert(
552 std::make_pair(current_thread, ThreadLocalValues())).first;
553 StartWatcherThreadFor(current_thread);
555 ThreadLocalValues& thread_local_values = thread_local_pos->second;
556 ThreadLocalValues::iterator value_pos =
557 thread_local_values.find(thread_local_instance);
558 if (value_pos == thread_local_values.end()) {
561 .insert(std::make_pair(
562 thread_local_instance,
563 std::shared_ptr<ThreadLocalValueHolderBase>(
564 thread_local_instance->NewValueForCurrentThread())))
567 return value_pos->second.get();
570 static void OnThreadLocalDestroyed(
571 const ThreadLocalBase* thread_local_instance) {
572 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
573 // Clean up the ThreadLocalValues data structure while holding the lock, but
574 // defer the destruction of the ThreadLocalValueHolderBases.
576 MutexLock lock(&mutex_);
577 ThreadIdToThreadLocals* const thread_to_thread_locals =
578 GetThreadLocalsMapLocked();
579 for (ThreadIdToThreadLocals::iterator it =
580 thread_to_thread_locals->begin();
581 it != thread_to_thread_locals->end();
583 ThreadLocalValues& thread_local_values = it->second;
584 ThreadLocalValues::iterator value_pos =
585 thread_local_values.find(thread_local_instance);
586 if (value_pos != thread_local_values.end()) {
587 value_holders.push_back(value_pos->second);
588 thread_local_values.erase(value_pos);
589 // This 'if' can only be successful at most once, so theoretically we
590 // could break out of the loop here, but we don't bother doing so.
594 // Outside the lock, let the destructor for 'value_holders' deallocate the
595 // ThreadLocalValueHolderBases.
598 static void OnThreadExit(DWORD thread_id) {
599 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
600 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
601 // Clean up the ThreadIdToThreadLocals data structure while holding the
602 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
604 MutexLock lock(&mutex_);
605 ThreadIdToThreadLocals* const thread_to_thread_locals =
606 GetThreadLocalsMapLocked();
607 ThreadIdToThreadLocals::iterator thread_local_pos =
608 thread_to_thread_locals->find(thread_id);
609 if (thread_local_pos != thread_to_thread_locals->end()) {
610 ThreadLocalValues& thread_local_values = thread_local_pos->second;
611 for (ThreadLocalValues::iterator value_pos =
612 thread_local_values.begin();
613 value_pos != thread_local_values.end();
615 value_holders.push_back(value_pos->second);
617 thread_to_thread_locals->erase(thread_local_pos);
620 // Outside the lock, let the destructor for 'value_holders' deallocate the
621 // ThreadLocalValueHolderBases.
625 // In a particular thread, maps a ThreadLocal object to its value.
626 typedef std::map<const ThreadLocalBase*,
627 std::shared_ptr<ThreadLocalValueHolderBase> >
629 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
631 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
633 // Holds the thread id and thread handle that we pass from
634 // StartWatcherThreadFor to WatcherThreadFunc.
635 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
637 static void StartWatcherThreadFor(DWORD thread_id) {
638 // The returned handle will be kept in thread_map and closed by
639 // watcher_thread in WatcherThreadFunc.
640 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
643 GTEST_CHECK_(thread != nullptr);
644 // We need to pass a valid thread ID pointer into CreateThread for it
645 // to work correctly under Win98.
646 DWORD watcher_thread_id;
647 HANDLE watcher_thread = ::CreateThread(
648 nullptr, // Default security.
649 0, // Default stack size
650 &ThreadLocalRegistryImpl::WatcherThreadFunc,
651 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
652 CREATE_SUSPENDED, &watcher_thread_id);
653 GTEST_CHECK_(watcher_thread != nullptr);
654 // Give the watcher thread the same priority as ours to avoid being
656 ::SetThreadPriority(watcher_thread,
657 ::GetThreadPriority(::GetCurrentThread()));
658 ::ResumeThread(watcher_thread);
659 ::CloseHandle(watcher_thread);
662 // Monitors exit from a given thread and notifies those
663 // ThreadIdToThreadLocals about thread termination.
664 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
665 const ThreadIdAndHandle* tah =
666 reinterpret_cast<const ThreadIdAndHandle*>(param);
668 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
669 OnThreadExit(tah->first);
670 ::CloseHandle(tah->second);
675 // Returns map of thread local instances.
676 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
679 MemoryIsNotDeallocated memory_is_not_deallocated;
681 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
685 // Protects access to GetThreadLocalsMapLocked() and its return value.
687 // Protects access to GetThreadMapLocked() and its return value.
688 static Mutex thread_map_mutex_;
691 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT
692 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); // NOLINT
694 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
695 const ThreadLocalBase* thread_local_instance) {
696 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
697 thread_local_instance);
700 void ThreadLocalRegistry::OnThreadLocalDestroyed(
701 const ThreadLocalBase* thread_local_instance) {
702 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
705 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
707 #if GTEST_USES_POSIX_RE
709 // Implements RE. Currently only needed for death tests.
713 // regfree'ing an invalid regex might crash because the content
714 // of the regex is undefined. Since the regex's are essentially
715 // the same, one cannot be valid (or invalid) without the other
717 regfree(&partial_regex_);
718 regfree(&full_regex_);
720 free(const_cast<char*>(pattern_));
723 // Returns true if and only if regular expression re matches the entire str.
724 bool RE::FullMatch(const char* str, const RE& re) {
725 if (!re.is_valid_) return false;
728 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
731 // Returns true if and only if regular expression re matches a substring of
732 // str (including str itself).
733 bool RE::PartialMatch(const char* str, const RE& re) {
734 if (!re.is_valid_) return false;
737 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
740 // Initializes an RE from its string representation.
741 void RE::Init(const char* regex) {
742 pattern_ = posix::StrDup(regex);
744 // Reserves enough bytes to hold the regular expression used for a
746 const size_t full_regex_len = strlen(regex) + 10;
747 char* const full_pattern = new char[full_regex_len];
749 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
750 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
751 // We want to call regcomp(&partial_regex_, ...) even if the
752 // previous expression returns false. Otherwise partial_regex_ may
753 // not be properly initialized can may cause trouble when it's
756 // Some implementation of POSIX regex (e.g. on at least some
757 // versions of Cygwin) doesn't accept the empty string as a valid
758 // regex. We change it to an equivalent form "()" to be safe.
760 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
761 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
763 EXPECT_TRUE(is_valid_)
764 << "Regular expression \"" << regex
765 << "\" is not a valid POSIX Extended regular expression.";
767 delete[] full_pattern;
770 #elif GTEST_USES_SIMPLE_RE
772 // Returns true if and only if ch appears anywhere in str (excluding the
773 // terminating '\0' character).
774 bool IsInSet(char ch, const char* str) {
775 return ch != '\0' && strchr(str, ch) != nullptr;
778 // Returns true if and only if ch belongs to the given classification.
779 // Unlike similar functions in <ctype.h>, these aren't affected by the
781 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
782 bool IsAsciiPunct(char ch) {
783 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
785 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
786 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
787 bool IsAsciiWordChar(char ch) {
788 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
789 ('0' <= ch && ch <= '9') || ch == '_';
792 // Returns true if and only if "\\c" is a supported escape sequence.
793 bool IsValidEscape(char c) {
794 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
797 // Returns true if and only if the given atom (specified by escaped and
798 // pattern) matches ch. The result is undefined if the atom is invalid.
799 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
800 if (escaped) { // "\\p" where p is pattern_char.
801 switch (pattern_char) {
802 case 'd': return IsAsciiDigit(ch);
803 case 'D': return !IsAsciiDigit(ch);
804 case 'f': return ch == '\f';
805 case 'n': return ch == '\n';
806 case 'r': return ch == '\r';
807 case 's': return IsAsciiWhiteSpace(ch);
808 case 'S': return !IsAsciiWhiteSpace(ch);
809 case 't': return ch == '\t';
810 case 'v': return ch == '\v';
811 case 'w': return IsAsciiWordChar(ch);
812 case 'W': return !IsAsciiWordChar(ch);
814 return IsAsciiPunct(pattern_char) && pattern_char == ch;
817 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
820 // Helper function used by ValidateRegex() to format error messages.
821 static std::string FormatRegexSyntaxError(const char* regex, int index) {
822 return (Message() << "Syntax error at index " << index
823 << " in simple regular expression \"" << regex << "\": ").GetString();
826 // Generates non-fatal failures and returns false if regex is invalid;
827 // otherwise returns true.
828 bool ValidateRegex(const char* regex) {
829 if (regex == nullptr) {
830 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
834 bool is_valid = true;
836 // True if and only if ?, *, or + can follow the previous atom.
837 bool prev_repeatable = false;
838 for (int i = 0; regex[i]; i++) {
839 if (regex[i] == '\\') { // An escape sequence
841 if (regex[i] == '\0') {
842 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
843 << "'\\' cannot appear at the end.";
847 if (!IsValidEscape(regex[i])) {
848 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
849 << "invalid escape sequence \"\\" << regex[i] << "\".";
852 prev_repeatable = true;
853 } else { // Not an escape sequence.
854 const char ch = regex[i];
856 if (ch == '^' && i > 0) {
857 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
858 << "'^' can only appear at the beginning.";
860 } else if (ch == '$' && regex[i + 1] != '\0') {
861 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
862 << "'$' can only appear at the end.";
864 } else if (IsInSet(ch, "()[]{}|")) {
865 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
866 << "'" << ch << "' is unsupported.";
868 } else if (IsRepeat(ch) && !prev_repeatable) {
869 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
870 << "'" << ch << "' can only follow a repeatable token.";
874 prev_repeatable = !IsInSet(ch, "^$?*+");
881 // Matches a repeated regex atom followed by a valid simple regular
882 // expression. The regex atom is defined as c if escaped is false,
883 // or \c otherwise. repeat is the repetition meta character (?, *,
884 // or +). The behavior is undefined if str contains too many
885 // characters to be indexable by size_t, in which case the test will
886 // probably time out anyway. We are fine with this limitation as
887 // std::string has it too.
888 bool MatchRepetitionAndRegexAtHead(
889 bool escaped, char c, char repeat, const char* regex,
891 const size_t min_count = (repeat == '+') ? 1 : 0;
892 const size_t max_count = (repeat == '?') ? 1 :
893 static_cast<size_t>(-1) - 1;
894 // We cannot call numeric_limits::max() as it conflicts with the
895 // max() macro on Windows.
897 for (size_t i = 0; i <= max_count; ++i) {
898 // We know that the atom matches each of the first i characters in str.
899 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
900 // We have enough matches at the head, and the tail matches too.
901 // Since we only care about *whether* the pattern matches str
902 // (as opposed to *how* it matches), there is no need to find a
906 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
912 // Returns true if and only if regex matches a prefix of str. regex must
913 // be a valid simple regular expression and not start with "^", or the
914 // result is undefined.
915 bool MatchRegexAtHead(const char* regex, const char* str) {
916 if (*regex == '\0') // An empty regex matches a prefix of anything.
919 // "$" only matches the end of a string. Note that regex being
920 // valid guarantees that there's nothing after "$" in it.
924 // Is the first thing in regex an escape sequence?
925 const bool escaped = *regex == '\\';
928 if (IsRepeat(regex[1])) {
929 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
930 // here's an indirect recursion. It terminates as the regex gets
931 // shorter in each recursion.
932 return MatchRepetitionAndRegexAtHead(
933 escaped, regex[0], regex[1], regex + 2, str);
935 // regex isn't empty, isn't "$", and doesn't start with a
936 // repetition. We match the first atom of regex with the first
937 // character of str and recurse.
938 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
939 MatchRegexAtHead(regex + 1, str + 1);
943 // Returns true if and only if regex matches any substring of str. regex must
944 // be a valid simple regular expression, or the result is undefined.
946 // The algorithm is recursive, but the recursion depth doesn't exceed
947 // the regex length, so we won't need to worry about running out of
948 // stack space normally. In rare cases the time complexity can be
949 // exponential with respect to the regex length + the string length,
950 // but usually it's must faster (often close to linear).
951 bool MatchRegexAnywhere(const char* regex, const char* str) {
952 if (regex == nullptr || str == nullptr) return false;
955 return MatchRegexAtHead(regex + 1, str);
957 // A successful match can be anywhere in str.
959 if (MatchRegexAtHead(regex, str))
961 } while (*str++ != '\0');
965 // Implements the RE class.
968 free(const_cast<char*>(pattern_));
969 free(const_cast<char*>(full_pattern_));
972 // Returns true if and only if regular expression re matches the entire str.
973 bool RE::FullMatch(const char* str, const RE& re) {
974 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
977 // Returns true if and only if regular expression re matches a substring of
978 // str (including str itself).
979 bool RE::PartialMatch(const char* str, const RE& re) {
980 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
983 // Initializes an RE from its string representation.
984 void RE::Init(const char* regex) {
985 pattern_ = full_pattern_ = nullptr;
986 if (regex != nullptr) {
987 pattern_ = posix::StrDup(regex);
990 is_valid_ = ValidateRegex(regex);
992 // No need to calculate the full pattern when the regex is invalid.
996 const size_t len = strlen(regex);
997 // Reserves enough bytes to hold the regular expression used for a
998 // full match: we need space to prepend a '^', append a '$', and
999 // terminate the string with '\0'.
1000 char* buffer = static_cast<char*>(malloc(len + 3));
1001 full_pattern_ = buffer;
1004 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
1006 // We don't use snprintf or strncpy, as they trigger a warning when
1007 // compiled with VC++ 8.0.
1008 memcpy(buffer, regex, len);
1011 if (len == 0 || regex[len - 1] != '$')
1012 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
1017 #endif // GTEST_USES_POSIX_RE
1019 const char kUnknownFile[] = "unknown file";
1021 // Formats a source file path and a line number as they would appear
1022 // in an error message from the compiler used to compile this code.
1023 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
1024 const std::string file_name(file == nullptr ? kUnknownFile : file);
1027 return file_name + ":";
1030 return file_name + "(" + StreamableToString(line) + "):";
1032 return file_name + ":" + StreamableToString(line) + ":";
1036 // Formats a file location for compiler-independent XML output.
1037 // Although this function is not platform dependent, we put it next to
1038 // FormatFileLocation in order to contrast the two functions.
1039 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
1040 // to the file location it produces, unlike FormatFileLocation().
1041 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
1042 const char* file, int line) {
1043 const std::string file_name(file == nullptr ? kUnknownFile : file);
1048 return file_name + ":" + StreamableToString(line);
1051 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
1052 : severity_(severity) {
1053 const char* const marker =
1054 severity == GTEST_INFO ? "[ INFO ]" :
1055 severity == GTEST_WARNING ? "[WARNING]" :
1056 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
1057 GetStream() << ::std::endl << marker << " "
1058 << FormatFileLocation(file, line).c_str() << ": ";
1061 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1062 GTestLog::~GTestLog() {
1063 GetStream() << ::std::endl;
1064 if (severity_ == GTEST_FATAL) {
1070 // Disable Microsoft deprecation warnings for POSIX functions called from
1071 // this class (creat, dup, dup2, and close)
1072 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
1074 #if GTEST_HAS_STREAM_REDIRECTION
1076 // Object that captures an output stream (stdout/stderr).
1077 class CapturedStream {
1079 // The ctor redirects the stream to a temporary file.
1080 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
1081 # if GTEST_OS_WINDOWS
1082 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
1083 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
1085 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
1086 const UINT success = ::GetTempFileNameA(temp_dir_path,
1088 0, // Generate unique file name.
1090 GTEST_CHECK_(success != 0)
1091 << "Unable to create a temporary file in " << temp_dir_path;
1092 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
1093 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
1095 filename_ = temp_file_path;
1097 // There's no guarantee that a test has write access to the current
1098 // directory, so we create the temporary file in a temporary directory.
1099 std::string name_template;
1101 # if GTEST_OS_LINUX_ANDROID
1102 // Note: Android applications are expected to call the framework's
1103 // Context.getExternalStorageDirectory() method through JNI to get
1104 // the location of the world-writable SD Card directory. However,
1105 // this requires a Context handle, which cannot be retrieved
1106 // globally from native code. Doing so also precludes running the
1107 // code as part of a regular standalone executable, which doesn't
1108 // run in a Dalvik process (e.g. when running it through 'adb shell').
1110 // The location /data/local/tmp is directly accessible from native code.
1111 // '/sdcard' and other variants cannot be relied on, as they are not
1112 // guaranteed to be mounted, or may have a delay in mounting.
1113 name_template = "/data/local/tmp/";
1115 char user_temp_dir[PATH_MAX + 1];
1117 // Documented alternative to NSTemporaryDirectory() (for obtaining creating
1118 // a temporary directory) at
1119 // https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10
1121 // _CS_DARWIN_USER_TEMP_DIR (as well as _CS_DARWIN_USER_CACHE_DIR) is not
1122 // documented in the confstr() man page at
1123 // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/confstr.3.html#//apple_ref/doc/man/3/confstr
1124 // but are still available, according to the WebKit patches at
1125 // https://trac.webkit.org/changeset/262004/webkit
1126 // https://trac.webkit.org/changeset/263705/webkit
1128 // The confstr() implementation falls back to getenv("TMPDIR"). See
1129 // https://opensource.apple.com/source/Libc/Libc-1439.100.3/gen/confstr.c.auto.html
1130 ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir));
1132 name_template = user_temp_dir;
1133 if (name_template.back() != GTEST_PATH_SEP_[0])
1134 name_template.push_back(GTEST_PATH_SEP_[0]);
1136 name_template = "/tmp/";
1138 name_template.append("gtest_captured_stream.XXXXXX");
1140 // mkstemp() modifies the string bytes in place, and does not go beyond the
1141 // string's length. This results in well-defined behavior in C++17.
1143 // The const_cast is needed below C++17. The constraints on std::string
1144 // implementations in C++11 and above make assumption behind the const_cast
1146 const int captured_fd = ::mkstemp(const_cast<char*>(name_template.data()));
1147 if (captured_fd == -1) {
1149 << "Failed to create tmp file " << name_template
1150 << " for test; does the test have access to the /tmp directory?";
1152 filename_ = std::move(name_template);
1153 # endif // GTEST_OS_WINDOWS
1155 dup2(captured_fd, fd_);
1160 remove(filename_.c_str());
1163 std::string GetCapturedString() {
1164 if (uncaptured_fd_ != -1) {
1165 // Restores the original stream.
1167 dup2(uncaptured_fd_, fd_);
1168 close(uncaptured_fd_);
1169 uncaptured_fd_ = -1;
1172 FILE* const file = posix::FOpen(filename_.c_str(), "r");
1173 if (file == nullptr) {
1174 GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
1175 << " for capturing stream.";
1177 const std::string content = ReadEntireFile(file);
1178 posix::FClose(file);
1183 const int fd_; // A stream to capture.
1185 // Name of the temporary file holding the stderr output.
1186 ::std::string filename_;
1188 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
1191 GTEST_DISABLE_MSC_DEPRECATED_POP_()
1193 static CapturedStream* g_captured_stderr = nullptr;
1194 static CapturedStream* g_captured_stdout = nullptr;
1196 // Starts capturing an output stream (stdout/stderr).
1197 static void CaptureStream(int fd, const char* stream_name,
1198 CapturedStream** stream) {
1199 if (*stream != nullptr) {
1200 GTEST_LOG_(FATAL) << "Only one " << stream_name
1201 << " capturer can exist at a time.";
1203 *stream = new CapturedStream(fd);
1206 // Stops capturing the output stream and returns the captured string.
1207 static std::string GetCapturedStream(CapturedStream** captured_stream) {
1208 const std::string content = (*captured_stream)->GetCapturedString();
1210 delete *captured_stream;
1211 *captured_stream = nullptr;
1216 // Starts capturing stdout.
1217 void CaptureStdout() {
1218 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
1221 // Starts capturing stderr.
1222 void CaptureStderr() {
1223 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
1226 // Stops capturing stdout and returns the captured string.
1227 std::string GetCapturedStdout() {
1228 return GetCapturedStream(&g_captured_stdout);
1231 // Stops capturing stderr and returns the captured string.
1232 std::string GetCapturedStderr() {
1233 return GetCapturedStream(&g_captured_stderr);
1236 #endif // GTEST_HAS_STREAM_REDIRECTION
1242 size_t GetFileSize(FILE* file) {
1243 fseek(file, 0, SEEK_END);
1244 return static_cast<size_t>(ftell(file));
1247 std::string ReadEntireFile(FILE* file) {
1248 const size_t file_size = GetFileSize(file);
1249 char* const buffer = new char[file_size];
1251 size_t bytes_last_read = 0; // # of bytes read in the last fread()
1252 size_t bytes_read = 0; // # of bytes read so far
1254 fseek(file, 0, SEEK_SET);
1256 // Keeps reading the file until we cannot read further or the
1257 // pre-determined file size is reached.
1259 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
1260 bytes_read += bytes_last_read;
1261 } while (bytes_last_read > 0 && bytes_read < file_size);
1263 const std::string content(buffer, bytes_read);
1269 #if GTEST_HAS_DEATH_TEST
1270 static const std::vector<std::string>* g_injected_test_argvs =
1273 std::vector<std::string> GetInjectableArgvs() {
1274 if (g_injected_test_argvs != nullptr) {
1275 return *g_injected_test_argvs;
1280 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
1281 if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
1282 g_injected_test_argvs = new_argvs;
1285 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
1287 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
1290 void ClearInjectableArgvs() {
1291 delete g_injected_test_argvs;
1292 g_injected_test_argvs = nullptr;
1294 #endif // GTEST_HAS_DEATH_TEST
1296 #if GTEST_OS_WINDOWS_MOBILE
1300 TerminateProcess(GetCurrentProcess(), 1);
1302 } // namespace posix
1303 #endif // GTEST_OS_WINDOWS_MOBILE
1305 // Returns the name of the environment variable corresponding to the
1306 // given flag. For example, FlagToEnvVar("foo") will return
1307 // "GTEST_FOO" in the open-source version.
1308 static std::string FlagToEnvVar(const char* flag) {
1309 const std::string full_flag =
1310 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
1313 for (size_t i = 0; i != full_flag.length(); i++) {
1314 env_var << ToUpper(full_flag.c_str()[i]);
1317 return env_var.GetString();
1320 // Parses 'str' for a 32-bit signed integer. If successful, writes
1321 // the result to *value and returns true; otherwise leaves *value
1322 // unchanged and returns false.
1323 bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
1324 // Parses the environment variable as a decimal integer.
1325 char* end = nullptr;
1326 const long long_value = strtol(str, &end, 10); // NOLINT
1328 // Has strtol() consumed all characters in the string?
1330 // No - an invalid character was encountered.
1332 msg << "WARNING: " << src_text
1333 << " is expected to be a 32-bit integer, but actually"
1334 << " has value \"" << str << "\".\n";
1335 printf("%s", msg.GetString().c_str());
1340 // Is the parsed value in the range of an int32_t?
1341 const auto result = static_cast<int32_t>(long_value);
1342 if (long_value == LONG_MAX || long_value == LONG_MIN ||
1343 // The parsed value overflows as a long. (strtol() returns
1344 // LONG_MAX or LONG_MIN when the input overflows.)
1345 result != long_value
1346 // The parsed value overflows as an int32_t.
1349 msg << "WARNING: " << src_text
1350 << " is expected to be a 32-bit integer, but actually"
1351 << " has value " << str << ", which overflows.\n";
1352 printf("%s", msg.GetString().c_str());
1361 // Reads and returns the Boolean environment variable corresponding to
1362 // the given flag; if it's not set, returns default_value.
1364 // The value is considered true if and only if it's not "0".
1365 bool BoolFromGTestEnv(const char* flag, bool default_value) {
1366 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1367 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1369 const std::string env_var = FlagToEnvVar(flag);
1370 const char* const string_value = posix::GetEnv(env_var.c_str());
1371 return string_value == nullptr ? default_value
1372 : strcmp(string_value, "0") != 0;
1373 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1376 // Reads and returns a 32-bit integer stored in the environment
1377 // variable corresponding to the given flag; if it isn't set or
1378 // doesn't represent a valid 32-bit integer, returns default_value.
1379 int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
1380 #if defined(GTEST_GET_INT32_FROM_ENV_)
1381 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1383 const std::string env_var = FlagToEnvVar(flag);
1384 const char* const string_value = posix::GetEnv(env_var.c_str());
1385 if (string_value == nullptr) {
1386 // The environment variable is not set.
1387 return default_value;
1390 int32_t result = default_value;
1391 if (!ParseInt32(Message() << "Environment variable " << env_var,
1392 string_value, &result)) {
1393 printf("The default value %s is used.\n",
1394 (Message() << default_value).GetString().c_str());
1396 return default_value;
1400 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1403 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
1404 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
1405 // system. The value of XML_OUTPUT_FILE is a filename without the
1406 // "xml:" prefix of GTEST_OUTPUT.
1407 // Note that this is meant to be called at the call site so it does
1408 // not check that the flag is 'output'
1409 // In essence this checks an env variable called XML_OUTPUT_FILE
1410 // and if it is set we prepend "xml:" to its value, if it not set we return ""
1411 std::string OutputFlagAlsoCheckEnvVar(){
1412 std::string default_value_for_output_flag = "";
1413 const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
1414 if (nullptr != xml_output_file_env) {
1415 default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
1417 return default_value_for_output_flag;
1420 // Reads and returns the string environment variable corresponding to
1421 // the given flag; if it's not set, returns default_value.
1422 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
1423 #if defined(GTEST_GET_STRING_FROM_ENV_)
1424 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1426 const std::string env_var = FlagToEnvVar(flag);
1427 const char* const value = posix::GetEnv(env_var.c_str());
1428 return value == nullptr ? default_value : value;
1429 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
1432 } // namespace internal
1433 } // namespace testing