45 #ifdef GTEST_OS_WINDOWS
56 #endif // GTEST_OS_WINDOWS
59 #include <mach/mach_init.h>
60 #include <mach/task.h>
61 #include <mach/vm_map.h>
62 #endif // GTEST_OS_MAC
64 #if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
65 defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \
66 defined(GTEST_OS_OPENBSD)
67 #include <sys/sysctl.h>
68 #if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
69 defined(GTEST_OS_GNU_KFREEBSD)
77 #include <sys/procfs.h>
78 #endif // GTEST_OS_QNX
82 #include <sys/types.h>
83 #endif // GTEST_OS_AIX
85 #ifdef GTEST_OS_FUCHSIA
86 #include <zircon/process.h>
87 #include <zircon/syscalls.h>
88 #endif // GTEST_OS_FUCHSIA
99 #if defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_HURD)
102 template <
typename T>
103 T ReadProcFileField(
const std::string& filename,
int field) {
105 std::ifstream file(filename.c_str());
106 while (field-- > 0) {
117 const std::string filename =
118 (Message() <<
"/proc/" << getpid() <<
"/stat").GetString();
119 return ReadProcFileField<size_t>(filename, 19);
122 #elif defined(GTEST_OS_MAC)
125 const task_t task = mach_task_self();
126 mach_msg_type_number_t thread_count;
127 thread_act_array_t thread_list;
128 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
129 if (status == KERN_SUCCESS) {
132 vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
133 sizeof(thread_t) * thread_count);
134 return static_cast<size_t>(thread_count);
140 #elif defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
141 defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD)
143 #ifdef GTEST_OS_NETBSD
145 #define KERN_PROC KERN_PROC2
146 #define kinfo_proc kinfo_proc2
149 #ifdef GTEST_OS_DRAGONFLY
150 #define KP_NLWP(kp) (kp.kp_nthreads)
151 #elif defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_GNU_KFREEBSD)
152 #define KP_NLWP(kp) (kp.ki_numthreads)
153 #elif defined(GTEST_OS_NETBSD)
154 #define KP_NLWP(kp) (kp.p_nlwps)
165 #ifdef GTEST_OS_NETBSD
166 sizeof(
struct kinfo_proc),
170 u_int miblen =
sizeof(mib) /
sizeof(mib[0]);
171 struct kinfo_proc info;
172 size_t size =
sizeof(info);
173 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
176 return static_cast<size_t>(KP_NLWP(info));
178 #elif defined(GTEST_OS_OPENBSD)
186 KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
188 sizeof(
struct kinfo_proc),
191 u_int miblen =
sizeof(mib) /
sizeof(mib[0]);
195 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
199 mib[5] =
static_cast<int>(size /
static_cast<size_t>(mib[4]));
202 std::vector<struct kinfo_proc> info(mib[5]);
203 if (sysctl(mib, miblen, info.data(), &size, NULL, 0)) {
209 for (
size_t i = 0;
i < size /
static_cast<size_t>(mib[4]);
i++) {
210 if (info[
i].p_tid != -1) nthreads++;
215 #elif defined(GTEST_OS_QNX)
220 const int fd = open(
"/proc/self/as", O_RDONLY);
224 procfs_info process_info;
226 devctl(fd, DCMD_PROC_INFO, &process_info,
sizeof(process_info),
nullptr);
229 return static_cast<size_t>(process_info.num_threads);
235 #elif defined(GTEST_OS_AIX)
238 struct procentry64 entry;
239 pid_t pid = getpid();
240 int status = getprocs64(&entry,
sizeof(entry),
nullptr, 0, &pid, 1);
242 return entry.pi_thcount;
248 #elif defined(GTEST_OS_FUCHSIA)
254 zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS,
255 &dummy_buffer, 0,
nullptr, &avail);
256 if (status == ZX_OK) {
271 #endif // GTEST_OS_LINUX
273 #if defined(GTEST_IS_THREADSAFE) && defined(GTEST_OS_WINDOWS)
275 AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
277 AutoHandle::AutoHandle(Handle handle) : handle_(handle) {}
279 AutoHandle::~AutoHandle() { Reset(); }
281 AutoHandle::Handle AutoHandle::Get()
const {
return handle_; }
283 void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); }
285 void AutoHandle::Reset(HANDLE handle) {
287 if (handle_ != handle) {
289 ::CloseHandle(handle_);
294 <<
"Resetting a valid handle to itself is likely a programmer error "
295 "and thus not allowed.";
299 bool AutoHandle::IsCloseable()
const {
302 return handle_ !=
nullptr && handle_ != INVALID_HANDLE_VALUE;
306 : owner_thread_id_(0),
308 critical_section_init_phase_(0),
309 critical_section_(new CRITICAL_SECTION) {
310 ::InitializeCriticalSection(critical_section_);
316 if (type_ == kDynamic) {
317 ::DeleteCriticalSection(critical_section_);
318 delete critical_section_;
319 critical_section_ =
nullptr;
324 ThreadSafeLazyInit();
325 ::EnterCriticalSection(critical_section_);
326 owner_thread_id_ = ::GetCurrentThreadId();
329 void Mutex::Unlock() {
330 ThreadSafeLazyInit();
334 owner_thread_id_ = 0;
335 ::LeaveCriticalSection(critical_section_);
340 void Mutex::AssertHeld() {
341 ThreadSafeLazyInit();
342 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
343 <<
"The current thread is not holding the mutex @" <<
this;
357 class MemoryIsNotDeallocated {
359 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
360 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
363 (
void)_CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
366 ~MemoryIsNotDeallocated() {
368 (
void)_CrtSetDbgFlag(old_crtdbg_flag_);
372 int old_crtdbg_flag_;
374 MemoryIsNotDeallocated(
const MemoryIsNotDeallocated&) =
delete;
375 MemoryIsNotDeallocated& operator=(
const MemoryIsNotDeallocated&) =
delete;
382 void Mutex::ThreadSafeLazyInit() {
384 if (type_ == kStatic) {
386 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
390 owner_thread_id_ = 0;
394 MemoryIsNotDeallocated memory_is_not_deallocated;
396 critical_section_ =
new CRITICAL_SECTION;
398 ::InitializeCriticalSection(critical_section_);
401 GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_,
407 while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L,
420 <<
"Unexpected value of critical_section_init_phase_ "
421 <<
"while initializing a static mutex.";
428 class ThreadWithParamSupport :
public ThreadWithParamBase {
430 static HANDLE CreateThread(Runnable* runnable,
431 Notification* thread_can_start) {
432 ThreadMainParam* param =
new ThreadMainParam(runnable, thread_can_start);
434 HANDLE thread_handle = ::CreateThread(
437 &ThreadWithParamSupport::ThreadMain,
442 <<
"CreateThread failed with error " << ::GetLastError() <<
".";
443 if (thread_handle ==
nullptr) {
446 return thread_handle;
450 struct ThreadMainParam {
451 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
452 : runnable_(runnable), thread_can_start_(thread_can_start) {}
453 std::unique_ptr<Runnable> runnable_;
455 Notification* thread_can_start_;
458 static DWORD WINAPI ThreadMain(
void* ptr) {
460 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
461 if (param->thread_can_start_ !=
nullptr)
462 param->thread_can_start_->WaitForNotification();
463 param->runnable_->Run();
468 ThreadWithParamSupport();
470 ThreadWithParamSupport(
const ThreadWithParamSupport&) =
delete;
471 ThreadWithParamSupport& operator=(
const ThreadWithParamSupport&) =
delete;
476 ThreadWithParamBase::ThreadWithParamBase(Runnable* runnable,
477 Notification* thread_can_start)
479 ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {}
481 ThreadWithParamBase::~ThreadWithParamBase() { Join(); }
483 void ThreadWithParamBase::Join() {
484 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
485 <<
"Failed to join the thread with error " << ::GetLastError() <<
".";
492 class ThreadLocalRegistryImpl {
496 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
497 const ThreadLocalBase* thread_local_instance) {
499 MemoryIsNotDeallocated memory_is_not_deallocated;
501 DWORD current_thread = ::GetCurrentThreadId();
503 ThreadIdToThreadLocals*
const thread_to_thread_locals =
504 GetThreadLocalsMapLocked();
505 ThreadIdToThreadLocals::iterator thread_local_pos =
506 thread_to_thread_locals->find(current_thread);
507 if (thread_local_pos == thread_to_thread_locals->end()) {
509 thread_to_thread_locals
510 ->insert(std::make_pair(current_thread, ThreadLocalValues()))
512 StartWatcherThreadFor(current_thread);
514 ThreadLocalValues& thread_local_values = thread_local_pos->second;
515 ThreadLocalValues::iterator value_pos =
516 thread_local_values.find(thread_local_instance);
517 if (value_pos == thread_local_values.end()) {
520 .insert(std::make_pair(
521 thread_local_instance,
522 std::shared_ptr<ThreadLocalValueHolderBase>(
523 thread_local_instance->NewValueForCurrentThread())))
526 return value_pos->second.get();
529 static void OnThreadLocalDestroyed(
530 const ThreadLocalBase* thread_local_instance) {
531 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
536 ThreadIdToThreadLocals*
const thread_to_thread_locals =
537 GetThreadLocalsMapLocked();
538 for (ThreadIdToThreadLocals::iterator it =
539 thread_to_thread_locals->begin();
540 it != thread_to_thread_locals->end(); ++it) {
541 ThreadLocalValues& thread_local_values = it->second;
542 ThreadLocalValues::iterator value_pos =
543 thread_local_values.find(thread_local_instance);
544 if (value_pos != thread_local_values.end()) {
545 value_holders.push_back(value_pos->second);
546 thread_local_values.erase(value_pos);
556 static void OnThreadExit(DWORD thread_id) {
558 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
563 ThreadIdToThreadLocals*
const thread_to_thread_locals =
564 GetThreadLocalsMapLocked();
565 ThreadIdToThreadLocals::iterator thread_local_pos =
566 thread_to_thread_locals->find(thread_id);
567 if (thread_local_pos != thread_to_thread_locals->end()) {
568 ThreadLocalValues& thread_local_values = thread_local_pos->second;
569 for (ThreadLocalValues::iterator value_pos =
570 thread_local_values.begin();
571 value_pos != thread_local_values.end(); ++value_pos) {
572 value_holders.push_back(value_pos->second);
574 thread_to_thread_locals->erase(thread_local_pos);
583 typedef std::map<
const ThreadLocalBase*,
584 std::shared_ptr<ThreadLocalValueHolderBase> >
588 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
590 struct WatcherThreadParams {
593 Notification has_initialized;
596 static void StartWatcherThreadFor(DWORD thread_id) {
600 ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id);
603 WatcherThreadParams* watcher_thread_params =
new WatcherThreadParams;
604 watcher_thread_params->thread_id = thread_id;
605 watcher_thread_params->handle = thread;
609 DWORD watcher_thread_id;
610 HANDLE watcher_thread =
611 ::CreateThread(
nullptr,
613 &ThreadLocalRegistryImpl::WatcherThreadFunc,
614 reinterpret_cast<LPVOID>(watcher_thread_params),
615 CREATE_SUSPENDED, &watcher_thread_id);
617 <<
"CreateThread failed with error " << ::GetLastError() <<
".";
620 ::SetThreadPriority(watcher_thread,
621 ::GetThreadPriority(::GetCurrentThread()));
622 ::ResumeThread(watcher_thread);
623 ::CloseHandle(watcher_thread);
629 watcher_thread_params->has_initialized.WaitForNotification();
634 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
635 WatcherThreadParams* watcher_thread_params =
636 reinterpret_cast<WatcherThreadParams*
>(param);
637 watcher_thread_params->has_initialized.Notify();
638 GTEST_CHECK_(::WaitForSingleObject(watcher_thread_params->handle,
639 INFINITE) == WAIT_OBJECT_0);
640 OnThreadExit(watcher_thread_params->thread_id);
641 ::CloseHandle(watcher_thread_params->handle);
642 delete watcher_thread_params;
647 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
650 MemoryIsNotDeallocated memory_is_not_deallocated;
652 static ThreadIdToThreadLocals* map =
new ThreadIdToThreadLocals();
659 static Mutex thread_map_mutex_;
662 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
663 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(
664 Mutex::kStaticMutex);
666 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
667 const ThreadLocalBase* thread_local_instance) {
668 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
669 thread_local_instance);
672 void ThreadLocalRegistry::OnThreadLocalDestroyed(
673 const ThreadLocalBase* thread_local_instance) {
674 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
677 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
679 #ifdef GTEST_USES_POSIX_RE
689 regfree(&partial_regex_);
690 regfree(&full_regex_);
695 bool RE::FullMatch(
const char* str,
const RE& re) {
696 if (!re.is_valid_)
return false;
699 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
704 bool RE::PartialMatch(
const char* str,
const RE& re) {
705 if (!re.is_valid_)
return false;
708 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
712 void RE::Init(
const char* regex) {
721 constexpr
int reg_flags = REG_EXTENDED | REG_GNU;
723 constexpr
int reg_flags = REG_EXTENDED;
728 const size_t full_regex_len = strlen(regex) + 10;
729 char*
const full_pattern =
new char[full_regex_len];
731 snprintf(full_pattern, full_regex_len,
"^(%s)$", regex);
732 is_valid_ = regcomp(&full_regex_, full_pattern, reg_flags) == 0;
742 const char*
const partial_regex = (*regex ==
'\0') ?
"()" : regex;
743 is_valid_ = regcomp(&partial_regex_, partial_regex, reg_flags) == 0;
746 <<
"Regular expression \"" << regex
747 <<
"\" is not a valid POSIX Extended regular expression.";
749 delete[] full_pattern;
752 #elif defined(GTEST_USES_SIMPLE_RE)
756 bool IsInSet(
char ch,
const char* str) {
757 return ch !=
'\0' && strchr(str, ch) !=
nullptr;
763 bool IsAsciiDigit(
char ch) {
return '0' <= ch && ch <=
'9'; }
764 bool IsAsciiPunct(
char ch) {
765 return IsInSet(ch,
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
767 bool IsRepeat(
char ch) {
return IsInSet(ch,
"?*+"); }
768 bool IsAsciiWhiteSpace(
char ch) {
return IsInSet(ch,
" \f\n\r\t\v"); }
769 bool IsAsciiWordChar(
char ch) {
770 return (
'a' <= ch && ch <=
'z') || (
'A' <= ch && ch <=
'Z') ||
771 (
'0' <= ch && ch <=
'9') || ch ==
'_';
775 bool IsValidEscape(
char c) {
776 return (IsAsciiPunct(c) || IsInSet(c,
"dDfnrsStvwW"));
781 bool AtomMatchesChar(
bool escaped,
char pattern_char,
char ch) {
783 switch (pattern_char) {
785 return IsAsciiDigit(ch);
787 return !IsAsciiDigit(ch);
795 return IsAsciiWhiteSpace(ch);
797 return !IsAsciiWhiteSpace(ch);
803 return IsAsciiWordChar(ch);
805 return !IsAsciiWordChar(ch);
807 return IsAsciiPunct(pattern_char) && pattern_char ==
ch;
810 return (pattern_char ==
'.' && ch !=
'\n') || pattern_char ==
ch;
814 static std::string FormatRegexSyntaxError(
const char* regex,
int index) {
815 return (Message() <<
"Syntax error at index " << index
816 <<
" in simple regular expression \"" << regex <<
"\": ")
822 bool ValidateRegex(
const char* regex) {
823 if (regex ==
nullptr) {
824 ADD_FAILURE() <<
"NULL is not a valid simple regular expression.";
828 bool is_valid =
true;
831 bool prev_repeatable =
false;
832 for (
int i = 0; regex[
i];
i++) {
833 if (regex[
i] ==
'\\') {
835 if (regex[
i] ==
'\0') {
837 <<
"'\\' cannot appear at the end.";
841 if (!IsValidEscape(regex[
i])) {
842 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
843 <<
"invalid escape sequence \"\\" << regex[
i] <<
"\".";
846 prev_repeatable =
true;
848 const char ch = regex[
i];
850 if (ch ==
'^' &&
i > 0) {
852 <<
"'^' can only appear at the beginning.";
854 }
else if (ch ==
'$' && regex[
i + 1] !=
'\0') {
856 <<
"'$' can only appear at the end.";
858 }
else if (IsInSet(ch,
"()[]{}|")) {
859 ADD_FAILURE() << FormatRegexSyntaxError(regex,
i) <<
"'" << ch
860 <<
"' is unsupported.";
862 }
else if (IsRepeat(ch) && !prev_repeatable) {
863 ADD_FAILURE() << FormatRegexSyntaxError(regex,
i) <<
"'" << ch
864 <<
"' can only follow a repeatable token.";
868 prev_repeatable = !IsInSet(ch,
"^$?*+");
882 bool MatchRepetitionAndRegexAtHead(
bool escaped,
char c,
char repeat,
883 const char* regex,
const char* str) {
884 const size_t min_count = (repeat ==
'+') ? 1 : 0;
885 const size_t max_count = (repeat ==
'?') ? 1 : static_cast<size_t>(-1) - 1;
889 for (
size_t i = 0;
i <= max_count; ++
i) {
891 if (
i >= min_count && MatchRegexAtHead(regex, str +
i)) {
898 if (str[
i] ==
'\0' || !AtomMatchesChar(escaped, c, str[
i]))
return false;
906 bool MatchRegexAtHead(
const char* regex,
const char* str) {
912 if (*regex ==
'$')
return *str ==
'\0';
915 const bool escaped = *regex ==
'\\';
916 if (escaped) ++regex;
917 if (IsRepeat(regex[1])) {
921 return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
927 return (*str !=
'\0') && AtomMatchesChar(escaped, *regex, *str) &&
928 MatchRegexAtHead(regex + 1, str + 1);
940 bool MatchRegexAnywhere(
const char* regex,
const char* str) {
941 if (regex ==
nullptr || str ==
nullptr)
return false;
943 if (*regex ==
'^')
return MatchRegexAtHead(regex + 1, str);
947 if (MatchRegexAtHead(regex, str))
return true;
948 }
while (*str++ !=
'\0');
957 bool RE::FullMatch(
const char* str,
const RE& re) {
958 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_.c_str(), str);
963 bool RE::PartialMatch(
const char* str,
const RE& re) {
964 return re.is_valid_ && MatchRegexAnywhere(re.pattern_.c_str(), str);
968 void RE::Init(
const char* regex) {
969 full_pattern_.clear();
972 if (regex !=
nullptr) {
976 is_valid_ = ValidateRegex(regex);
984 full_pattern_.reserve(pattern_.size() + 2);
986 if (pattern_.empty() || pattern_.front() !=
'^') {
987 full_pattern_.push_back(
'^');
990 full_pattern_.append(pattern_);
992 if (pattern_.empty() || pattern_.back() !=
'$') {
993 full_pattern_.push_back(
'$');
997 #endif // GTEST_USES_POSIX_RE
1004 const std::string file_name(file ==
nullptr ? kUnknownFile : file);
1007 return file_name +
":";
1023 const std::string file_name(file ==
nullptr ? kUnknownFile : file);
1032 : severity_(severity) {
1033 const char*
const marker = severity ==
GTEST_INFO ?
"[ INFO ]"
1051 #if GTEST_HAS_STREAM_REDIRECTION
1059 #if defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_IOS)
1060 bool EndsWithPathSeparator(
const std::string& path) {
1068 class CapturedStream {
1071 explicit CapturedStream(
int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
1072 #ifdef GTEST_OS_WINDOWS
1073 char temp_dir_path[MAX_PATH + 1] = {
'\0'};
1074 char temp_file_path[MAX_PATH + 1] = {
'\0'};
1076 ::GetTempPathA(
sizeof(temp_dir_path), temp_dir_path);
1077 const UINT success = ::GetTempFileNameA(temp_dir_path,
"gtest_redir",
1081 <<
"Unable to create a temporary file in " << temp_dir_path;
1082 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
1084 <<
"Unable to open temporary file " << temp_file_path;
1085 filename_ = temp_file_path;
1089 std::string name_template;
1091 #ifdef GTEST_OS_LINUX_ANDROID
1107 if (!EndsWithPathSeparator(name_template))
1110 #elif defined(GTEST_OS_IOS)
1111 char user_temp_dir[PATH_MAX + 1];
1126 ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir,
sizeof(user_temp_dir));
1128 name_template = user_temp_dir;
1129 if (!EndsWithPathSeparator(name_template))
1132 name_template =
"/tmp/";
1134 name_template.append(
"gtest_captured_stream.XXXXXX");
1142 const int captured_fd = ::mkstemp(const_cast<char*>(name_template.data()));
1143 if (captured_fd == -1) {
1145 <<
"Failed to create tmp file " << name_template
1146 <<
" for test; does the test have access to the /tmp directory?";
1148 filename_ = std::move(name_template);
1149 #endif // GTEST_OS_WINDOWS
1151 dup2(captured_fd, fd_);
1155 ~CapturedStream() {
remove(filename_.c_str()); }
1157 std::string GetCapturedString() {
1158 if (uncaptured_fd_ != -1) {
1161 dup2(uncaptured_fd_, fd_);
1162 close(uncaptured_fd_);
1163 uncaptured_fd_ = -1;
1166 FILE*
const file =
posix::FOpen(filename_.c_str(),
"r");
1167 if (file ==
nullptr) {
1168 GTEST_LOG_(FATAL) <<
"Failed to open tmp file " << filename_
1169 <<
" for capturing stream.";
1180 ::std::string filename_;
1182 CapturedStream(
const CapturedStream&) =
delete;
1183 CapturedStream& operator=(
const CapturedStream&) =
delete;
1188 static CapturedStream* g_captured_stderr =
nullptr;
1189 static CapturedStream* g_captured_stdout =
nullptr;
1192 static
void CaptureStream(
int fd, const
char* stream_name,
1193 CapturedStream** stream) {
1194 if (*stream !=
nullptr) {
1195 GTEST_LOG_(FATAL) <<
"Only one " << stream_name
1196 <<
" capturer can exist at a time.";
1198 *stream =
new CapturedStream(fd);
1202 static std::string GetCapturedStream(CapturedStream** captured_stream) {
1203 const std::string content = (*captured_stream)->GetCapturedString();
1205 delete *captured_stream;
1206 *captured_stream =
nullptr;
1211 #if defined(_MSC_VER) || defined(__BORLANDC__)
1213 const int kStdOutFileno = 1;
1214 const int kStdErrFileno = 2;
1216 const int kStdOutFileno = STDOUT_FILENO;
1217 const int kStdErrFileno = STDERR_FILENO;
1218 #endif // defined(_MSC_VER) || defined(__BORLANDC__)
1222 CaptureStream(kStdOutFileno,
"stdout", &g_captured_stdout);
1227 CaptureStream(kStdErrFileno,
"stderr", &g_captured_stderr);
1232 return GetCapturedStream(&g_captured_stdout);
1237 return GetCapturedStream(&g_captured_stderr);
1240 #endif // GTEST_HAS_STREAM_REDIRECTION
1243 fseek(file, 0, SEEK_END);
1244 return static_cast<size_t>(ftell(file));
1249 char*
const buffer =
new char[file_size];
1251 size_t bytes_last_read = 0;
1252 size_t bytes_read = 0;
1254 fseek(file, 0, SEEK_SET);
1260 fread(buffer + bytes_read, 1, file_size - bytes_read, file);
1261 bytes_read += bytes_last_read;
1262 }
while (bytes_last_read > 0 && bytes_read < file_size);
1264 const std::string content(buffer, bytes_read);
1270 #ifdef GTEST_HAS_DEATH_TEST
1271 static const std::vector<std::string>* g_injected_test_argvs =
1274 std::vector<std::string> GetInjectableArgvs() {
1275 if (g_injected_test_argvs !=
nullptr) {
1276 return *g_injected_test_argvs;
1281 void SetInjectableArgvs(
const std::vector<std::string>* new_argvs) {
1282 if (g_injected_test_argvs != new_argvs)
delete g_injected_test_argvs;
1283 g_injected_test_argvs = new_argvs;
1286 void SetInjectableArgvs(
const std::vector<std::string>& new_argvs) {
1288 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
1291 void ClearInjectableArgvs() {
1292 delete g_injected_test_argvs;
1293 g_injected_test_argvs =
nullptr;
1295 #endif // GTEST_HAS_DEATH_TEST
1297 #ifdef GTEST_OS_WINDOWS_MOBILE
1301 TerminateProcess(GetCurrentProcess(), 1);
1304 #endif // GTEST_OS_WINDOWS_MOBILE
1310 const std::string full_flag =
1314 for (
size_t i = 0;
i != full_flag.length();
i++) {
1315 env_var <<
ToUpper(full_flag.c_str()[
i]);
1326 char* end =
nullptr;
1327 const long long_value = strtol(str, &end, 10);
1333 msg <<
"WARNING: " << src_text
1334 <<
" is expected to be a 32-bit integer, but actually"
1335 <<
" has value \"" << str <<
"\".\n";
1342 const auto result =
static_cast<int32_t
>(long_value);
1343 if (long_value == LONG_MAX || long_value == LONG_MIN ||
1346 result != long_value
1350 msg <<
"WARNING: " << src_text
1351 <<
" is expected to be a 32-bit integer, but actually" <<
" has value "
1352 << str <<
", which overflows.\n";
1367 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1368 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1371 const char*
const string_value =
posix::GetEnv(env_var.c_str());
1372 return string_value ==
nullptr ? default_value
1373 : strcmp(string_value,
"0") != 0;
1374 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
1381 #if defined(GTEST_GET_INT32_FROM_ENV_)
1382 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1385 const char*
const string_value =
posix::GetEnv(env_var.c_str());
1386 if (string_value ==
nullptr) {
1388 return default_value;
1391 int32_t result = default_value;
1394 printf(
"The default value %s is used.\n",
1395 (
Message() << default_value).GetString().c_str());
1397 return default_value;
1401 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
1413 std::string default_value_for_output_flag =
"";
1414 const char* xml_output_file_env =
posix::GetEnv(
"XML_OUTPUT_FILE");
1415 if (
nullptr != xml_output_file_env) {
1416 default_value_for_output_flag = std::string(
"xml:") + xml_output_file_env;
1418 return default_value_for_output_flag;
1424 #if defined(GTEST_GET_STRING_FROM_ENV_)
1425 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1429 return value ==
nullptr ? default_value :
value;
1430 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
GTEST_API_ int32_t Int32FromGTestEnv(const char *flag, int32_t default_val)
GTEST_API_ std::string GetCapturedStdout()
GTEST_API_ std::string GetCapturedStderr()
#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
const char * StringFromGTestEnv(const char *flag, const char *default_val)
#define GTEST_LOG_(severity)
GTEST_API_ size_t GetThreadCount()
const char * GetEnv(const char *name)
GTEST_API_ void CaptureStdout()
#define GTEST_DISABLE_MSC_DEPRECATED_POP_()
GTEST_API_ std::vector< std::string > GetArgvs()
static std::string FlagToEnvVar(const char *flag)
std::string StreamableToString(const T &streamable)
GTEST_API_ std::string ReadEntireFile(FILE *file)
GTEST_API_ bool ParseInt32(const Message &src_text, const char *str, int32_t *value)
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
::std::ostream & GetStream()
const GTestLogSeverity severity_
expr expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c *expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 c
#define GTEST_CHECK_(condition)
GTEST_API_ size_t GetFileSize(FILE *file)
std::string GetString() const
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_API_ GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
bool BoolFromGTestEnv(const char *flag, bool default_val)
FILE * FOpen(const char *path, const char *mode)
const char kUnknownFile[]
GTEST_API_ void CaptureStderr()
#define EXPECT_TRUE(condition)
std::string OutputFlagAlsoCheckEnvVar()
#define GTEST_FLAG_PREFIX_
GTEST_API_ std::string TempDir()