43 # include <sys/stat.h>
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
76 #define GTEST_IMPLEMENTATION_ 1
78 #undef GTEST_IMPLEMENTATION_
83 #if defined(_MSC_VER) || defined(__BORLANDC__)
98 std::ifstream
file(filename.c_str());
111 (
Message() <<
"/proc/" << getpid() <<
"/stat").GetString();
112 return ReadProcFileField<int>(
filename, 19);
118 const task_t task = mach_task_self();
119 mach_msg_type_number_t thread_count;
120 thread_act_array_t thread_list;
121 const kern_return_t
status = task_threads(task, &thread_list, &thread_count);
122 if (status == KERN_SUCCESS) {
126 reinterpret_cast<vm_address_t>(thread_list),
127 sizeof(thread_t) * thread_count);
128 return static_cast<size_t>(thread_count);
139 const int fd =
open(
"/proc/self/as", O_RDONLY);
143 procfs_info process_info;
145 devctl(fd, DCMD_PROC_INFO, &process_info,
sizeof(process_info), NULL);
148 return static_cast<size_t>(process_info.num_threads);
157 struct procentry64
entry;
158 pid_t
pid = getpid();
159 int status = getprocs64(&
entry,
sizeof(
entry), NULL, 0, &pid, 1);
161 return entry.pi_thcount;
175 #endif // GTEST_OS_LINUX
177 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
179 void SleepMilliseconds(
int n) {
183 AutoHandle::AutoHandle()
184 : handle_(INVALID_HANDLE_VALUE) {}
186 AutoHandle::AutoHandle(Handle handle)
189 AutoHandle::~AutoHandle() {
193 AutoHandle::Handle AutoHandle::Get()
const {
198 Reset(INVALID_HANDLE_VALUE);
203 if (handle_ != handle) {
205 ::CloseHandle(handle_);
210 <<
"Resetting a valid handle to itself is likely a programmer error "
211 "and thus not allowed.";
215 bool AutoHandle::IsCloseable()
const {
218 return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
221 Notification::Notification()
222 : event_(::CreateEvent(NULL,
229 void Notification::Notify() {
233 void Notification::WaitForNotification() {
235 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
239 : owner_thread_id_(0),
241 critical_section_init_phase_(0),
242 critical_section_(new CRITICAL_SECTION) {
243 ::InitializeCriticalSection(critical_section_);
252 if (type_ == kDynamic) {
253 ::DeleteCriticalSection(critical_section_);
254 delete critical_section_;
255 critical_section_ = NULL;
260 ThreadSafeLazyInit();
261 ::EnterCriticalSection(critical_section_);
262 owner_thread_id_ = ::GetCurrentThreadId();
265 void Mutex::Unlock() {
266 ThreadSafeLazyInit();
270 owner_thread_id_ = 0;
271 ::LeaveCriticalSection(critical_section_);
276 void Mutex::AssertHeld() {
277 ThreadSafeLazyInit();
278 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
279 <<
"The current thread is not holding the mutex @" <<
this;
283 void Mutex::ThreadSafeLazyInit() {
285 if (type_ == kStatic) {
287 ::InterlockedCompareExchange(&critical_section_init_phase_, 1
L, 0
L)) {
291 owner_thread_id_ = 0;
292 critical_section_ =
new CRITICAL_SECTION;
293 ::InitializeCriticalSection(critical_section_);
297 &critical_section_init_phase_, 2
L, 1
L) ==
303 while (::InterlockedCompareExchange(&critical_section_init_phase_,
317 <<
"Unexpected value of critical_section_init_phase_ "
318 <<
"while initializing a static mutex.";
325 class ThreadWithParamSupport :
public ThreadWithParamBase {
327 static HANDLE CreateThread(Runnable* runnable,
328 Notification* thread_can_start) {
329 ThreadMainParam* param =
new ThreadMainParam(runnable, thread_can_start);
332 HANDLE thread_handle = ::CreateThread(
335 &ThreadWithParamSupport::ThreadMain,
339 GTEST_CHECK_(thread_handle != NULL) <<
"CreateThread failed with error "
340 << ::GetLastError() <<
".";
341 if (thread_handle == NULL) {
344 return thread_handle;
348 struct ThreadMainParam {
349 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
350 : runnable_(runnable),
351 thread_can_start_(thread_can_start) {
353 scoped_ptr<Runnable> runnable_;
355 Notification* thread_can_start_;
358 static DWORD WINAPI ThreadMain(
void* ptr) {
360 scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
361 if (param->thread_can_start_ != NULL)
362 param->thread_can_start_->WaitForNotification();
363 param->runnable_->Run();
368 ThreadWithParamSupport();
375 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
376 Notification* thread_can_start)
377 : thread_(ThreadWithParamSupport::CreateThread(runnable,
381 ThreadWithParamBase::~ThreadWithParamBase() {
385 void ThreadWithParamBase::Join() {
386 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
387 <<
"Failed to join the thread with error " << ::GetLastError() <<
".";
394 class ThreadLocalRegistryImpl {
398 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
399 const ThreadLocalBase* thread_local_instance) {
400 DWORD current_thread = ::GetCurrentThreadId();
402 ThreadIdToThreadLocals*
const thread_to_thread_locals =
403 GetThreadLocalsMapLocked();
404 ThreadIdToThreadLocals::iterator thread_local_pos =
405 thread_to_thread_locals->find(current_thread);
406 if (thread_local_pos == thread_to_thread_locals->end()) {
407 thread_local_pos = thread_to_thread_locals->insert(
408 std::make_pair(current_thread, ThreadLocalValues())).first;
409 StartWatcherThreadFor(current_thread);
411 ThreadLocalValues& thread_local_values = thread_local_pos->second;
412 ThreadLocalValues::iterator value_pos =
413 thread_local_values.find(thread_local_instance);
414 if (value_pos == thread_local_values.end()) {
417 .insert(std::make_pair(
418 thread_local_instance,
419 linked_ptr<ThreadLocalValueHolderBase>(
420 thread_local_instance->NewValueForCurrentThread())))
423 return value_pos->second.get();
426 static void OnThreadLocalDestroyed(
427 const ThreadLocalBase* thread_local_instance) {
428 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
433 ThreadIdToThreadLocals*
const thread_to_thread_locals =
434 GetThreadLocalsMapLocked();
435 for (ThreadIdToThreadLocals::iterator
it =
436 thread_to_thread_locals->begin();
437 it != thread_to_thread_locals->end();
439 ThreadLocalValues& thread_local_values =
it->second;
440 ThreadLocalValues::iterator value_pos =
441 thread_local_values.find(thread_local_instance);
442 if (value_pos != thread_local_values.end()) {
443 value_holders.push_back(value_pos->second);
444 thread_local_values.erase(value_pos);
454 static void OnThreadExit(DWORD thread_id) {
456 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
461 ThreadIdToThreadLocals*
const thread_to_thread_locals =
462 GetThreadLocalsMapLocked();
463 ThreadIdToThreadLocals::iterator thread_local_pos =
464 thread_to_thread_locals->find(thread_id);
465 if (thread_local_pos != thread_to_thread_locals->end()) {
466 ThreadLocalValues& thread_local_values = thread_local_pos->second;
467 for (ThreadLocalValues::iterator value_pos =
468 thread_local_values.begin();
469 value_pos != thread_local_values.end();
471 value_holders.push_back(value_pos->second);
473 thread_to_thread_locals->erase(thread_local_pos);
482 typedef std::map<
const ThreadLocalBase*,
483 linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
486 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
490 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
492 static void StartWatcherThreadFor(DWORD thread_id) {
495 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
501 DWORD watcher_thread_id;
502 HANDLE watcher_thread = ::CreateThread(
505 &ThreadLocalRegistryImpl::WatcherThreadFunc,
506 reinterpret_cast<LPVOID>(
new ThreadIdAndHandle(thread_id, thread)),
512 ::SetThreadPriority(watcher_thread,
513 ::GetThreadPriority(::GetCurrentThread()));
514 ::ResumeThread(watcher_thread);
515 ::CloseHandle(watcher_thread);
520 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
521 const ThreadIdAndHandle* tah =
522 reinterpret_cast<const ThreadIdAndHandle*
>(param);
524 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
525 OnThreadExit(tah->first);
526 ::CloseHandle(tah->second);
532 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
534 static ThreadIdToThreadLocals* map =
new ThreadIdToThreadLocals;
541 static Mutex thread_map_mutex_;
544 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
545 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
547 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
548 const ThreadLocalBase* thread_local_instance) {
549 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
550 thread_local_instance);
553 void ThreadLocalRegistry::OnThreadLocalDestroyed(
554 const ThreadLocalBase* thread_local_instance) {
555 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
558 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
560 #if GTEST_USES_POSIX_RE
570 regfree(&partial_regex_);
571 regfree(&full_regex_);
573 free(const_cast<char*>(pattern_));
577 bool RE::FullMatch(
const char*
str,
const RE& re) {
578 if (!re.is_valid_)
return false;
581 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
586 bool RE::PartialMatch(
const char* str,
const RE& re) {
587 if (!re.is_valid_)
return false;
590 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
599 const size_t full_regex_len = strlen(regex) + 10;
600 char*
const full_pattern =
new char[full_regex_len];
602 snprintf(full_pattern, full_regex_len,
"^(%s)$", regex);
603 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
613 const char*
const partial_regex = (*regex ==
'\0') ?
"()" : regex;
614 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
617 <<
"Regular expression \"" << regex
618 <<
"\" is not a valid POSIX Extended regular expression.";
620 delete[] full_pattern;
623 #elif GTEST_USES_SIMPLE_RE
627 bool IsInSet(
char ch,
const char* str) {
628 return ch !=
'\0' && strchr(str, ch) != NULL;
634 bool IsAsciiDigit(
char ch) {
return '0' <= ch && ch <=
'9'; }
635 bool IsAsciiPunct(
char ch) {
636 return IsInSet(ch,
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
638 bool IsRepeat(
char ch) {
return IsInSet(ch,
"?*+"); }
639 bool IsAsciiWhiteSpace(
char ch) {
return IsInSet(ch,
" \f\n\r\t\v"); }
640 bool IsAsciiWordChar(
char ch) {
641 return (
'a' <= ch && ch <=
'z') || (
'A' <= ch && ch <=
'Z') ||
642 (
'0' <= ch && ch <=
'9') || ch ==
'_';
646 bool IsValidEscape(
char c) {
647 return (IsAsciiPunct(c) || IsInSet(c,
"dDfnrsStvwW"));
652 bool AtomMatchesChar(
bool escaped,
char pattern_char,
char ch) {
654 switch (pattern_char) {
655 case 'd':
return IsAsciiDigit(ch);
656 case 'D':
return !IsAsciiDigit(ch);
657 case 'f':
return ch ==
'\f';
658 case 'n':
return ch ==
'\n';
659 case 'r':
return ch ==
'\r';
660 case 's':
return IsAsciiWhiteSpace(ch);
661 case 'S':
return !IsAsciiWhiteSpace(ch);
662 case 't':
return ch ==
'\t';
663 case 'v':
return ch ==
'\v';
664 case 'w':
return IsAsciiWordChar(ch);
665 case 'W':
return !IsAsciiWordChar(ch);
667 return IsAsciiPunct(pattern_char) && pattern_char == ch;
670 return (pattern_char ==
'.' && ch !=
'\n') || pattern_char == ch;
675 return (Message() <<
"Syntax error at index " << index
676 <<
" in simple regular expression \"" << regex <<
"\": ").GetString();
681 bool ValidateRegex(
const char* regex) {
686 ADD_FAILURE() <<
"NULL is not a valid simple regular expression.";
693 bool prev_repeatable =
false;
694 for (
int i = 0; regex[
i];
i++) {
695 if (regex[
i] ==
'\\') {
697 if (regex[
i] ==
'\0') {
699 <<
"'\\' cannot appear at the end.";
703 if (!IsValidEscape(regex[
i])) {
704 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
705 <<
"invalid escape sequence \"\\" << regex[
i] <<
"\".";
708 prev_repeatable =
true;
710 const char ch = regex[
i];
712 if (ch ==
'^' &&
i > 0) {
714 <<
"'^' can only appear at the beginning.";
716 }
else if (ch ==
'$' && regex[
i + 1] !=
'\0') {
718 <<
"'$' can only appear at the end.";
720 }
else if (IsInSet(ch,
"()[]{}|")) {
722 <<
"'" << ch <<
"' is unsupported.";
724 }
else if (IsRepeat(ch) && !prev_repeatable) {
726 <<
"'" << ch <<
"' can only follow a repeatable token.";
730 prev_repeatable = !IsInSet(ch,
"^$?*+");
744 bool MatchRepetitionAndRegexAtHead(
745 bool escaped,
char c,
char repeat,
const char* regex,
747 const size_t min_count = (repeat ==
'+') ? 1 : 0;
748 const size_t max_count = (repeat ==
'?') ? 1 :
749 static_cast<size_t>(-1) - 1;
753 for (
size_t i = 0;
i <= max_count; ++
i) {
755 if (
i >= min_count && MatchRegexAtHead(regex, str +
i)) {
762 if (str[
i] ==
'\0' || !AtomMatchesChar(escaped, c, str[
i]))
771 bool MatchRegexAtHead(
const char* regex,
const char* str) {
781 const bool escaped = *regex ==
'\\';
784 if (IsRepeat(regex[1])) {
788 return MatchRepetitionAndRegexAtHead(
789 escaped, regex[0], regex[1], regex + 2, str);
794 return (*str !=
'\0') && AtomMatchesChar(escaped, *regex, *str) &&
795 MatchRegexAtHead(regex + 1, str + 1);
807 bool MatchRegexAnywhere(
const char* regex,
const char* str) {
808 if (regex == NULL || str == NULL)
812 return MatchRegexAtHead(regex + 1, str);
816 if (MatchRegexAtHead(regex, str))
818 }
while (*str++ !=
'\0');
825 free(const_cast<char*>(pattern_));
826 free(const_cast<char*>(full_pattern_));
830 bool RE::FullMatch(
const char* str,
const RE& re) {
831 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
836 bool RE::PartialMatch(
const char* str,
const RE& re) {
837 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
842 pattern_ = full_pattern_ = NULL;
847 is_valid_ = ValidateRegex(regex);
853 const size_t len = strlen(regex);
857 char*
buffer =
static_cast<char*
>(malloc(len + 3));
858 full_pattern_ = buffer;
865 memcpy(buffer, regex, len);
868 if (len == 0 || regex[len - 1] !=
'$')
874 #endif // GTEST_USES_POSIX_RE
884 return file_name +
":";
909 : severity_(severity) {
910 const char*
const marker =
913 severity ==
GTEST_ERROR ?
"[ ERROR ]" :
"[ FATAL ]";
914 GetStream() << ::std::endl << marker <<
" "
930 #if GTEST_HAS_STREAM_REDIRECTION
933 class CapturedStream {
936 explicit CapturedStream(
int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
937 # if GTEST_OS_WINDOWS
938 char temp_dir_path[MAX_PATH + 1] = {
'\0' };
939 char temp_file_path[MAX_PATH + 1] = {
'\0' };
941 ::GetTempPathA(
sizeof(temp_dir_path), temp_dir_path);
942 const UINT success = ::GetTempFileNameA(temp_dir_path,
947 <<
"Unable to create a temporary file in " << temp_dir_path;
948 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
949 GTEST_CHECK_(captured_fd != -1) <<
"Unable to open temporary file "
951 filename_ = temp_file_path;
957 # if GTEST_OS_LINUX_ANDROID
972 char name_template[] =
"/sdcard/gtest_captured_stream.XXXXXX";
974 char name_template[] =
"/tmp/captured_stream.XXXXXX";
975 # endif // GTEST_OS_LINUX_ANDROID
976 const int captured_fd = mkstemp(name_template);
977 filename_ = name_template;
978 # endif // GTEST_OS_WINDOWS
980 dup2(captured_fd, fd_);
985 remove(filename_.c_str());
989 if (uncaptured_fd_ != -1) {
992 dup2(uncaptured_fd_, fd_);
993 close(uncaptured_fd_);
1014 static CapturedStream* g_captured_stderr = NULL;
1015 static CapturedStream* g_captured_stdout = NULL;
1018 void CaptureStream(
int fd, const
char* stream_name, CapturedStream** stream) {
1019 if (*stream != NULL) {
1021 <<
" capturer can exist at a time.";
1023 *stream =
new CapturedStream(fd);
1027 std::string GetCapturedStream(CapturedStream** captured_stream) {
1028 const std::string content = (*captured_stream)->GetCapturedString();
1030 delete *captured_stream;
1031 *captured_stream = NULL;
1048 return GetCapturedStream(&g_captured_stdout);
1053 return GetCapturedStream(&g_captured_stderr);
1056 #endif // GTEST_HAS_STREAM_REDIRECTION
1059 #if GTEST_OS_WINDOWS_MOBILE
1061 #elif GTEST_OS_WINDOWS
1063 if (temp_dir == NULL || temp_dir[0] ==
'\0')
1065 else if (temp_dir[strlen(temp_dir) - 1] ==
'\\')
1069 #elif GTEST_OS_LINUX_ANDROID
1073 #endif // GTEST_OS_WINDOWS_MOBILE
1077 fseek(file, 0, SEEK_END);
1078 return static_cast<size_t>(ftell(file));
1083 char*
const buffer =
new char[file_size];
1085 size_t bytes_last_read = 0;
1086 size_t bytes_read = 0;
1088 fseek(file, 0, SEEK_SET);
1093 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
1094 bytes_read += bytes_last_read;
1095 }
while (bytes_last_read > 0 && bytes_read < file_size);
1103 #if GTEST_HAS_DEATH_TEST
1105 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
1108 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
1109 if (g_injected_test_argvs != argvs)
1110 delete g_injected_test_argvs;
1111 g_injected_test_argvs = argvs;
1114 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
1115 if (g_injected_test_argvs != NULL) {
1116 return *g_injected_test_argvs;
1120 #endif // GTEST_HAS_DEATH_TEST
1122 #if GTEST_OS_WINDOWS_MOBILE
1126 TerminateProcess(GetCurrentProcess(), 1);
1129 #endif // GTEST_OS_WINDOWS_MOBILE
1139 for (
size_t i = 0;
i != full_flag.length();
i++) {
1140 env_var <<
ToUpper(full_flag.c_str()[
i]);
1152 const long long_value = strtol(str, &end, 10);
1158 msg <<
"WARNING: " << src_text
1159 <<
" is expected to be a 32-bit integer, but actually"
1160 <<
" has value \"" << str <<
"\".\n";
1167 const Int32 result =
static_cast<Int32>(long_value);
1168 if (long_value == LONG_MAX || long_value == LONG_MIN ||
1171 result != long_value
1175 msg <<
"WARNING: " << src_text
1176 <<
" is expected to be a 32-bit integer, but actually"
1177 <<
" has value " << str <<
", which overflows.\n";
1192 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1193 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1194 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1196 const char*
const string_value =
posix::GetEnv(env_var.c_str());
1197 return string_value == NULL ?
1198 default_value : strcmp(string_value,
"0") != 0;
1205 #if defined(GTEST_GET_INT32_FROM_ENV_)
1206 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1207 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1209 const char*
const string_value =
posix::GetEnv(env_var.c_str());
1210 if (string_value == NULL) {
1212 return default_value;
1215 Int32 result = default_value;
1217 string_value, &result)) {
1218 printf(
"The default value %s is used.\n",
1219 (
Message() << default_value).GetString().c_str());
1221 return default_value;
1230 #if defined(GTEST_GET_STRING_FROM_ENV_)
1231 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1232 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
1235 if (value != NULL) {
1249 if (strcmp(flag,
"output") == 0) {
1251 if (value != NULL) {
1255 return default_value;