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
;
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)) {
201 mib
[5] = size
/ mib
[4];
203 // populate array of structs
204 struct kinfo_proc info
[mib
[5]];
205 if (sysctl(mib
, miblen
, &info
, &size
, NULL
, 0)) {
209 // exclude empty members
211 for (int i
= 0; i
< size
/ mib
[4]; i
++) {
212 if (info
[i
].p_tid
!= -1)
220 // Returns the number of threads running in the process, or 0 to indicate that
221 // we cannot detect it.
222 size_t GetThreadCount() {
223 const int fd
= open("/proc/self/as", O_RDONLY
);
227 procfs_info process_info
;
229 devctl(fd
, DCMD_PROC_INFO
, &process_info
, sizeof(process_info
), nullptr);
232 return static_cast<size_t>(process_info
.num_threads
);
240 size_t GetThreadCount() {
241 struct procentry64 entry
;
242 pid_t pid
= getpid();
243 int status
= getprocs64(&entry
, sizeof(entry
), nullptr, 0, &pid
, 1);
245 return entry
.pi_thcount
;
251 #elif GTEST_OS_FUCHSIA
253 size_t GetThreadCount() {
256 zx_status_t status
= zx_object_get_info(
258 ZX_INFO_PROCESS_THREADS
,
263 if (status
== ZX_OK
) {
272 size_t GetThreadCount() {
273 // There's no portable way to detect the number of threads, so we just
274 // return 0 to indicate that we cannot detect it.
278 #endif // GTEST_OS_LINUX
280 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
282 void SleepMilliseconds(int n
) {
283 ::Sleep(static_cast<DWORD
>(n
));
286 AutoHandle::AutoHandle()
287 : handle_(INVALID_HANDLE_VALUE
) {}
289 AutoHandle::AutoHandle(Handle handle
)
292 AutoHandle::~AutoHandle() {
296 AutoHandle::Handle
AutoHandle::Get() const {
300 void AutoHandle::Reset() {
301 Reset(INVALID_HANDLE_VALUE
);
304 void AutoHandle::Reset(HANDLE handle
) {
305 // Resetting with the same handle we already own is invalid.
306 if (handle_
!= handle
) {
308 ::CloseHandle(handle_
);
312 GTEST_CHECK_(!IsCloseable())
313 << "Resetting a valid handle to itself is likely a programmer error "
314 "and thus not allowed.";
318 bool AutoHandle::IsCloseable() const {
319 // Different Windows APIs may use either of these values to represent an
321 return handle_
!= nullptr && handle_
!= INVALID_HANDLE_VALUE
;
324 Notification::Notification()
325 : event_(::CreateEvent(nullptr, // Default security attributes.
326 TRUE
, // Do not reset automatically.
327 FALSE
, // Initially unset.
328 nullptr)) { // Anonymous event.
329 GTEST_CHECK_(event_
.Get() != nullptr);
332 void Notification::Notify() {
333 GTEST_CHECK_(::SetEvent(event_
.Get()) != FALSE
);
336 void Notification::WaitForNotification() {
338 ::WaitForSingleObject(event_
.Get(), INFINITE
) == WAIT_OBJECT_0
);
342 : owner_thread_id_(0),
344 critical_section_init_phase_(0),
345 critical_section_(new CRITICAL_SECTION
) {
346 ::InitializeCriticalSection(critical_section_
);
350 // Static mutexes are leaked intentionally. It is not thread-safe to try
352 if (type_
== kDynamic
) {
353 ::DeleteCriticalSection(critical_section_
);
354 delete critical_section_
;
355 critical_section_
= nullptr;
360 ThreadSafeLazyInit();
361 ::EnterCriticalSection(critical_section_
);
362 owner_thread_id_
= ::GetCurrentThreadId();
365 void Mutex::Unlock() {
366 ThreadSafeLazyInit();
367 // We don't protect writing to owner_thread_id_ here, as it's the
368 // caller's responsibility to ensure that the current thread holds the
369 // mutex when this is called.
370 owner_thread_id_
= 0;
371 ::LeaveCriticalSection(critical_section_
);
374 // Does nothing if the current thread holds the mutex. Otherwise, crashes
375 // with high probability.
376 void Mutex::AssertHeld() {
377 ThreadSafeLazyInit();
378 GTEST_CHECK_(owner_thread_id_
== ::GetCurrentThreadId())
379 << "The current thread is not holding the mutex @" << this;
385 // Use the RAII idiom to flag mem allocs that are intentionally never
386 // deallocated. The motivation is to silence the false positive mem leaks
387 // that are reported by the debug version of MS's CRT which can only detect
388 // if an alloc is missing a matching deallocation.
390 // MemoryIsNotDeallocated memory_is_not_deallocated;
391 // critical_section_ = new CRITICAL_SECTION;
393 class MemoryIsNotDeallocated
396 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
397 old_crtdbg_flag_
= _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG
);
398 // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
399 // doesn't report mem leak if there's no matching deallocation.
400 _CrtSetDbgFlag(old_crtdbg_flag_
& ~_CRTDBG_ALLOC_MEM_DF
);
403 ~MemoryIsNotDeallocated() {
404 // Restore the original _CRTDBG_ALLOC_MEM_DF flag
405 _CrtSetDbgFlag(old_crtdbg_flag_
);
409 int old_crtdbg_flag_
;
411 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated
);
417 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
418 void Mutex::ThreadSafeLazyInit() {
419 // Dynamic mutexes are initialized in the constructor.
420 if (type_
== kStatic
) {
422 ::InterlockedCompareExchange(&critical_section_init_phase_
, 1L, 0L)) {
424 // If critical_section_init_phase_ was 0 before the exchange, we
425 // are the first to test it and need to perform the initialization.
426 owner_thread_id_
= 0;
428 // Use RAII to flag that following mem alloc is never deallocated.
430 MemoryIsNotDeallocated memory_is_not_deallocated
;
432 critical_section_
= new CRITICAL_SECTION
;
434 ::InitializeCriticalSection(critical_section_
);
435 // Updates the critical_section_init_phase_ to 2 to signal
436 // initialization complete.
437 GTEST_CHECK_(::InterlockedCompareExchange(
438 &critical_section_init_phase_
, 2L, 1L) ==
442 // Somebody else is already initializing the mutex; spin until they
444 while (::InterlockedCompareExchange(&critical_section_init_phase_
,
447 // Possibly yields the rest of the thread's time slice to other
454 break; // The mutex is already initialized and ready for use.
458 << "Unexpected value of critical_section_init_phase_ "
459 << "while initializing a static mutex.";
466 class ThreadWithParamSupport
: public ThreadWithParamBase
{
468 static HANDLE
CreateThread(Runnable
* runnable
,
469 Notification
* thread_can_start
) {
470 ThreadMainParam
* param
= new ThreadMainParam(runnable
, thread_can_start
);
472 HANDLE thread_handle
= ::CreateThread(
473 nullptr, // Default security.
474 0, // Default stack size.
475 &ThreadWithParamSupport::ThreadMain
,
476 param
, // Parameter to ThreadMainStatic
477 0x0, // Default creation flags.
478 &thread_id
); // Need a valid pointer for the call to work under Win98.
479 GTEST_CHECK_(thread_handle
!= nullptr)
480 << "CreateThread failed with error " << ::GetLastError() << ".";
481 if (thread_handle
== nullptr) {
484 return thread_handle
;
488 struct ThreadMainParam
{
489 ThreadMainParam(Runnable
* runnable
, Notification
* thread_can_start
)
490 : runnable_(runnable
),
491 thread_can_start_(thread_can_start
) {
493 std::unique_ptr
<Runnable
> runnable_
;
495 Notification
* thread_can_start_
;
498 static DWORD WINAPI
ThreadMain(void* ptr
) {
499 // Transfers ownership.
500 std::unique_ptr
<ThreadMainParam
> param(static_cast<ThreadMainParam
*>(ptr
));
501 if (param
->thread_can_start_
!= nullptr)
502 param
->thread_can_start_
->WaitForNotification();
503 param
->runnable_
->Run();
507 // Prohibit instantiation.
508 ThreadWithParamSupport();
510 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport
);
515 ThreadWithParamBase::ThreadWithParamBase(Runnable
*runnable
,
516 Notification
* thread_can_start
)
517 : thread_(ThreadWithParamSupport::CreateThread(runnable
,
521 ThreadWithParamBase::~ThreadWithParamBase() {
525 void ThreadWithParamBase::Join() {
526 GTEST_CHECK_(::WaitForSingleObject(thread_
.Get(), INFINITE
) == WAIT_OBJECT_0
)
527 << "Failed to join the thread with error " << ::GetLastError() << ".";
530 // Maps a thread to a set of ThreadIdToThreadLocals that have values
531 // instantiated on that thread and notifies them when the thread exits. A
532 // ThreadLocal instance is expected to persist until all threads it has
533 // values on have terminated.
534 class ThreadLocalRegistryImpl
{
536 // Registers thread_local_instance as having value on the current thread.
537 // Returns a value that can be used to identify the thread from other threads.
538 static ThreadLocalValueHolderBase
* GetValueOnCurrentThread(
539 const ThreadLocalBase
* thread_local_instance
) {
541 MemoryIsNotDeallocated memory_is_not_deallocated
;
543 DWORD current_thread
= ::GetCurrentThreadId();
544 MutexLock
lock(&mutex_
);
545 ThreadIdToThreadLocals
* const thread_to_thread_locals
=
546 GetThreadLocalsMapLocked();
547 ThreadIdToThreadLocals::iterator thread_local_pos
=
548 thread_to_thread_locals
->find(current_thread
);
549 if (thread_local_pos
== thread_to_thread_locals
->end()) {
550 thread_local_pos
= thread_to_thread_locals
->insert(
551 std::make_pair(current_thread
, ThreadLocalValues())).first
;
552 StartWatcherThreadFor(current_thread
);
554 ThreadLocalValues
& thread_local_values
= thread_local_pos
->second
;
555 ThreadLocalValues::iterator value_pos
=
556 thread_local_values
.find(thread_local_instance
);
557 if (value_pos
== thread_local_values
.end()) {
560 .insert(std::make_pair(
561 thread_local_instance
,
562 std::shared_ptr
<ThreadLocalValueHolderBase
>(
563 thread_local_instance
->NewValueForCurrentThread())))
566 return value_pos
->second
.get();
569 static void OnThreadLocalDestroyed(
570 const ThreadLocalBase
* thread_local_instance
) {
571 std::vector
<std::shared_ptr
<ThreadLocalValueHolderBase
> > value_holders
;
572 // Clean up the ThreadLocalValues data structure while holding the lock, but
573 // defer the destruction of the ThreadLocalValueHolderBases.
575 MutexLock
lock(&mutex_
);
576 ThreadIdToThreadLocals
* const thread_to_thread_locals
=
577 GetThreadLocalsMapLocked();
578 for (ThreadIdToThreadLocals::iterator it
=
579 thread_to_thread_locals
->begin();
580 it
!= thread_to_thread_locals
->end();
582 ThreadLocalValues
& thread_local_values
= it
->second
;
583 ThreadLocalValues::iterator value_pos
=
584 thread_local_values
.find(thread_local_instance
);
585 if (value_pos
!= thread_local_values
.end()) {
586 value_holders
.push_back(value_pos
->second
);
587 thread_local_values
.erase(value_pos
);
588 // This 'if' can only be successful at most once, so theoretically we
589 // could break out of the loop here, but we don't bother doing so.
593 // Outside the lock, let the destructor for 'value_holders' deallocate the
594 // ThreadLocalValueHolderBases.
597 static void OnThreadExit(DWORD thread_id
) {
598 GTEST_CHECK_(thread_id
!= 0) << ::GetLastError();
599 std::vector
<std::shared_ptr
<ThreadLocalValueHolderBase
> > value_holders
;
600 // Clean up the ThreadIdToThreadLocals data structure while holding the
601 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
603 MutexLock
lock(&mutex_
);
604 ThreadIdToThreadLocals
* const thread_to_thread_locals
=
605 GetThreadLocalsMapLocked();
606 ThreadIdToThreadLocals::iterator thread_local_pos
=
607 thread_to_thread_locals
->find(thread_id
);
608 if (thread_local_pos
!= thread_to_thread_locals
->end()) {
609 ThreadLocalValues
& thread_local_values
= thread_local_pos
->second
;
610 for (ThreadLocalValues::iterator value_pos
=
611 thread_local_values
.begin();
612 value_pos
!= thread_local_values
.end();
614 value_holders
.push_back(value_pos
->second
);
616 thread_to_thread_locals
->erase(thread_local_pos
);
619 // Outside the lock, let the destructor for 'value_holders' deallocate the
620 // ThreadLocalValueHolderBases.
624 // In a particular thread, maps a ThreadLocal object to its value.
625 typedef std::map
<const ThreadLocalBase
*,
626 std::shared_ptr
<ThreadLocalValueHolderBase
> >
628 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
630 typedef std::map
<DWORD
, ThreadLocalValues
> ThreadIdToThreadLocals
;
632 // Holds the thread id and thread handle that we pass from
633 // StartWatcherThreadFor to WatcherThreadFunc.
634 typedef std::pair
<DWORD
, HANDLE
> ThreadIdAndHandle
;
636 static void StartWatcherThreadFor(DWORD thread_id
) {
637 // The returned handle will be kept in thread_map and closed by
638 // watcher_thread in WatcherThreadFunc.
639 HANDLE thread
= ::OpenThread(SYNCHRONIZE
| THREAD_QUERY_INFORMATION
,
642 GTEST_CHECK_(thread
!= nullptr);
643 // We need to pass a valid thread ID pointer into CreateThread for it
644 // to work correctly under Win98.
645 DWORD watcher_thread_id
;
646 HANDLE watcher_thread
= ::CreateThread(
647 nullptr, // Default security.
648 0, // Default stack size
649 &ThreadLocalRegistryImpl::WatcherThreadFunc
,
650 reinterpret_cast<LPVOID
>(new ThreadIdAndHandle(thread_id
, thread
)),
651 CREATE_SUSPENDED
, &watcher_thread_id
);
652 GTEST_CHECK_(watcher_thread
!= nullptr);
653 // Give the watcher thread the same priority as ours to avoid being
655 ::SetThreadPriority(watcher_thread
,
656 ::GetThreadPriority(::GetCurrentThread()));
657 ::ResumeThread(watcher_thread
);
658 ::CloseHandle(watcher_thread
);
661 // Monitors exit from a given thread and notifies those
662 // ThreadIdToThreadLocals about thread termination.
663 static DWORD WINAPI
WatcherThreadFunc(LPVOID param
) {
664 const ThreadIdAndHandle
* tah
=
665 reinterpret_cast<const ThreadIdAndHandle
*>(param
);
667 ::WaitForSingleObject(tah
->second
, INFINITE
) == WAIT_OBJECT_0
);
668 OnThreadExit(tah
->first
);
669 ::CloseHandle(tah
->second
);
674 // Returns map of thread local instances.
675 static ThreadIdToThreadLocals
* GetThreadLocalsMapLocked() {
678 MemoryIsNotDeallocated memory_is_not_deallocated
;
680 static ThreadIdToThreadLocals
* map
= new ThreadIdToThreadLocals();
684 // Protects access to GetThreadLocalsMapLocked() and its return value.
686 // Protects access to GetThreadMapLocked() and its return value.
687 static Mutex thread_map_mutex_
;
690 Mutex
ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex
);
691 Mutex
ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex
);
693 ThreadLocalValueHolderBase
* ThreadLocalRegistry::GetValueOnCurrentThread(
694 const ThreadLocalBase
* thread_local_instance
) {
695 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
696 thread_local_instance
);
699 void ThreadLocalRegistry::OnThreadLocalDestroyed(
700 const ThreadLocalBase
* thread_local_instance
) {
701 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance
);
704 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
706 #if GTEST_USES_POSIX_RE
708 // Implements RE. Currently only needed for death tests.
712 // regfree'ing an invalid regex might crash because the content
713 // of the regex is undefined. Since the regex's are essentially
714 // the same, one cannot be valid (or invalid) without the other
716 regfree(&partial_regex_
);
717 regfree(&full_regex_
);
719 free(const_cast<char*>(pattern_
));
722 // Returns true if and only if regular expression re matches the entire str.
723 bool RE::FullMatch(const char* str
, const RE
& re
) {
724 if (!re
.is_valid_
) return false;
727 return regexec(&re
.full_regex_
, str
, 1, &match
, 0) == 0;
730 // Returns true if and only if regular expression re matches a substring of
731 // str (including str itself).
732 bool RE::PartialMatch(const char* str
, const RE
& re
) {
733 if (!re
.is_valid_
) return false;
736 return regexec(&re
.partial_regex_
, str
, 1, &match
, 0) == 0;
739 // Initializes an RE from its string representation.
740 void RE::Init(const char* regex
) {
741 pattern_
= posix::StrDup(regex
);
743 // Reserves enough bytes to hold the regular expression used for a
745 const size_t full_regex_len
= strlen(regex
) + 10;
746 char* const full_pattern
= new char[full_regex_len
];
748 snprintf(full_pattern
, full_regex_len
, "^(%s)$", regex
);
749 is_valid_
= regcomp(&full_regex_
, full_pattern
, REG_EXTENDED
) == 0;
750 // We want to call regcomp(&partial_regex_, ...) even if the
751 // previous expression returns false. Otherwise partial_regex_ may
752 // not be properly initialized can may cause trouble when it's
755 // Some implementation of POSIX regex (e.g. on at least some
756 // versions of Cygwin) doesn't accept the empty string as a valid
757 // regex. We change it to an equivalent form "()" to be safe.
759 const char* const partial_regex
= (*regex
== '\0') ? "()" : regex
;
760 is_valid_
= regcomp(&partial_regex_
, partial_regex
, REG_EXTENDED
) == 0;
762 EXPECT_TRUE(is_valid_
)
763 << "Regular expression \"" << regex
764 << "\" is not a valid POSIX Extended regular expression.";
766 delete[] full_pattern
;
769 #elif GTEST_USES_SIMPLE_RE
771 // Returns true if and only if ch appears anywhere in str (excluding the
772 // terminating '\0' character).
773 bool IsInSet(char ch
, const char* str
) {
774 return ch
!= '\0' && strchr(str
, ch
) != nullptr;
777 // Returns true if and only if ch belongs to the given classification.
778 // Unlike similar functions in <ctype.h>, these aren't affected by the
780 bool IsAsciiDigit(char ch
) { return '0' <= ch
&& ch
<= '9'; }
781 bool IsAsciiPunct(char ch
) {
782 return IsInSet(ch
, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
784 bool IsRepeat(char ch
) { return IsInSet(ch
, "?*+"); }
785 bool IsAsciiWhiteSpace(char ch
) { return IsInSet(ch
, " \f\n\r\t\v"); }
786 bool IsAsciiWordChar(char ch
) {
787 return ('a' <= ch
&& ch
<= 'z') || ('A' <= ch
&& ch
<= 'Z') ||
788 ('0' <= ch
&& ch
<= '9') || ch
== '_';
791 // Returns true if and only if "\\c" is a supported escape sequence.
792 bool IsValidEscape(char c
) {
793 return (IsAsciiPunct(c
) || IsInSet(c
, "dDfnrsStvwW"));
796 // Returns true if and only if the given atom (specified by escaped and
797 // pattern) matches ch. The result is undefined if the atom is invalid.
798 bool AtomMatchesChar(bool escaped
, char pattern_char
, char ch
) {
799 if (escaped
) { // "\\p" where p is pattern_char.
800 switch (pattern_char
) {
801 case 'd': return IsAsciiDigit(ch
);
802 case 'D': return !IsAsciiDigit(ch
);
803 case 'f': return ch
== '\f';
804 case 'n': return ch
== '\n';
805 case 'r': return ch
== '\r';
806 case 's': return IsAsciiWhiteSpace(ch
);
807 case 'S': return !IsAsciiWhiteSpace(ch
);
808 case 't': return ch
== '\t';
809 case 'v': return ch
== '\v';
810 case 'w': return IsAsciiWordChar(ch
);
811 case 'W': return !IsAsciiWordChar(ch
);
813 return IsAsciiPunct(pattern_char
) && pattern_char
== ch
;
816 return (pattern_char
== '.' && ch
!= '\n') || pattern_char
== ch
;
819 // Helper function used by ValidateRegex() to format error messages.
820 static std::string
FormatRegexSyntaxError(const char* regex
, int index
) {
821 return (Message() << "Syntax error at index " << index
822 << " in simple regular expression \"" << regex
<< "\": ").GetString();
825 // Generates non-fatal failures and returns false if regex is invalid;
826 // otherwise returns true.
827 bool ValidateRegex(const char* regex
) {
828 if (regex
== nullptr) {
829 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
833 bool is_valid
= true;
835 // True if and only if ?, *, or + can follow the previous atom.
836 bool prev_repeatable
= false;
837 for (int i
= 0; regex
[i
]; i
++) {
838 if (regex
[i
] == '\\') { // An escape sequence
840 if (regex
[i
] == '\0') {
841 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
842 << "'\\' cannot appear at the end.";
846 if (!IsValidEscape(regex
[i
])) {
847 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
848 << "invalid escape sequence \"\\" << regex
[i
] << "\".";
851 prev_repeatable
= true;
852 } else { // Not an escape sequence.
853 const char ch
= regex
[i
];
855 if (ch
== '^' && i
> 0) {
856 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
857 << "'^' can only appear at the beginning.";
859 } else if (ch
== '$' && regex
[i
+ 1] != '\0') {
860 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
861 << "'$' can only appear at the end.";
863 } else if (IsInSet(ch
, "()[]{}|")) {
864 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
865 << "'" << ch
<< "' is unsupported.";
867 } else if (IsRepeat(ch
) && !prev_repeatable
) {
868 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
869 << "'" << ch
<< "' can only follow a repeatable token.";
873 prev_repeatable
= !IsInSet(ch
, "^$?*+");
880 // Matches a repeated regex atom followed by a valid simple regular
881 // expression. The regex atom is defined as c if escaped is false,
882 // or \c otherwise. repeat is the repetition meta character (?, *,
883 // or +). The behavior is undefined if str contains too many
884 // characters to be indexable by size_t, in which case the test will
885 // probably time out anyway. We are fine with this limitation as
886 // std::string has it too.
887 bool MatchRepetitionAndRegexAtHead(
888 bool escaped
, char c
, char repeat
, const char* regex
,
890 const size_t min_count
= (repeat
== '+') ? 1 : 0;
891 const size_t max_count
= (repeat
== '?') ? 1 :
892 static_cast<size_t>(-1) - 1;
893 // We cannot call numeric_limits::max() as it conflicts with the
894 // max() macro on Windows.
896 for (size_t i
= 0; i
<= max_count
; ++i
) {
897 // We know that the atom matches each of the first i characters in str.
898 if (i
>= min_count
&& MatchRegexAtHead(regex
, str
+ i
)) {
899 // We have enough matches at the head, and the tail matches too.
900 // Since we only care about *whether* the pattern matches str
901 // (as opposed to *how* it matches), there is no need to find a
905 if (str
[i
] == '\0' || !AtomMatchesChar(escaped
, c
, str
[i
]))
911 // Returns true if and only if regex matches a prefix of str. regex must
912 // be a valid simple regular expression and not start with "^", or the
913 // result is undefined.
914 bool MatchRegexAtHead(const char* regex
, const char* str
) {
915 if (*regex
== '\0') // An empty regex matches a prefix of anything.
918 // "$" only matches the end of a string. Note that regex being
919 // valid guarantees that there's nothing after "$" in it.
923 // Is the first thing in regex an escape sequence?
924 const bool escaped
= *regex
== '\\';
927 if (IsRepeat(regex
[1])) {
928 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
929 // here's an indirect recursion. It terminates as the regex gets
930 // shorter in each recursion.
931 return MatchRepetitionAndRegexAtHead(
932 escaped
, regex
[0], regex
[1], regex
+ 2, str
);
934 // regex isn't empty, isn't "$", and doesn't start with a
935 // repetition. We match the first atom of regex with the first
936 // character of str and recurse.
937 return (*str
!= '\0') && AtomMatchesChar(escaped
, *regex
, *str
) &&
938 MatchRegexAtHead(regex
+ 1, str
+ 1);
942 // Returns true if and only if regex matches any substring of str. regex must
943 // be a valid simple regular expression, or the result is undefined.
945 // The algorithm is recursive, but the recursion depth doesn't exceed
946 // the regex length, so we won't need to worry about running out of
947 // stack space normally. In rare cases the time complexity can be
948 // exponential with respect to the regex length + the string length,
949 // but usually it's must faster (often close to linear).
950 bool MatchRegexAnywhere(const char* regex
, const char* str
) {
951 if (regex
== nullptr || str
== nullptr) return false;
954 return MatchRegexAtHead(regex
+ 1, str
);
956 // A successful match can be anywhere in str.
958 if (MatchRegexAtHead(regex
, str
))
960 } while (*str
++ != '\0');
964 // Implements the RE class.
967 free(const_cast<char*>(pattern_
));
968 free(const_cast<char*>(full_pattern_
));
971 // Returns true if and only if regular expression re matches the entire str.
972 bool RE::FullMatch(const char* str
, const RE
& re
) {
973 return re
.is_valid_
&& MatchRegexAnywhere(re
.full_pattern_
, str
);
976 // Returns true if and only if regular expression re matches a substring of
977 // str (including str itself).
978 bool RE::PartialMatch(const char* str
, const RE
& re
) {
979 return re
.is_valid_
&& MatchRegexAnywhere(re
.pattern_
, str
);
982 // Initializes an RE from its string representation.
983 void RE::Init(const char* regex
) {
984 pattern_
= full_pattern_
= nullptr;
985 if (regex
!= nullptr) {
986 pattern_
= posix::StrDup(regex
);
989 is_valid_
= ValidateRegex(regex
);
991 // No need to calculate the full pattern when the regex is invalid.
995 const size_t len
= strlen(regex
);
996 // Reserves enough bytes to hold the regular expression used for a
997 // full match: we need space to prepend a '^', append a '$', and
998 // terminate the string with '\0'.
999 char* buffer
= static_cast<char*>(malloc(len
+ 3));
1000 full_pattern_
= buffer
;
1003 *buffer
++ = '^'; // Makes sure full_pattern_ starts with '^'.
1005 // We don't use snprintf or strncpy, as they trigger a warning when
1006 // compiled with VC++ 8.0.
1007 memcpy(buffer
, regex
, len
);
1010 if (len
== 0 || regex
[len
- 1] != '$')
1011 *buffer
++ = '$'; // Makes sure full_pattern_ ends with '$'.
1016 #endif // GTEST_USES_POSIX_RE
1018 const char kUnknownFile
[] = "unknown file";
1020 // Formats a source file path and a line number as they would appear
1021 // in an error message from the compiler used to compile this code.
1022 GTEST_API_ ::std::string
FormatFileLocation(const char* file
, int line
) {
1023 const std::string
file_name(file
== nullptr ? kUnknownFile
: file
);
1026 return file_name
+ ":";
1029 return file_name
+ "(" + StreamableToString(line
) + "):";
1031 return file_name
+ ":" + StreamableToString(line
) + ":";
1035 // Formats a file location for compiler-independent XML output.
1036 // Although this function is not platform dependent, we put it next to
1037 // FormatFileLocation in order to contrast the two functions.
1038 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
1039 // to the file location it produces, unlike FormatFileLocation().
1040 GTEST_API_ ::std::string
FormatCompilerIndependentFileLocation(
1041 const char* file
, int line
) {
1042 const std::string
file_name(file
== nullptr ? kUnknownFile
: file
);
1047 return file_name
+ ":" + StreamableToString(line
);
1050 GTestLog::GTestLog(GTestLogSeverity severity
, const char* file
, int line
)
1051 : severity_(severity
) {
1052 const char* const marker
=
1053 severity
== GTEST_INFO
? "[ INFO ]" :
1054 severity
== GTEST_WARNING
? "[WARNING]" :
1055 severity
== GTEST_ERROR
? "[ ERROR ]" : "[ FATAL ]";
1056 GetStream() << ::std::endl
<< marker
<< " "
1057 << FormatFileLocation(file
, line
).c_str() << ": ";
1060 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1061 GTestLog::~GTestLog() {
1062 GetStream() << ::std::endl
;
1063 if (severity_
== GTEST_FATAL
) {
1069 // Disable Microsoft deprecation warnings for POSIX functions called from
1070 // this class (creat, dup, dup2, and close)
1071 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
1073 #if GTEST_HAS_STREAM_REDIRECTION
1075 // Object that captures an output stream (stdout/stderr).
1076 class CapturedStream
{
1078 // The ctor redirects the stream to a temporary file.
1079 explicit CapturedStream(int fd
) : fd_(fd
), uncaptured_fd_(dup(fd
)) {
1080 # if GTEST_OS_WINDOWS
1081 char temp_dir_path
[MAX_PATH
+ 1] = { '\0' }; // NOLINT
1082 char temp_file_path
[MAX_PATH
+ 1] = { '\0' }; // NOLINT
1084 ::GetTempPathA(sizeof(temp_dir_path
), temp_dir_path
);
1085 const UINT success
= ::GetTempFileNameA(temp_dir_path
,
1087 0, // Generate unique file name.
1089 GTEST_CHECK_(success
!= 0)
1090 << "Unable to create a temporary file in " << temp_dir_path
;
1091 const int captured_fd
= creat(temp_file_path
, _S_IREAD
| _S_IWRITE
);
1092 GTEST_CHECK_(captured_fd
!= -1) << "Unable to open temporary file "
1094 filename_
= temp_file_path
;
1096 // There's no guarantee that a test has write access to the current
1097 // directory, so we create the temporary file in the /tmp directory
1098 // instead. We use /tmp on most systems, and /sdcard on Android.
1099 // That's because Android doesn't have /tmp.
1100 # if GTEST_OS_LINUX_ANDROID
1101 // Note: Android applications are expected to call the framework's
1102 // Context.getExternalStorageDirectory() method through JNI to get
1103 // the location of the world-writable SD Card directory. However,
1104 // this requires a Context handle, which cannot be retrieved
1105 // globally from native code. Doing so also precludes running the
1106 // code as part of a regular standalone executable, which doesn't
1107 // run in a Dalvik process (e.g. when running it through 'adb shell').
1109 // The location /data/local/tmp is directly accessible from native code.
1110 // '/sdcard' and other variants cannot be relied on, as they are not
1111 // guaranteed to be mounted, or may have a delay in mounting.
1112 char name_template
[] = "/data/local/tmp/gtest_captured_stream.XXXXXX";
1114 char name_template
[] = "/tmp/captured_stream.XXXXXX";
1115 # endif // GTEST_OS_LINUX_ANDROID
1116 const int captured_fd
= mkstemp(name_template
);
1117 if (captured_fd
== -1) {
1119 << "Failed to create tmp file " << name_template
1120 << " for test; does the test have access to the /tmp directory?";
1122 filename_
= name_template
;
1123 # endif // GTEST_OS_WINDOWS
1125 dup2(captured_fd
, fd_
);
1130 remove(filename_
.c_str());
1133 std::string
GetCapturedString() {
1134 if (uncaptured_fd_
!= -1) {
1135 // Restores the original stream.
1137 dup2(uncaptured_fd_
, fd_
);
1138 close(uncaptured_fd_
);
1139 uncaptured_fd_
= -1;
1142 FILE* const file
= posix::FOpen(filename_
.c_str(), "r");
1143 if (file
== nullptr) {
1144 GTEST_LOG_(FATAL
) << "Failed to open tmp file " << filename_
1145 << " for capturing stream.";
1147 const std::string content
= ReadEntireFile(file
);
1148 posix::FClose(file
);
1153 const int fd_
; // A stream to capture.
1155 // Name of the temporary file holding the stderr output.
1156 ::std::string filename_
;
1158 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream
);
1161 GTEST_DISABLE_MSC_DEPRECATED_POP_()
1163 static CapturedStream
* g_captured_stderr
= nullptr;
1164 static CapturedStream
* g_captured_stdout
= nullptr;
1166 // Starts capturing an output stream (stdout/stderr).
1167 static void CaptureStream(int fd
, const char* stream_name
,
1168 CapturedStream
** stream
) {
1169 if (*stream
!= nullptr) {
1170 GTEST_LOG_(FATAL
) << "Only one " << stream_name
1171 << " capturer can exist at a time.";
1173 *stream
= new CapturedStream(fd
);
1176 // Stops capturing the output stream and returns the captured string.
1177 static std::string
GetCapturedStream(CapturedStream
** captured_stream
) {
1178 const std::string content
= (*captured_stream
)->GetCapturedString();
1180 delete *captured_stream
;
1181 *captured_stream
= nullptr;
1186 // Starts capturing stdout.
1187 void CaptureStdout() {
1188 CaptureStream(kStdOutFileno
, "stdout", &g_captured_stdout
);
1191 // Starts capturing stderr.
1192 void CaptureStderr() {
1193 CaptureStream(kStdErrFileno
, "stderr", &g_captured_stderr
);
1196 // Stops capturing stdout and returns the captured string.
1197 std::string
GetCapturedStdout() {
1198 return GetCapturedStream(&g_captured_stdout
);
1201 // Stops capturing stderr and returns the captured string.
1202 std::string
GetCapturedStderr() {
1203 return GetCapturedStream(&g_captured_stderr
);
1206 #endif // GTEST_HAS_STREAM_REDIRECTION
1212 size_t GetFileSize(FILE* file
) {
1213 fseek(file
, 0, SEEK_END
);
1214 return static_cast<size_t>(ftell(file
));
1217 std::string
ReadEntireFile(FILE* file
) {
1218 const size_t file_size
= GetFileSize(file
);
1219 char* const buffer
= new char[file_size
];
1221 size_t bytes_last_read
= 0; // # of bytes read in the last fread()
1222 size_t bytes_read
= 0; // # of bytes read so far
1224 fseek(file
, 0, SEEK_SET
);
1226 // Keeps reading the file until we cannot read further or the
1227 // pre-determined file size is reached.
1229 bytes_last_read
= fread(buffer
+bytes_read
, 1, file_size
-bytes_read
, file
);
1230 bytes_read
+= bytes_last_read
;
1231 } while (bytes_last_read
> 0 && bytes_read
< file_size
);
1233 const std::string
content(buffer
, bytes_read
);
1239 #if GTEST_HAS_DEATH_TEST
1240 static const std::vector
<std::string
>* g_injected_test_argvs
=
1243 std::vector
<std::string
> GetInjectableArgvs() {
1244 if (g_injected_test_argvs
!= nullptr) {
1245 return *g_injected_test_argvs
;
1250 void SetInjectableArgvs(const std::vector
<std::string
>* new_argvs
) {
1251 if (g_injected_test_argvs
!= new_argvs
) delete g_injected_test_argvs
;
1252 g_injected_test_argvs
= new_argvs
;
1255 void SetInjectableArgvs(const std::vector
<std::string
>& new_argvs
) {
1257 new std::vector
<std::string
>(new_argvs
.begin(), new_argvs
.end()));
1260 void ClearInjectableArgvs() {
1261 delete g_injected_test_argvs
;
1262 g_injected_test_argvs
= nullptr;
1264 #endif // GTEST_HAS_DEATH_TEST
1266 #if GTEST_OS_WINDOWS_MOBILE
1270 TerminateProcess(GetCurrentProcess(), 1);
1272 } // namespace posix
1273 #endif // GTEST_OS_WINDOWS_MOBILE
1275 // Returns the name of the environment variable corresponding to the
1276 // given flag. For example, FlagToEnvVar("foo") will return
1277 // "GTEST_FOO" in the open-source version.
1278 static std::string
FlagToEnvVar(const char* flag
) {
1279 const std::string full_flag
=
1280 (Message() << GTEST_FLAG_PREFIX_
<< flag
).GetString();
1283 for (size_t i
= 0; i
!= full_flag
.length(); i
++) {
1284 env_var
<< ToUpper(full_flag
.c_str()[i
]);
1287 return env_var
.GetString();
1290 // Parses 'str' for a 32-bit signed integer. If successful, writes
1291 // the result to *value and returns true; otherwise leaves *value
1292 // unchanged and returns false.
1293 bool ParseInt32(const Message
& src_text
, const char* str
, int32_t* value
) {
1294 // Parses the environment variable as a decimal integer.
1295 char* end
= nullptr;
1296 const long long_value
= strtol(str
, &end
, 10); // NOLINT
1298 // Has strtol() consumed all characters in the string?
1300 // No - an invalid character was encountered.
1302 msg
<< "WARNING: " << src_text
1303 << " is expected to be a 32-bit integer, but actually"
1304 << " has value \"" << str
<< "\".\n";
1305 printf("%s", msg
.GetString().c_str());
1310 // Is the parsed value in the range of an int32_t?
1311 const auto result
= static_cast<int32_t>(long_value
);
1312 if (long_value
== LONG_MAX
|| long_value
== LONG_MIN
||
1313 // The parsed value overflows as a long. (strtol() returns
1314 // LONG_MAX or LONG_MIN when the input overflows.)
1315 result
!= long_value
1316 // The parsed value overflows as an int32_t.
1319 msg
<< "WARNING: " << src_text
1320 << " is expected to be a 32-bit integer, but actually"
1321 << " has value " << str
<< ", which overflows.\n";
1322 printf("%s", msg
.GetString().c_str());
1331 // Reads and returns the Boolean environment variable corresponding to
1332 // the given flag; if it's not set, returns default_value.
1334 // The value is considered true if and only if it's not "0".
1335 bool BoolFromGTestEnv(const char* flag
, bool default_value
) {
1336 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1337 return GTEST_GET_BOOL_FROM_ENV_(flag
, default_value
);
1339 const std::string env_var
= FlagToEnvVar(flag
);
1340 const char* const string_value
= posix::GetEnv(env_var
.c_str());
1341 return string_value
== nullptr ? default_value
1342 : strcmp(string_value
, "0") != 0;
1343 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1346 // Reads and returns a 32-bit integer stored in the environment
1347 // variable corresponding to the given flag; if it isn't set or
1348 // doesn't represent a valid 32-bit integer, returns default_value.
1349 int32_t Int32FromGTestEnv(const char* flag
, int32_t default_value
) {
1350 #if defined(GTEST_GET_INT32_FROM_ENV_)
1351 return GTEST_GET_INT32_FROM_ENV_(flag
, default_value
);
1353 const std::string env_var
= FlagToEnvVar(flag
);
1354 const char* const string_value
= posix::GetEnv(env_var
.c_str());
1355 if (string_value
== nullptr) {
1356 // The environment variable is not set.
1357 return default_value
;
1360 int32_t result
= default_value
;
1361 if (!ParseInt32(Message() << "Environment variable " << env_var
,
1362 string_value
, &result
)) {
1363 printf("The default value %s is used.\n",
1364 (Message() << default_value
).GetString().c_str());
1366 return default_value
;
1370 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1373 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
1374 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
1375 // system. The value of XML_OUTPUT_FILE is a filename without the
1376 // "xml:" prefix of GTEST_OUTPUT.
1377 // Note that this is meant to be called at the call site so it does
1378 // not check that the flag is 'output'
1379 // In essence this checks an env variable called XML_OUTPUT_FILE
1380 // and if it is set we prepend "xml:" to its value, if it not set we return ""
1381 std::string
OutputFlagAlsoCheckEnvVar(){
1382 std::string default_value_for_output_flag
= "";
1383 const char* xml_output_file_env
= posix::GetEnv("XML_OUTPUT_FILE");
1384 if (nullptr != xml_output_file_env
) {
1385 default_value_for_output_flag
= std::string("xml:") + xml_output_file_env
;
1387 return default_value_for_output_flag
;
1390 // Reads and returns the string environment variable corresponding to
1391 // the given flag; if it's not set, returns default_value.
1392 const char* StringFromGTestEnv(const char* flag
, const char* default_value
) {
1393 #if defined(GTEST_GET_STRING_FROM_ENV_)
1394 return GTEST_GET_STRING_FROM_ENV_(flag
, default_value
);
1396 const std::string env_var
= FlagToEnvVar(flag
);
1397 const char* const value
= posix::GetEnv(env_var
.c_str());
1398 return value
== nullptr ? default_value
: value
;
1399 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
1402 } // namespace internal
1403 } // namespace testing