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.
30 // Author: wan@google.com (Zhanyong Wan)
32 #include "gtest/internal/gtest-port.h"
43 # include <sys/stat.h>
44 # include <map> // Used in ThreadLocal.
47 #endif // GTEST_OS_WINDOWS
50 # include <mach/mach_init.h>
51 # include <mach/task.h>
52 # include <mach/vm_map.h>
53 #endif // GTEST_OS_MAC
58 # include <sys/procfs.h>
59 #endif // GTEST_OS_QNX
62 # include <procinfo.h>
63 # include <sys/types.h>
64 #endif // GTEST_OS_AIX
67 # include <zircon/process.h>
68 # include <zircon/syscalls.h>
69 #endif // GTEST_OS_FUCHSIA
71 #include "gtest/gtest-spi.h"
72 #include "gtest/gtest-message.h"
73 #include "gtest/internal/gtest-internal.h"
74 #include "gtest/internal/gtest-string.h"
75 #include "src/gtest-internal-inl.h"
80 #if defined(_MSC_VER) || defined(__BORLANDC__)
81 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
82 const int kStdOutFileno
= 1;
83 const int kStdErrFileno
= 2;
85 const int kStdOutFileno
= STDOUT_FILENO
;
86 const int kStdErrFileno
= STDERR_FILENO
;
93 T
ReadProcFileField(const std::string
& filename
, int field
) {
95 std::ifstream
file(filename
.c_str());
105 // Returns the number of active threads, or 0 when there is an error.
106 size_t GetThreadCount() {
107 const std::string filename
=
108 (Message() << "/proc/" << getpid() << "/stat").GetString();
109 return ReadProcFileField
<int>(filename
, 19);
114 size_t GetThreadCount() {
115 const task_t task
= mach_task_self();
116 mach_msg_type_number_t thread_count
;
117 thread_act_array_t thread_list
;
118 const kern_return_t status
= task_threads(task
, &thread_list
, &thread_count
);
119 if (status
== KERN_SUCCESS
) {
120 // task_threads allocates resources in thread_list and we need to free them
123 reinterpret_cast<vm_address_t
>(thread_list
),
124 sizeof(thread_t
) * thread_count
);
125 return static_cast<size_t>(thread_count
);
133 // Returns the number of threads running in the process, or 0 to indicate that
134 // we cannot detect it.
135 size_t GetThreadCount() {
136 const int fd
= open("/proc/self/as", O_RDONLY
);
140 procfs_info process_info
;
142 devctl(fd
, DCMD_PROC_INFO
, &process_info
, sizeof(process_info
), NULL
);
145 return static_cast<size_t>(process_info
.num_threads
);
153 size_t GetThreadCount() {
154 struct procentry64 entry
;
155 pid_t pid
= getpid();
156 int status
= getprocs64(&entry
, sizeof(entry
), NULL
, 0, &pid
, 1);
158 return entry
.pi_thcount
;
164 #elif GTEST_OS_FUCHSIA
166 size_t GetThreadCount() {
169 zx_status_t status
= zx_object_get_info(
171 ZX_INFO_PROCESS_THREADS
,
176 if (status
== ZX_OK
) {
185 size_t GetThreadCount() {
186 // There's no portable way to detect the number of threads, so we just
187 // return 0 to indicate that we cannot detect it.
191 #endif // GTEST_OS_LINUX
193 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
195 void SleepMilliseconds(int n
) {
199 AutoHandle::AutoHandle()
200 : handle_(INVALID_HANDLE_VALUE
) {}
202 AutoHandle::AutoHandle(Handle handle
)
205 AutoHandle::~AutoHandle() {
209 AutoHandle::Handle
AutoHandle::Get() const {
213 void AutoHandle::Reset() {
214 Reset(INVALID_HANDLE_VALUE
);
217 void AutoHandle::Reset(HANDLE handle
) {
218 // Resetting with the same handle we already own is invalid.
219 if (handle_
!= handle
) {
221 ::CloseHandle(handle_
);
225 GTEST_CHECK_(!IsCloseable())
226 << "Resetting a valid handle to itself is likely a programmer error "
227 "and thus not allowed.";
231 bool AutoHandle::IsCloseable() const {
232 // Different Windows APIs may use either of these values to represent an
234 return handle_
!= NULL
&& handle_
!= INVALID_HANDLE_VALUE
;
237 Notification::Notification()
238 : event_(::CreateEvent(NULL
, // Default security attributes.
239 TRUE
, // Do not reset automatically.
240 FALSE
, // Initially unset.
241 NULL
)) { // Anonymous event.
242 GTEST_CHECK_(event_
.Get() != NULL
);
245 void Notification::Notify() {
246 GTEST_CHECK_(::SetEvent(event_
.Get()) != FALSE
);
249 void Notification::WaitForNotification() {
251 ::WaitForSingleObject(event_
.Get(), INFINITE
) == WAIT_OBJECT_0
);
255 : owner_thread_id_(0),
257 critical_section_init_phase_(0),
258 critical_section_(new CRITICAL_SECTION
) {
259 ::InitializeCriticalSection(critical_section_
);
263 // Static mutexes are leaked intentionally. It is not thread-safe to try
265 // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
266 // nothing to clean it up but is available only on Vista and later.
267 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
268 if (type_
== kDynamic
) {
269 ::DeleteCriticalSection(critical_section_
);
270 delete critical_section_
;
271 critical_section_
= NULL
;
276 ThreadSafeLazyInit();
277 ::EnterCriticalSection(critical_section_
);
278 owner_thread_id_
= ::GetCurrentThreadId();
281 void Mutex::Unlock() {
282 ThreadSafeLazyInit();
283 // We don't protect writing to owner_thread_id_ here, as it's the
284 // caller's responsibility to ensure that the current thread holds the
285 // mutex when this is called.
286 owner_thread_id_
= 0;
287 ::LeaveCriticalSection(critical_section_
);
290 // Does nothing if the current thread holds the mutex. Otherwise, crashes
291 // with high probability.
292 void Mutex::AssertHeld() {
293 ThreadSafeLazyInit();
294 GTEST_CHECK_(owner_thread_id_
== ::GetCurrentThreadId())
295 << "The current thread is not holding the mutex @" << this;
298 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
299 void Mutex::ThreadSafeLazyInit() {
300 // Dynamic mutexes are initialized in the constructor.
301 if (type_
== kStatic
) {
303 ::InterlockedCompareExchange(&critical_section_init_phase_
, 1L, 0L)) {
305 // If critical_section_init_phase_ was 0 before the exchange, we
306 // are the first to test it and need to perform the initialization.
307 owner_thread_id_
= 0;
308 critical_section_
= new CRITICAL_SECTION
;
309 ::InitializeCriticalSection(critical_section_
);
310 // Updates the critical_section_init_phase_ to 2 to signal
311 // initialization complete.
312 GTEST_CHECK_(::InterlockedCompareExchange(
313 &critical_section_init_phase_
, 2L, 1L) ==
317 // Somebody else is already initializing the mutex; spin until they
319 while (::InterlockedCompareExchange(&critical_section_init_phase_
,
322 // Possibly yields the rest of the thread's time slice to other
329 break; // The mutex is already initialized and ready for use.
333 << "Unexpected value of critical_section_init_phase_ "
334 << "while initializing a static mutex.";
341 class ThreadWithParamSupport
: public ThreadWithParamBase
{
343 static HANDLE
CreateThread(Runnable
* runnable
,
344 Notification
* thread_can_start
) {
345 ThreadMainParam
* param
= new ThreadMainParam(runnable
, thread_can_start
);
347 // TODO(yukawa): Consider to use _beginthreadex instead.
348 HANDLE thread_handle
= ::CreateThread(
349 NULL
, // Default security.
350 0, // Default stack size.
351 &ThreadWithParamSupport::ThreadMain
,
352 param
, // Parameter to ThreadMainStatic
353 0x0, // Default creation flags.
354 &thread_id
); // Need a valid pointer for the call to work under Win98.
355 GTEST_CHECK_(thread_handle
!= NULL
) << "CreateThread failed with error "
356 << ::GetLastError() << ".";
357 if (thread_handle
== NULL
) {
360 return thread_handle
;
364 struct ThreadMainParam
{
365 ThreadMainParam(Runnable
* runnable
, Notification
* thread_can_start
)
366 : runnable_(runnable
),
367 thread_can_start_(thread_can_start
) {
369 scoped_ptr
<Runnable
> runnable_
;
371 Notification
* thread_can_start_
;
374 static DWORD WINAPI
ThreadMain(void* ptr
) {
375 // Transfers ownership.
376 scoped_ptr
<ThreadMainParam
> param(static_cast<ThreadMainParam
*>(ptr
));
377 if (param
->thread_can_start_
!= NULL
)
378 param
->thread_can_start_
->WaitForNotification();
379 param
->runnable_
->Run();
383 // Prohibit instantiation.
384 ThreadWithParamSupport();
386 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport
);
391 ThreadWithParamBase::ThreadWithParamBase(Runnable
*runnable
,
392 Notification
* thread_can_start
)
393 : thread_(ThreadWithParamSupport::CreateThread(runnable
,
397 ThreadWithParamBase::~ThreadWithParamBase() {
401 void ThreadWithParamBase::Join() {
402 GTEST_CHECK_(::WaitForSingleObject(thread_
.Get(), INFINITE
) == WAIT_OBJECT_0
)
403 << "Failed to join the thread with error " << ::GetLastError() << ".";
406 // Maps a thread to a set of ThreadIdToThreadLocals that have values
407 // instantiated on that thread and notifies them when the thread exits. A
408 // ThreadLocal instance is expected to persist until all threads it has
409 // values on have terminated.
410 class ThreadLocalRegistryImpl
{
412 // Registers thread_local_instance as having value on the current thread.
413 // Returns a value that can be used to identify the thread from other threads.
414 static ThreadLocalValueHolderBase
* GetValueOnCurrentThread(
415 const ThreadLocalBase
* thread_local_instance
) {
416 DWORD current_thread
= ::GetCurrentThreadId();
417 MutexLock
lock(&mutex_
);
418 ThreadIdToThreadLocals
* const thread_to_thread_locals
=
419 GetThreadLocalsMapLocked();
420 ThreadIdToThreadLocals::iterator thread_local_pos
=
421 thread_to_thread_locals
->find(current_thread
);
422 if (thread_local_pos
== thread_to_thread_locals
->end()) {
423 thread_local_pos
= thread_to_thread_locals
->insert(
424 std::make_pair(current_thread
, ThreadLocalValues())).first
;
425 StartWatcherThreadFor(current_thread
);
427 ThreadLocalValues
& thread_local_values
= thread_local_pos
->second
;
428 ThreadLocalValues::iterator value_pos
=
429 thread_local_values
.find(thread_local_instance
);
430 if (value_pos
== thread_local_values
.end()) {
433 .insert(std::make_pair(
434 thread_local_instance
,
435 linked_ptr
<ThreadLocalValueHolderBase
>(
436 thread_local_instance
->NewValueForCurrentThread())))
439 return value_pos
->second
.get();
442 static void OnThreadLocalDestroyed(
443 const ThreadLocalBase
* thread_local_instance
) {
444 std::vector
<linked_ptr
<ThreadLocalValueHolderBase
> > value_holders
;
445 // Clean up the ThreadLocalValues data structure while holding the lock, but
446 // defer the destruction of the ThreadLocalValueHolderBases.
448 MutexLock
lock(&mutex_
);
449 ThreadIdToThreadLocals
* const thread_to_thread_locals
=
450 GetThreadLocalsMapLocked();
451 for (ThreadIdToThreadLocals::iterator it
=
452 thread_to_thread_locals
->begin();
453 it
!= thread_to_thread_locals
->end();
455 ThreadLocalValues
& thread_local_values
= it
->second
;
456 ThreadLocalValues::iterator value_pos
=
457 thread_local_values
.find(thread_local_instance
);
458 if (value_pos
!= thread_local_values
.end()) {
459 value_holders
.push_back(value_pos
->second
);
460 thread_local_values
.erase(value_pos
);
461 // This 'if' can only be successful at most once, so theoretically we
462 // could break out of the loop here, but we don't bother doing so.
466 // Outside the lock, let the destructor for 'value_holders' deallocate the
467 // ThreadLocalValueHolderBases.
470 static void OnThreadExit(DWORD thread_id
) {
471 GTEST_CHECK_(thread_id
!= 0) << ::GetLastError();
472 std::vector
<linked_ptr
<ThreadLocalValueHolderBase
> > value_holders
;
473 // Clean up the ThreadIdToThreadLocals data structure while holding the
474 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
476 MutexLock
lock(&mutex_
);
477 ThreadIdToThreadLocals
* const thread_to_thread_locals
=
478 GetThreadLocalsMapLocked();
479 ThreadIdToThreadLocals::iterator thread_local_pos
=
480 thread_to_thread_locals
->find(thread_id
);
481 if (thread_local_pos
!= thread_to_thread_locals
->end()) {
482 ThreadLocalValues
& thread_local_values
= thread_local_pos
->second
;
483 for (ThreadLocalValues::iterator value_pos
=
484 thread_local_values
.begin();
485 value_pos
!= thread_local_values
.end();
487 value_holders
.push_back(value_pos
->second
);
489 thread_to_thread_locals
->erase(thread_local_pos
);
492 // Outside the lock, let the destructor for 'value_holders' deallocate the
493 // ThreadLocalValueHolderBases.
497 // In a particular thread, maps a ThreadLocal object to its value.
498 typedef std::map
<const ThreadLocalBase
*,
499 linked_ptr
<ThreadLocalValueHolderBase
> > ThreadLocalValues
;
500 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
502 typedef std::map
<DWORD
, ThreadLocalValues
> ThreadIdToThreadLocals
;
504 // Holds the thread id and thread handle that we pass from
505 // StartWatcherThreadFor to WatcherThreadFunc.
506 typedef std::pair
<DWORD
, HANDLE
> ThreadIdAndHandle
;
508 static void StartWatcherThreadFor(DWORD thread_id
) {
509 // The returned handle will be kept in thread_map and closed by
510 // watcher_thread in WatcherThreadFunc.
511 HANDLE thread
= ::OpenThread(SYNCHRONIZE
| THREAD_QUERY_INFORMATION
,
514 GTEST_CHECK_(thread
!= NULL
);
515 // We need to pass a valid thread ID pointer into CreateThread for it
516 // to work correctly under Win98.
517 DWORD watcher_thread_id
;
518 HANDLE watcher_thread
= ::CreateThread(
519 NULL
, // Default security.
520 0, // Default stack size
521 &ThreadLocalRegistryImpl::WatcherThreadFunc
,
522 reinterpret_cast<LPVOID
>(new ThreadIdAndHandle(thread_id
, thread
)),
525 GTEST_CHECK_(watcher_thread
!= NULL
);
526 // Give the watcher thread the same priority as ours to avoid being
528 ::SetThreadPriority(watcher_thread
,
529 ::GetThreadPriority(::GetCurrentThread()));
530 ::ResumeThread(watcher_thread
);
531 ::CloseHandle(watcher_thread
);
534 // Monitors exit from a given thread and notifies those
535 // ThreadIdToThreadLocals about thread termination.
536 static DWORD WINAPI
WatcherThreadFunc(LPVOID param
) {
537 const ThreadIdAndHandle
* tah
=
538 reinterpret_cast<const ThreadIdAndHandle
*>(param
);
540 ::WaitForSingleObject(tah
->second
, INFINITE
) == WAIT_OBJECT_0
);
541 OnThreadExit(tah
->first
);
542 ::CloseHandle(tah
->second
);
547 // Returns map of thread local instances.
548 static ThreadIdToThreadLocals
* GetThreadLocalsMapLocked() {
550 static ThreadIdToThreadLocals
* map
= new ThreadIdToThreadLocals
;
554 // Protects access to GetThreadLocalsMapLocked() and its return value.
556 // Protects access to GetThreadMapLocked() and its return value.
557 static Mutex thread_map_mutex_
;
560 Mutex
ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex
);
561 Mutex
ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex
);
563 ThreadLocalValueHolderBase
* ThreadLocalRegistry::GetValueOnCurrentThread(
564 const ThreadLocalBase
* thread_local_instance
) {
565 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
566 thread_local_instance
);
569 void ThreadLocalRegistry::OnThreadLocalDestroyed(
570 const ThreadLocalBase
* thread_local_instance
) {
571 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance
);
574 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
576 #if GTEST_USES_POSIX_RE
578 // Implements RE. Currently only needed for death tests.
582 // regfree'ing an invalid regex might crash because the content
583 // of the regex is undefined. Since the regex's are essentially
584 // the same, one cannot be valid (or invalid) without the other
586 regfree(&partial_regex_
);
587 regfree(&full_regex_
);
589 free(const_cast<char*>(pattern_
));
592 // Returns true iff regular expression re matches the entire str.
593 bool RE::FullMatch(const char* str
, const RE
& re
) {
594 if (!re
.is_valid_
) return false;
597 return regexec(&re
.full_regex_
, str
, 1, &match
, 0) == 0;
600 // Returns true iff regular expression re matches a substring of str
601 // (including str itself).
602 bool RE::PartialMatch(const char* str
, const RE
& re
) {
603 if (!re
.is_valid_
) return false;
606 return regexec(&re
.partial_regex_
, str
, 1, &match
, 0) == 0;
609 // Initializes an RE from its string representation.
610 void RE::Init(const char* regex
) {
611 pattern_
= posix::StrDup(regex
);
613 // Reserves enough bytes to hold the regular expression used for a
615 const size_t full_regex_len
= strlen(regex
) + 10;
616 char* const full_pattern
= new char[full_regex_len
];
618 snprintf(full_pattern
, full_regex_len
, "^(%s)$", regex
);
619 is_valid_
= regcomp(&full_regex_
, full_pattern
, REG_EXTENDED
) == 0;
620 // We want to call regcomp(&partial_regex_, ...) even if the
621 // previous expression returns false. Otherwise partial_regex_ may
622 // not be properly initialized can may cause trouble when it's
625 // Some implementation of POSIX regex (e.g. on at least some
626 // versions of Cygwin) doesn't accept the empty string as a valid
627 // regex. We change it to an equivalent form "()" to be safe.
629 const char* const partial_regex
= (*regex
== '\0') ? "()" : regex
;
630 is_valid_
= regcomp(&partial_regex_
, partial_regex
, REG_EXTENDED
) == 0;
632 EXPECT_TRUE(is_valid_
)
633 << "Regular expression \"" << regex
634 << "\" is not a valid POSIX Extended regular expression.";
636 delete[] full_pattern
;
639 #elif GTEST_USES_SIMPLE_RE
641 // Returns true iff ch appears anywhere in str (excluding the
642 // terminating '\0' character).
643 bool IsInSet(char ch
, const char* str
) {
644 return ch
!= '\0' && strchr(str
, ch
) != NULL
;
647 // Returns true iff ch belongs to the given classification. Unlike
648 // similar functions in <ctype.h>, these aren't affected by the
650 bool IsAsciiDigit(char ch
) { return '0' <= ch
&& ch
<= '9'; }
651 bool IsAsciiPunct(char ch
) {
652 return IsInSet(ch
, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
654 bool IsRepeat(char ch
) { return IsInSet(ch
, "?*+"); }
655 bool IsAsciiWhiteSpace(char ch
) { return IsInSet(ch
, " \f\n\r\t\v"); }
656 bool IsAsciiWordChar(char ch
) {
657 return ('a' <= ch
&& ch
<= 'z') || ('A' <= ch
&& ch
<= 'Z') ||
658 ('0' <= ch
&& ch
<= '9') || ch
== '_';
661 // Returns true iff "\\c" is a supported escape sequence.
662 bool IsValidEscape(char c
) {
663 return (IsAsciiPunct(c
) || IsInSet(c
, "dDfnrsStvwW"));
666 // Returns true iff the given atom (specified by escaped and pattern)
667 // matches ch. The result is undefined if the atom is invalid.
668 bool AtomMatchesChar(bool escaped
, char pattern_char
, char ch
) {
669 if (escaped
) { // "\\p" where p is pattern_char.
670 switch (pattern_char
) {
671 case 'd': return IsAsciiDigit(ch
);
672 case 'D': return !IsAsciiDigit(ch
);
673 case 'f': return ch
== '\f';
674 case 'n': return ch
== '\n';
675 case 'r': return ch
== '\r';
676 case 's': return IsAsciiWhiteSpace(ch
);
677 case 'S': return !IsAsciiWhiteSpace(ch
);
678 case 't': return ch
== '\t';
679 case 'v': return ch
== '\v';
680 case 'w': return IsAsciiWordChar(ch
);
681 case 'W': return !IsAsciiWordChar(ch
);
683 return IsAsciiPunct(pattern_char
) && pattern_char
== ch
;
686 return (pattern_char
== '.' && ch
!= '\n') || pattern_char
== ch
;
689 // Helper function used by ValidateRegex() to format error messages.
690 static std::string
FormatRegexSyntaxError(const char* regex
, int index
) {
691 return (Message() << "Syntax error at index " << index
692 << " in simple regular expression \"" << regex
<< "\": ").GetString();
695 // Generates non-fatal failures and returns false if regex is invalid;
696 // otherwise returns true.
697 bool ValidateRegex(const char* regex
) {
699 // TODO(wan@google.com): fix the source file location in the
700 // assertion failures to match where the regex is used in user
702 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
706 bool is_valid
= true;
708 // True iff ?, *, or + can follow the previous atom.
709 bool prev_repeatable
= false;
710 for (int i
= 0; regex
[i
]; i
++) {
711 if (regex
[i
] == '\\') { // An escape sequence
713 if (regex
[i
] == '\0') {
714 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
715 << "'\\' cannot appear at the end.";
719 if (!IsValidEscape(regex
[i
])) {
720 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
721 << "invalid escape sequence \"\\" << regex
[i
] << "\".";
724 prev_repeatable
= true;
725 } else { // Not an escape sequence.
726 const char ch
= regex
[i
];
728 if (ch
== '^' && i
> 0) {
729 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
730 << "'^' can only appear at the beginning.";
732 } else if (ch
== '$' && regex
[i
+ 1] != '\0') {
733 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
734 << "'$' can only appear at the end.";
736 } else if (IsInSet(ch
, "()[]{}|")) {
737 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
738 << "'" << ch
<< "' is unsupported.";
740 } else if (IsRepeat(ch
) && !prev_repeatable
) {
741 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
742 << "'" << ch
<< "' can only follow a repeatable token.";
746 prev_repeatable
= !IsInSet(ch
, "^$?*+");
753 // Matches a repeated regex atom followed by a valid simple regular
754 // expression. The regex atom is defined as c if escaped is false,
755 // or \c otherwise. repeat is the repetition meta character (?, *,
756 // or +). The behavior is undefined if str contains too many
757 // characters to be indexable by size_t, in which case the test will
758 // probably time out anyway. We are fine with this limitation as
759 // std::string has it too.
760 bool MatchRepetitionAndRegexAtHead(
761 bool escaped
, char c
, char repeat
, const char* regex
,
763 const size_t min_count
= (repeat
== '+') ? 1 : 0;
764 const size_t max_count
= (repeat
== '?') ? 1 :
765 static_cast<size_t>(-1) - 1;
766 // We cannot call numeric_limits::max() as it conflicts with the
767 // max() macro on Windows.
769 for (size_t i
= 0; i
<= max_count
; ++i
) {
770 // We know that the atom matches each of the first i characters in str.
771 if (i
>= min_count
&& MatchRegexAtHead(regex
, str
+ i
)) {
772 // We have enough matches at the head, and the tail matches too.
773 // Since we only care about *whether* the pattern matches str
774 // (as opposed to *how* it matches), there is no need to find a
778 if (str
[i
] == '\0' || !AtomMatchesChar(escaped
, c
, str
[i
]))
784 // Returns true iff regex matches a prefix of str. regex must be a
785 // valid simple regular expression and not start with "^", or the
786 // result is undefined.
787 bool MatchRegexAtHead(const char* regex
, const char* str
) {
788 if (*regex
== '\0') // An empty regex matches a prefix of anything.
791 // "$" only matches the end of a string. Note that regex being
792 // valid guarantees that there's nothing after "$" in it.
796 // Is the first thing in regex an escape sequence?
797 const bool escaped
= *regex
== '\\';
800 if (IsRepeat(regex
[1])) {
801 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
802 // here's an indirect recursion. It terminates as the regex gets
803 // shorter in each recursion.
804 return MatchRepetitionAndRegexAtHead(
805 escaped
, regex
[0], regex
[1], regex
+ 2, str
);
807 // regex isn't empty, isn't "$", and doesn't start with a
808 // repetition. We match the first atom of regex with the first
809 // character of str and recurse.
810 return (*str
!= '\0') && AtomMatchesChar(escaped
, *regex
, *str
) &&
811 MatchRegexAtHead(regex
+ 1, str
+ 1);
815 // Returns true iff regex matches any substring of str. regex must be
816 // a valid simple regular expression, or the result is undefined.
818 // The algorithm is recursive, but the recursion depth doesn't exceed
819 // the regex length, so we won't need to worry about running out of
820 // stack space normally. In rare cases the time complexity can be
821 // exponential with respect to the regex length + the string length,
822 // but usually it's must faster (often close to linear).
823 bool MatchRegexAnywhere(const char* regex
, const char* str
) {
824 if (regex
== NULL
|| str
== NULL
)
828 return MatchRegexAtHead(regex
+ 1, str
);
830 // A successful match can be anywhere in str.
832 if (MatchRegexAtHead(regex
, str
))
834 } while (*str
++ != '\0');
838 // Implements the RE class.
841 free(const_cast<char*>(pattern_
));
842 free(const_cast<char*>(full_pattern_
));
845 // Returns true iff regular expression re matches the entire str.
846 bool RE::FullMatch(const char* str
, const RE
& re
) {
847 return re
.is_valid_
&& MatchRegexAnywhere(re
.full_pattern_
, str
);
850 // Returns true iff regular expression re matches a substring of str
851 // (including str itself).
852 bool RE::PartialMatch(const char* str
, const RE
& re
) {
853 return re
.is_valid_
&& MatchRegexAnywhere(re
.pattern_
, str
);
856 // Initializes an RE from its string representation.
857 void RE::Init(const char* regex
) {
858 pattern_
= full_pattern_
= NULL
;
860 pattern_
= posix::StrDup(regex
);
863 is_valid_
= ValidateRegex(regex
);
865 // No need to calculate the full pattern when the regex is invalid.
869 const size_t len
= strlen(regex
);
870 // Reserves enough bytes to hold the regular expression used for a
871 // full match: we need space to prepend a '^', append a '$', and
872 // terminate the string with '\0'.
873 char* buffer
= static_cast<char*>(malloc(len
+ 3));
874 full_pattern_
= buffer
;
877 *buffer
++ = '^'; // Makes sure full_pattern_ starts with '^'.
879 // We don't use snprintf or strncpy, as they trigger a warning when
880 // compiled with VC++ 8.0.
881 memcpy(buffer
, regex
, len
);
884 if (len
== 0 || regex
[len
- 1] != '$')
885 *buffer
++ = '$'; // Makes sure full_pattern_ ends with '$'.
890 #endif // GTEST_USES_POSIX_RE
892 const char kUnknownFile
[] = "unknown file";
894 // Formats a source file path and a line number as they would appear
895 // in an error message from the compiler used to compile this code.
896 GTEST_API_ ::std::string
FormatFileLocation(const char* file
, int line
) {
897 const std::string
file_name(file
== NULL
? kUnknownFile
: file
);
900 return file_name
+ ":";
903 return file_name
+ "(" + StreamableToString(line
) + "):";
905 return file_name
+ ":" + StreamableToString(line
) + ":";
909 // Formats a file location for compiler-independent XML output.
910 // Although this function is not platform dependent, we put it next to
911 // FormatFileLocation in order to contrast the two functions.
912 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
913 // to the file location it produces, unlike FormatFileLocation().
914 GTEST_API_ ::std::string
FormatCompilerIndependentFileLocation(
915 const char* file
, int line
) {
916 const std::string
file_name(file
== NULL
? kUnknownFile
: file
);
921 return file_name
+ ":" + StreamableToString(line
);
924 GTestLog::GTestLog(GTestLogSeverity severity
, const char* file
, int line
)
925 : severity_(severity
) {
926 const char* const marker
=
927 severity
== GTEST_INFO
? "[ INFO ]" :
928 severity
== GTEST_WARNING
? "[WARNING]" :
929 severity
== GTEST_ERROR
? "[ ERROR ]" : "[ FATAL ]";
930 GetStream() << ::std::endl
<< marker
<< " "
931 << FormatFileLocation(file
, line
).c_str() << ": ";
934 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
935 GTestLog::~GTestLog() {
936 GetStream() << ::std::endl
;
937 if (severity_
== GTEST_FATAL
) {
943 // Disable Microsoft deprecation warnings for POSIX functions called from
944 // this class (creat, dup, dup2, and close)
945 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
947 #if GTEST_HAS_STREAM_REDIRECTION
949 // Object that captures an output stream (stdout/stderr).
950 class CapturedStream
{
952 // The ctor redirects the stream to a temporary file.
953 explicit CapturedStream(int fd
) : fd_(fd
), uncaptured_fd_(dup(fd
)) {
954 # if GTEST_OS_WINDOWS
955 char temp_dir_path
[MAX_PATH
+ 1] = { '\0' }; // NOLINT
956 char temp_file_path
[MAX_PATH
+ 1] = { '\0' }; // NOLINT
958 ::GetTempPathA(sizeof(temp_dir_path
), temp_dir_path
);
959 const UINT success
= ::GetTempFileNameA(temp_dir_path
,
961 0, // Generate unique file name.
963 GTEST_CHECK_(success
!= 0)
964 << "Unable to create a temporary file in " << temp_dir_path
;
965 const int captured_fd
= creat(temp_file_path
, _S_IREAD
| _S_IWRITE
);
966 GTEST_CHECK_(captured_fd
!= -1) << "Unable to open temporary file "
968 filename_
= temp_file_path
;
970 // There's no guarantee that a test has write access to the current
971 // directory, so we create the temporary file in the /tmp directory
972 // instead. We use /tmp on most systems, and /sdcard on Android.
973 // That's because Android doesn't have /tmp.
974 # if GTEST_OS_LINUX_ANDROID
975 // Note: Android applications are expected to call the framework's
976 // Context.getExternalStorageDirectory() method through JNI to get
977 // the location of the world-writable SD Card directory. However,
978 // this requires a Context handle, which cannot be retrieved
979 // globally from native code. Doing so also precludes running the
980 // code as part of a regular standalone executable, which doesn't
981 // run in a Dalvik process (e.g. when running it through 'adb shell').
983 // The location /sdcard is directly accessible from native code
984 // and is the only location (unofficially) supported by the Android
985 // team. It's generally a symlink to the real SD Card mount point
986 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
987 // other OEM-customized locations. Never rely on these, and always
989 char name_template
[] = "/sdcard/gtest_captured_stream.XXXXXX";
991 char name_template
[] = "/tmp/captured_stream.XXXXXX";
992 # endif // GTEST_OS_LINUX_ANDROID
993 const int captured_fd
= mkstemp(name_template
);
994 filename_
= name_template
;
995 # endif // GTEST_OS_WINDOWS
997 dup2(captured_fd
, fd_
);
1002 remove(filename_
.c_str());
1005 std::string
GetCapturedString() {
1006 if (uncaptured_fd_
!= -1) {
1007 // Restores the original stream.
1009 dup2(uncaptured_fd_
, fd_
);
1010 close(uncaptured_fd_
);
1011 uncaptured_fd_
= -1;
1014 FILE* const file
= posix::FOpen(filename_
.c_str(), "r");
1015 const std::string content
= ReadEntireFile(file
);
1016 posix::FClose(file
);
1021 const int fd_
; // A stream to capture.
1023 // Name of the temporary file holding the stderr output.
1024 ::std::string filename_
;
1026 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream
);
1029 GTEST_DISABLE_MSC_WARNINGS_POP_()
1031 static CapturedStream
* g_captured_stderr
= NULL
;
1032 static CapturedStream
* g_captured_stdout
= NULL
;
1034 // Starts capturing an output stream (stdout/stderr).
1035 static void CaptureStream(int fd
, const char* stream_name
,
1036 CapturedStream
** stream
) {
1037 if (*stream
!= NULL
) {
1038 GTEST_LOG_(FATAL
) << "Only one " << stream_name
1039 << " capturer can exist at a time.";
1041 *stream
= new CapturedStream(fd
);
1044 // Stops capturing the output stream and returns the captured string.
1045 static std::string
GetCapturedStream(CapturedStream
** captured_stream
) {
1046 const std::string content
= (*captured_stream
)->GetCapturedString();
1048 delete *captured_stream
;
1049 *captured_stream
= NULL
;
1054 // Starts capturing stdout.
1055 void CaptureStdout() {
1056 CaptureStream(kStdOutFileno
, "stdout", &g_captured_stdout
);
1059 // Starts capturing stderr.
1060 void CaptureStderr() {
1061 CaptureStream(kStdErrFileno
, "stderr", &g_captured_stderr
);
1064 // Stops capturing stdout and returns the captured string.
1065 std::string
GetCapturedStdout() {
1066 return GetCapturedStream(&g_captured_stdout
);
1069 // Stops capturing stderr and returns the captured string.
1070 std::string
GetCapturedStderr() {
1071 return GetCapturedStream(&g_captured_stderr
);
1074 #endif // GTEST_HAS_STREAM_REDIRECTION
1080 size_t GetFileSize(FILE* file
) {
1081 fseek(file
, 0, SEEK_END
);
1082 return static_cast<size_t>(ftell(file
));
1085 std::string
ReadEntireFile(FILE* file
) {
1086 const size_t file_size
= GetFileSize(file
);
1087 char* const buffer
= new char[file_size
];
1089 size_t bytes_last_read
= 0; // # of bytes read in the last fread()
1090 size_t bytes_read
= 0; // # of bytes read so far
1092 fseek(file
, 0, SEEK_SET
);
1094 // Keeps reading the file until we cannot read further or the
1095 // pre-determined file size is reached.
1097 bytes_last_read
= fread(buffer
+bytes_read
, 1, file_size
-bytes_read
, file
);
1098 bytes_read
+= bytes_last_read
;
1099 } while (bytes_last_read
> 0 && bytes_read
< file_size
);
1101 const std::string
content(buffer
, bytes_read
);
1107 #if GTEST_HAS_DEATH_TEST
1108 static const std::vector
<std::string
>* g_injected_test_argvs
= NULL
; // Owned.
1110 std::vector
<std::string
> GetInjectableArgvs() {
1111 if (g_injected_test_argvs
!= NULL
) {
1112 return *g_injected_test_argvs
;
1117 void SetInjectableArgvs(const std::vector
<std::string
>* new_argvs
) {
1118 if (g_injected_test_argvs
!= new_argvs
) delete g_injected_test_argvs
;
1119 g_injected_test_argvs
= new_argvs
;
1122 void SetInjectableArgvs(const std::vector
<std::string
>& new_argvs
) {
1124 new std::vector
<std::string
>(new_argvs
.begin(), new_argvs
.end()));
1127 #if GTEST_HAS_GLOBAL_STRING
1128 void SetInjectableArgvs(const std::vector
< ::string
>& new_argvs
) {
1130 new std::vector
<std::string
>(new_argvs
.begin(), new_argvs
.end()));
1132 #endif // GTEST_HAS_GLOBAL_STRING
1134 void ClearInjectableArgvs() {
1135 delete g_injected_test_argvs
;
1136 g_injected_test_argvs
= NULL
;
1138 #endif // GTEST_HAS_DEATH_TEST
1140 #if GTEST_OS_WINDOWS_MOBILE
1144 TerminateProcess(GetCurrentProcess(), 1);
1146 } // namespace posix
1147 #endif // GTEST_OS_WINDOWS_MOBILE
1149 // Returns the name of the environment variable corresponding to the
1150 // given flag. For example, FlagToEnvVar("foo") will return
1151 // "GTEST_FOO" in the open-source version.
1152 static std::string
FlagToEnvVar(const char* flag
) {
1153 const std::string full_flag
=
1154 (Message() << GTEST_FLAG_PREFIX_
<< flag
).GetString();
1157 for (size_t i
= 0; i
!= full_flag
.length(); i
++) {
1158 env_var
<< ToUpper(full_flag
.c_str()[i
]);
1161 return env_var
.GetString();
1164 // Parses 'str' for a 32-bit signed integer. If successful, writes
1165 // the result to *value and returns true; otherwise leaves *value
1166 // unchanged and returns false.
1167 bool ParseInt32(const Message
& src_text
, const char* str
, Int32
* value
) {
1168 // Parses the environment variable as a decimal integer.
1170 const long long_value
= strtol(str
, &end
, 10); // NOLINT
1172 // Has strtol() consumed all characters in the string?
1174 // No - an invalid character was encountered.
1176 msg
<< "WARNING: " << src_text
1177 << " is expected to be a 32-bit integer, but actually"
1178 << " has value \"" << str
<< "\".\n";
1179 printf("%s", msg
.GetString().c_str());
1184 // Is the parsed value in the range of an Int32?
1185 const Int32 result
= static_cast<Int32
>(long_value
);
1186 if (long_value
== LONG_MAX
|| long_value
== LONG_MIN
||
1187 // The parsed value overflows as a long. (strtol() returns
1188 // LONG_MAX or LONG_MIN when the input overflows.)
1189 result
!= long_value
1190 // The parsed value overflows as an Int32.
1193 msg
<< "WARNING: " << src_text
1194 << " is expected to be a 32-bit integer, but actually"
1195 << " has value " << str
<< ", which overflows.\n";
1196 printf("%s", msg
.GetString().c_str());
1205 // Reads and returns the Boolean environment variable corresponding to
1206 // the given flag; if it's not set, returns default_value.
1208 // The value is considered true iff it's not "0".
1209 bool BoolFromGTestEnv(const char* flag
, bool default_value
) {
1210 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1211 return GTEST_GET_BOOL_FROM_ENV_(flag
, default_value
);
1213 const std::string env_var
= FlagToEnvVar(flag
);
1214 const char* const string_value
= posix::GetEnv(env_var
.c_str());
1215 return string_value
== NULL
?
1216 default_value
: strcmp(string_value
, "0") != 0;
1217 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1220 // Reads and returns a 32-bit integer stored in the environment
1221 // variable corresponding to the given flag; if it isn't set or
1222 // doesn't represent a valid 32-bit integer, returns default_value.
1223 Int32
Int32FromGTestEnv(const char* flag
, Int32 default_value
) {
1224 #if defined(GTEST_GET_INT32_FROM_ENV_)
1225 return GTEST_GET_INT32_FROM_ENV_(flag
, default_value
);
1227 const std::string env_var
= FlagToEnvVar(flag
);
1228 const char* const string_value
= posix::GetEnv(env_var
.c_str());
1229 if (string_value
== NULL
) {
1230 // The environment variable is not set.
1231 return default_value
;
1234 Int32 result
= default_value
;
1235 if (!ParseInt32(Message() << "Environment variable " << env_var
,
1236 string_value
, &result
)) {
1237 printf("The default value %s is used.\n",
1238 (Message() << default_value
).GetString().c_str());
1240 return default_value
;
1244 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1247 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
1248 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
1249 // system. The value of XML_OUTPUT_FILE is a filename without the
1250 // "xml:" prefix of GTEST_OUTPUT.
1251 // Note that this is meant to be called at the call site so it does
1252 // not check that the flag is 'output'
1253 // In essence this checks an env variable called XML_OUTPUT_FILE
1254 // and if it is set we prepend "xml:" to its value, if it not set we return ""
1255 std::string
OutputFlagAlsoCheckEnvVar(){
1256 std::string default_value_for_output_flag
= "";
1257 const char* xml_output_file_env
= posix::GetEnv("XML_OUTPUT_FILE");
1258 if (NULL
!= xml_output_file_env
) {
1259 default_value_for_output_flag
= std::string("xml:") + xml_output_file_env
;
1261 return default_value_for_output_flag
;
1264 // Reads and returns the string environment variable corresponding to
1265 // the given flag; if it's not set, returns default_value.
1266 const char* StringFromGTestEnv(const char* flag
, const char* default_value
) {
1267 #if defined(GTEST_GET_STRING_FROM_ENV_)
1268 return GTEST_GET_STRING_FROM_ENV_(flag
, default_value
);
1270 const std::string env_var
= FlagToEnvVar(flag
);
1271 const char* const value
= posix::GetEnv(env_var
.c_str());
1272 return value
== NULL
? default_value
: value
;
1273 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
1276 } // namespace internal
1277 } // namespace testing