31#include "gtest/internal/gtest-port.h"
54# include <mach/mach_init.h>
55# include <mach/task.h>
56# include <mach/vm_map.h>
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
70# include <sys/procfs.h>
75# include <sys/types.h>
79# include <zircon/process.h>
80# include <zircon/syscalls.h>
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__)
94const int kStdOutFileno = 1;
95const int kStdErrFileno = 2;
97const int kStdOutFileno = STDOUT_FILENO;
98const int kStdErrFileno = STDERR_FILENO;
105T ReadProcFileField(
const std::string& filename,
int field) {
107 std::ifstream file(filename.c_str());
108 while (field-- > 0) {
118size_t GetThreadCount() {
119 const std::string filename =
120 (Message() <<
"/proc/" << getpid() <<
"/stat").GetString();
121 return ReadProcFileField<size_t>(filename, 19);
126size_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) {
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)
157#define KP_NLWP(kp) (kp.p_nlwps)
162size_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
185size_t GetThreadCount() {
189 KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
191 sizeof(
struct kinfo_proc),
194 u_int miblen =
sizeof(mib) /
sizeof(mib[0]);
198 if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
202 mib[5] =
static_cast<int>(size /
static_cast<size_t>(mib[4]));
205 struct kinfo_proc info[mib[5]];
206 if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
212 for (
size_t i = 0; i < size /
static_cast<size_t>(mib[4]); i++) {
213 if (info[i].p_tid != -1)
223size_t GetThreadCount() {
224 const int fd = open(
"/proc/self/as", O_RDONLY);
228 procfs_info process_info;
230 devctl(fd, DCMD_PROC_INFO, &process_info,
sizeof(process_info),
nullptr);
233 return static_cast<size_t>(process_info.num_threads);
241size_t GetThreadCount() {
242 struct procentry64 entry;
243 pid_t pid = getpid();
244 int status = getprocs64(&entry,
sizeof(entry),
nullptr, 0, &pid, 1);
246 return entry.pi_thcount;
252#elif GTEST_OS_FUCHSIA
254size_t GetThreadCount() {
257 zx_status_t status = zx_object_get_info(
259 ZX_INFO_PROCESS_THREADS,
264 if (status == ZX_OK) {
273size_t GetThreadCount() {
281#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
283void SleepMilliseconds(
int n) {
284 ::Sleep(
static_cast<DWORD
>(n));
287AutoHandle::AutoHandle()
288 : handle_(INVALID_HANDLE_VALUE) {}
290AutoHandle::AutoHandle(Handle handle)
293AutoHandle::~AutoHandle() {
297AutoHandle::Handle AutoHandle::Get()
const {
301void AutoHandle::Reset() {
302 Reset(INVALID_HANDLE_VALUE);
305void AutoHandle::Reset(HANDLE handle) {
307 if (handle_ != handle) {
309 ::CloseHandle(handle_);
313 GTEST_CHECK_(!IsCloseable())
314 <<
"Resetting a valid handle to itself is likely a programmer error "
315 "and thus not allowed.";
319bool AutoHandle::IsCloseable()
const {
322 return handle_ !=
nullptr && handle_ != INVALID_HANDLE_VALUE;
325Notification::Notification()
326 : event_(::CreateEvent(nullptr,
330 GTEST_CHECK_(event_.Get() !=
nullptr);
333void Notification::Notify() {
334 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
337void Notification::WaitForNotification() {
339 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
343 : owner_thread_id_(0),
345 critical_section_init_phase_(0),
346 critical_section_(new CRITICAL_SECTION) {
347 ::InitializeCriticalSection(critical_section_);
353 if (type_ == kDynamic) {
354 ::DeleteCriticalSection(critical_section_);
355 delete critical_section_;
356 critical_section_ =
nullptr;
361 ThreadSafeLazyInit();
362 ::EnterCriticalSection(critical_section_);
363 owner_thread_id_ = ::GetCurrentThreadId();
366void Mutex::Unlock() {
367 ThreadSafeLazyInit();
371 owner_thread_id_ = 0;
372 ::LeaveCriticalSection(critical_section_);
377void Mutex::AssertHeld() {
378 ThreadSafeLazyInit();
379 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
380 <<
"The current thread is not holding the mutex @" <<
this;
394class MemoryIsNotDeallocated
397 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
398 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
401 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
404 ~MemoryIsNotDeallocated() {
406 _CrtSetDbgFlag(old_crtdbg_flag_);
410 int old_crtdbg_flag_;
412 GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
419void Mutex::ThreadSafeLazyInit() {
421 if (type_ == kStatic) {
423 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
427 owner_thread_id_ = 0;
431 MemoryIsNotDeallocated memory_is_not_deallocated;
433 critical_section_ =
new CRITICAL_SECTION;
435 ::InitializeCriticalSection(critical_section_);
438 GTEST_CHECK_(::InterlockedCompareExchange(
439 &critical_section_init_phase_, 2L, 1L) ==
445 while (::InterlockedCompareExchange(&critical_section_init_phase_,
459 <<
"Unexpected value of critical_section_init_phase_ "
460 <<
"while initializing a static mutex.";
467class ThreadWithParamSupport :
public ThreadWithParamBase {
469 static HANDLE CreateThread(Runnable* runnable,
470 Notification* thread_can_start) {
471 ThreadMainParam* param =
new ThreadMainParam(runnable, thread_can_start);
473 HANDLE thread_handle = ::CreateThread(
476 &ThreadWithParamSupport::ThreadMain,
480 GTEST_CHECK_(thread_handle !=
nullptr)
481 <<
"CreateThread failed with error " << ::GetLastError() <<
".";
482 if (thread_handle ==
nullptr) {
485 return thread_handle;
489 struct ThreadMainParam {
490 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
491 : runnable_(runnable),
492 thread_can_start_(thread_can_start) {
494 std::unique_ptr<Runnable> runnable_;
496 Notification* thread_can_start_;
499 static DWORD WINAPI ThreadMain(
void* ptr) {
501 std::unique_ptr<ThreadMainParam> param(
static_cast<ThreadMainParam*
>(ptr));
502 if (param->thread_can_start_ !=
nullptr)
503 param->thread_can_start_->WaitForNotification();
504 param->runnable_->Run();
509 ThreadWithParamSupport();
511 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
516ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
517 Notification* thread_can_start)
518 : thread_(ThreadWithParamSupport::CreateThread(runnable,
522ThreadWithParamBase::~ThreadWithParamBase() {
526void ThreadWithParamBase::Join() {
527 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
528 <<
"Failed to join the thread with error " << ::GetLastError() <<
".";
535class ThreadLocalRegistryImpl {
539 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
540 const ThreadLocalBase* thread_local_instance) {
542 MemoryIsNotDeallocated memory_is_not_deallocated;
544 DWORD current_thread = ::GetCurrentThreadId();
545 MutexLock lock(&mutex_);
546 ThreadIdToThreadLocals*
const thread_to_thread_locals =
547 GetThreadLocalsMapLocked();
548 ThreadIdToThreadLocals::iterator thread_local_pos =
549 thread_to_thread_locals->find(current_thread);
550 if (thread_local_pos == thread_to_thread_locals->end()) {
551 thread_local_pos = thread_to_thread_locals->insert(
552 std::make_pair(current_thread, ThreadLocalValues())).first;
553 StartWatcherThreadFor(current_thread);
555 ThreadLocalValues& thread_local_values = thread_local_pos->second;
556 ThreadLocalValues::iterator value_pos =
557 thread_local_values.find(thread_local_instance);
558 if (value_pos == thread_local_values.end()) {
561 .insert(std::make_pair(
562 thread_local_instance,
563 std::shared_ptr<ThreadLocalValueHolderBase>(
564 thread_local_instance->NewValueForCurrentThread())))
567 return value_pos->second.get();
570 static void OnThreadLocalDestroyed(
571 const ThreadLocalBase* thread_local_instance) {
572 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
576 MutexLock lock(&mutex_);
577 ThreadIdToThreadLocals*
const thread_to_thread_locals =
578 GetThreadLocalsMapLocked();
579 for (ThreadIdToThreadLocals::iterator it =
580 thread_to_thread_locals->begin();
581 it != thread_to_thread_locals->end();
583 ThreadLocalValues& thread_local_values = it->second;
584 ThreadLocalValues::iterator value_pos =
585 thread_local_values.find(thread_local_instance);
586 if (value_pos != thread_local_values.end()) {
587 value_holders.push_back(value_pos->second);
588 thread_local_values.erase(value_pos);
598 static void OnThreadExit(DWORD thread_id) {
599 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
600 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
604 MutexLock lock(&mutex_);
605 ThreadIdToThreadLocals*
const thread_to_thread_locals =
606 GetThreadLocalsMapLocked();
607 ThreadIdToThreadLocals::iterator thread_local_pos =
608 thread_to_thread_locals->find(thread_id);
609 if (thread_local_pos != thread_to_thread_locals->end()) {
610 ThreadLocalValues& thread_local_values = thread_local_pos->second;
611 for (ThreadLocalValues::iterator value_pos =
612 thread_local_values.begin();
613 value_pos != thread_local_values.end();
615 value_holders.push_back(value_pos->second);
617 thread_to_thread_locals->erase(thread_local_pos);
626 typedef std::map<
const ThreadLocalBase*,
627 std::shared_ptr<ThreadLocalValueHolderBase> >
631 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
635 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
637 static void StartWatcherThreadFor(DWORD thread_id) {
640 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
643 GTEST_CHECK_(thread !=
nullptr);
646 DWORD watcher_thread_id;
647 HANDLE watcher_thread = ::CreateThread(
650 &ThreadLocalRegistryImpl::WatcherThreadFunc,
651 reinterpret_cast<LPVOID
>(
new ThreadIdAndHandle(thread_id, thread)),
652 CREATE_SUSPENDED, &watcher_thread_id);
653 GTEST_CHECK_(watcher_thread !=
nullptr);
656 ::SetThreadPriority(watcher_thread,
657 ::GetThreadPriority(::GetCurrentThread()));
658 ::ResumeThread(watcher_thread);
659 ::CloseHandle(watcher_thread);
664 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
665 const ThreadIdAndHandle* tah =
666 reinterpret_cast<const ThreadIdAndHandle*
>(param);
668 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
669 OnThreadExit(tah->first);
670 ::CloseHandle(tah->second);
676 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
679 MemoryIsNotDeallocated memory_is_not_deallocated;
681 static ThreadIdToThreadLocals* map =
new ThreadIdToThreadLocals();
688 static Mutex thread_map_mutex_;
691Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
692Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
694ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
695 const ThreadLocalBase* thread_local_instance) {
696 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
697 thread_local_instance);
700void ThreadLocalRegistry::OnThreadLocalDestroyed(
701 const ThreadLocalBase* thread_local_instance) {
702 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
707#if GTEST_USES_POSIX_RE
717 regfree(&partial_regex_);
718 regfree(&full_regex_);
720 free(
const_cast<char*
>(pattern_));
724bool RE::FullMatch(
const char* str,
const RE& re) {
725 if (!re.is_valid_)
return false;
728 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
733bool RE::PartialMatch(
const char* str,
const RE& re) {
734 if (!re.is_valid_)
return false;
737 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
741void RE::Init(
const char* regex) {
742 pattern_ = posix::StrDup(regex);
746 const size_t full_regex_len = strlen(regex) + 10;
747 char*
const full_pattern =
new char[full_regex_len];
749 snprintf(full_pattern, full_regex_len,
"^(%s)$", regex);
750 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
760 const char*
const partial_regex = (*regex ==
'\0') ?
"()" : regex;
761 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
763 EXPECT_TRUE(is_valid_)
764 <<
"Regular expression \"" << regex
765 <<
"\" is not a valid POSIX Extended regular expression.";
767 delete[] full_pattern;
770#elif GTEST_USES_SIMPLE_RE
774bool IsInSet(
char ch,
const char* str) {
775 return ch !=
'\0' && strchr(str, ch) !=
nullptr;
781bool IsAsciiDigit(
char ch) {
return '0' <= ch && ch <=
'9'; }
782bool IsAsciiPunct(
char ch) {
783 return IsInSet(ch,
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
785bool IsRepeat(
char ch) {
return IsInSet(ch,
"?*+"); }
786bool IsAsciiWhiteSpace(
char ch) {
return IsInSet(ch,
" \f\n\r\t\v"); }
787bool IsAsciiWordChar(
char ch) {
788 return (
'a' <= ch && ch <=
'z') || (
'A' <= ch && ch <=
'Z') ||
789 (
'0' <= ch && ch <=
'9') || ch ==
'_';
793bool IsValidEscape(
char c) {
794 return (IsAsciiPunct(c) || IsInSet(c,
"dDfnrsStvwW"));
799bool AtomMatchesChar(
bool escaped,
char pattern_char,
char ch) {
801 switch (pattern_char) {
802 case 'd':
return IsAsciiDigit(ch);
803 case 'D':
return !IsAsciiDigit(ch);
804 case 'f':
return ch ==
'\f';
805 case 'n':
return ch ==
'\n';
806 case 'r':
return ch ==
'\r';
807 case 's':
return IsAsciiWhiteSpace(ch);
808 case 'S':
return !IsAsciiWhiteSpace(ch);
809 case 't':
return ch ==
'\t';
810 case 'v':
return ch ==
'\v';
811 case 'w':
return IsAsciiWordChar(ch);
812 case 'W':
return !IsAsciiWordChar(ch);
814 return IsAsciiPunct(pattern_char) && pattern_char == ch;
817 return (pattern_char ==
'.' && ch !=
'\n') || pattern_char == ch;
821static std::string FormatRegexSyntaxError(
const char* regex,
int index) {
822 return (Message() <<
"Syntax error at index " << index
823 <<
" in simple regular expression \"" << regex <<
"\": ").GetString();
828bool ValidateRegex(
const char* regex) {
829 if (regex ==
nullptr) {
830 ADD_FAILURE() <<
"NULL is not a valid simple regular expression.";
834 bool is_valid =
true;
837 bool prev_repeatable =
false;
838 for (
int i = 0; regex[i]; i++) {
839 if (regex[i] ==
'\\') {
841 if (regex[i] ==
'\0') {
842 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
843 <<
"'\\' cannot appear at the end.";
847 if (!IsValidEscape(regex[i])) {
848 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
849 <<
"invalid escape sequence \"\\" << regex[i] <<
"\".";
852 prev_repeatable =
true;
854 const char ch = regex[i];
856 if (ch ==
'^' && i > 0) {
857 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
858 <<
"'^' can only appear at the beginning.";
860 }
else if (ch ==
'$' && regex[i + 1] !=
'\0') {
861 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
862 <<
"'$' can only appear at the end.";
864 }
else if (IsInSet(ch,
"()[]{}|")) {
865 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
866 <<
"'" << ch <<
"' is unsupported.";
868 }
else if (IsRepeat(ch) && !prev_repeatable) {
869 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
870 <<
"'" << ch <<
"' can only follow a repeatable token.";
874 prev_repeatable = !IsInSet(ch,
"^$?*+");
888bool MatchRepetitionAndRegexAtHead(
889 bool escaped,
char c,
char repeat,
const char* regex,
891 const size_t min_count = (repeat ==
'+') ? 1 : 0;
892 const size_t max_count = (repeat ==
'?') ? 1 :
893 static_cast<size_t>(-1) - 1;
897 for (
size_t i = 0; i <= max_count; ++i) {
899 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
906 if (str[i] ==
'\0' || !AtomMatchesChar(escaped, c, str[i]))
915bool MatchRegexAtHead(
const char* regex,
const char* str) {
925 const bool escaped = *regex ==
'\\';
928 if (IsRepeat(regex[1])) {
932 return MatchRepetitionAndRegexAtHead(
933 escaped, regex[0], regex[1], regex + 2, str);
938 return (*str !=
'\0') && AtomMatchesChar(escaped, *regex, *str) &&
939 MatchRegexAtHead(regex + 1, str + 1);
951bool MatchRegexAnywhere(
const char* regex,
const char* str) {
952 if (regex ==
nullptr || str ==
nullptr)
return false;
955 return MatchRegexAtHead(regex + 1, str);
959 if (MatchRegexAtHead(regex, str))
961 }
while (*str++ !=
'\0');
968 free(
const_cast<char*
>(pattern_));
969 free(
const_cast<char*
>(full_pattern_));
973bool RE::FullMatch(
const char* str,
const RE& re) {
974 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
979bool RE::PartialMatch(
const char* str,
const RE& re) {
980 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
984void RE::Init(
const char* regex) {
985 pattern_ = full_pattern_ =
nullptr;
986 if (regex !=
nullptr) {
987 pattern_ = posix::StrDup(regex);
990 is_valid_ = ValidateRegex(regex);
996 const size_t len = strlen(regex);
1000 char* buffer =
static_cast<char*
>(malloc(len + 3));
1001 full_pattern_ = buffer;
1008 memcpy(buffer, regex, len);
1011 if (len == 0 || regex[len - 1] !=
'$')
1019const char kUnknownFile[] =
"unknown file";
1023GTEST_API_ ::std::string FormatFileLocation(
const char* file,
int line) {
1024 const std::string file_name(file ==
nullptr ? kUnknownFile : file);
1027 return file_name +
":";
1030 return file_name +
"(" + StreamableToString(line) +
"):";
1032 return file_name +
":" + StreamableToString(line) +
":";
1041GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
1042 const char* file,
int line) {
1043 const std::string file_name(file ==
nullptr ? kUnknownFile : file);
1048 return file_name +
":" + StreamableToString(line);
1051GTestLog::GTestLog(GTestLogSeverity severity,
const char* file,
int line)
1052 : severity_(severity) {
1053 const char*
const marker =
1054 severity == GTEST_INFO ?
"[ INFO ]" :
1055 severity == GTEST_WARNING ?
"[WARNING]" :
1056 severity == GTEST_ERROR ?
"[ ERROR ]" :
"[ FATAL ]";
1057 GetStream() << ::std::endl << marker <<
" "
1058 << FormatFileLocation(file, line).c_str() <<
": ";
1062GTestLog::~GTestLog() {
1063 GetStream() << ::std::endl;
1064 if (severity_ == GTEST_FATAL) {
1072GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
1074#if GTEST_HAS_STREAM_REDIRECTION
1077class CapturedStream {
1080 explicit CapturedStream(
int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
1081# if GTEST_OS_WINDOWS
1082 char temp_dir_path[MAX_PATH + 1] = {
'\0' };
1083 char temp_file_path[MAX_PATH + 1] = {
'\0' };
1085 ::GetTempPathA(
sizeof(temp_dir_path), temp_dir_path);
1086 const UINT success = ::GetTempFileNameA(temp_dir_path,
1090 GTEST_CHECK_(success != 0)
1091 <<
"Unable to create a temporary file in " << temp_dir_path;
1092 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
1093 GTEST_CHECK_(captured_fd != -1) <<
"Unable to open temporary file "
1095 filename_ = temp_file_path;
1101# if GTEST_OS_LINUX_ANDROID
1113 char name_template[] =
"/data/local/tmp/gtest_captured_stream.XXXXXX";
1115 char name_template[] =
"/tmp/captured_stream.XXXXXX";
1117 const int captured_fd = mkstemp(name_template);
1118 if (captured_fd == -1) {
1120 <<
"Failed to create tmp file " << name_template
1121 <<
" for test; does the test have access to the /tmp directory?";
1123 filename_ = name_template;
1126 dup2(captured_fd, fd_);
1131 remove(filename_.c_str());
1134 std::string GetCapturedString() {
1135 if (uncaptured_fd_ != -1) {
1138 dup2(uncaptured_fd_, fd_);
1139 close(uncaptured_fd_);
1140 uncaptured_fd_ = -1;
1143 FILE*
const file = posix::FOpen(filename_.c_str(),
"r");
1144 if (file ==
nullptr) {
1145 GTEST_LOG_(FATAL) <<
"Failed to open tmp file " << filename_
1146 <<
" for capturing stream.";
1148 const std::string content = ReadEntireFile(file);
1149 posix::FClose(file);
1157 ::std::string filename_;
1159 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
1162GTEST_DISABLE_MSC_DEPRECATED_POP_()
1164static CapturedStream* g_captured_stderr =
nullptr;
1165static CapturedStream* g_captured_stdout =
nullptr;
1168static
void CaptureStream(
int fd, const
char* stream_name,
1169 CapturedStream** stream) {
1170 if (*stream !=
nullptr) {
1171 GTEST_LOG_(FATAL) <<
"Only one " << stream_name
1172 <<
" capturer can exist at a time.";
1174 *stream =
new CapturedStream(fd);
1178static std::string GetCapturedStream(CapturedStream** captured_stream) {
1179 const std::string content = (*captured_stream)->GetCapturedString();
1181 delete *captured_stream;
1182 *captured_stream =
nullptr;
1188void CaptureStdout() {
1189 CaptureStream(kStdOutFileno,
"stdout", &g_captured_stdout);
1193void CaptureStderr() {
1194 CaptureStream(kStdErrFileno,
"stderr", &g_captured_stderr);
1198std::string GetCapturedStdout() {
1199 return GetCapturedStream(&g_captured_stdout);
1203std::string GetCapturedStderr() {
1204 return GetCapturedStream(&g_captured_stderr);
1213size_t GetFileSize(FILE* file) {
1214 fseek(file, 0, SEEK_END);
1215 return static_cast<size_t>(ftell(file));
1218std::string ReadEntireFile(FILE* file) {
1219 const size_t file_size = GetFileSize(file);
1220 char*
const buffer =
new char[file_size];
1222 size_t bytes_last_read = 0;
1223 size_t bytes_read = 0;
1225 fseek(file, 0, SEEK_SET);
1230 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
1231 bytes_read += bytes_last_read;
1232 }
while (bytes_last_read > 0 && bytes_read < file_size);
1234 const std::string content(buffer, bytes_read);
1240#if GTEST_HAS_DEATH_TEST
1241static const std::vector<std::string>* g_injected_test_argvs =
1244std::vector<std::string> GetInjectableArgvs() {
1245 if (g_injected_test_argvs !=
nullptr) {
1246 return *g_injected_test_argvs;
1251void SetInjectableArgvs(
const std::vector<std::string>* new_argvs) {
1252 if (g_injected_test_argvs != new_argvs)
delete g_injected_test_argvs;
1253 g_injected_test_argvs = new_argvs;
1256void SetInjectableArgvs(
const std::vector<std::string>& new_argvs) {
1258 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
1261void ClearInjectableArgvs() {
1262 delete g_injected_test_argvs;
1263 g_injected_test_argvs =
nullptr;
1267#if GTEST_OS_WINDOWS_MOBILE
1271 TerminateProcess(GetCurrentProcess(), 1);
1279static std::string FlagToEnvVar(
const char* flag) {
1280 const std::string full_flag =
1281 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
1284 for (
size_t i = 0; i != full_flag.length(); i++) {
1285 env_var << ToUpper(full_flag.c_str()[i]);
1288 return env_var.GetString();
1294bool ParseInt32(
const Message& src_text,
const char* str, int32_t* value) {
1296 char* end =
nullptr;
1297 const long long_value = strtol(str, &end, 10);
1303 msg <<
"WARNING: " << src_text
1304 <<
" is expected to be a 32-bit integer, but actually"
1305 <<
" has value \"" << str <<
"\".\n";
1306 printf(
"%s", msg.GetString().c_str());
1312 const auto result =
static_cast<int32_t
>(long_value);
1313 if (long_value == LONG_MAX || long_value == LONG_MIN ||
1316 result != long_value
1320 msg <<
"WARNING: " << src_text
1321 <<
" is expected to be a 32-bit integer, but actually"
1322 <<
" has value " << str <<
", which overflows.\n";
1323 printf(
"%s", msg.GetString().c_str());
1336bool BoolFromGTestEnv(
const char* flag,
bool default_value) {
1337#if defined(GTEST_GET_BOOL_FROM_ENV_)
1338 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1340 const std::string env_var = FlagToEnvVar(flag);
1341 const char*
const string_value = posix::GetEnv(env_var.c_str());
1342 return string_value ==
nullptr ? default_value
1343 : strcmp(string_value,
"0") != 0;
1350int32_t Int32FromGTestEnv(
const char* flag, int32_t default_value) {
1351#if defined(GTEST_GET_INT32_FROM_ENV_)
1352 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1354 const std::string env_var = FlagToEnvVar(flag);
1355 const char*
const string_value = posix::GetEnv(env_var.c_str());
1356 if (string_value ==
nullptr) {
1358 return default_value;
1361 int32_t result = default_value;
1362 if (!ParseInt32(Message() <<
"Environment variable " << env_var,
1363 string_value, &result)) {
1364 printf(
"The default value %s is used.\n",
1365 (Message() << default_value).GetString().c_str());
1367 return default_value;
1382std::string OutputFlagAlsoCheckEnvVar(){
1383 std::string default_value_for_output_flag =
"";
1384 const char* xml_output_file_env = posix::GetEnv(
"XML_OUTPUT_FILE");
1385 if (
nullptr != xml_output_file_env) {
1386 default_value_for_output_flag = std::string(
"xml:") + xml_output_file_env;
1388 return default_value_for_output_flag;
1393const char* StringFromGTestEnv(
const char* flag,
const char* default_value) {
1394#if defined(GTEST_GET_STRING_FROM_ENV_)
1395 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1397 const std::string env_var = FlagToEnvVar(flag);
1398 const char*
const value = posix::GetEnv(env_var.c_str());
1399 return value ==
nullptr ? default_value : value;