1 // Copyright 2008, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
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
13 // distribution.
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.
17 //
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.
29 
30 #include "gtest/internal/gtest-port.h"
31 
32 #include <limits.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <fstream>
37 #include <memory>
38 
39 #if GTEST_OS_WINDOWS
40 #include <windows.h>
41 #include <io.h>
42 #include <sys/stat.h>
43 #include <map>  // Used in ThreadLocal.
44 #ifdef _MSC_VER
45 #include <crtdbg.h>
46 #endif  // _MSC_VER
47 #else
48 #include <unistd.h>
49 #endif  // GTEST_OS_WINDOWS
50 
51 #if GTEST_OS_MAC
52 #include <mach/mach_init.h>
53 #include <mach/task.h>
54 #include <mach/vm_map.h>
55 #endif  // GTEST_OS_MAC
56 
57 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
58     GTEST_OS_NETBSD || GTEST_OS_OPENBSD
59 #include <sys/sysctl.h>
60 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
61 #include <sys/user.h>
62 #endif
63 #endif
64 
65 #if GTEST_OS_QNX
66 #include <devctl.h>
67 #include <fcntl.h>
68 #include <sys/procfs.h>
69 #endif  // GTEST_OS_QNX
70 
71 #if GTEST_OS_AIX
72 #include <procinfo.h>
73 #include <sys/types.h>
74 #endif  // GTEST_OS_AIX
75 
76 #if GTEST_OS_FUCHSIA
77 #include <zircon/process.h>
78 #include <zircon/syscalls.h>
79 #endif  // GTEST_OS_FUCHSIA
80 
81 #include "gtest/gtest-spi.h"
82 #include "gtest/gtest-message.h"
83 #include "gtest/internal/gtest-internal.h"
84 #include "gtest/internal/gtest-string.h"
85 #include "src/gtest-internal-inl.h"
86 
87 namespace testing {
88 namespace internal {
89 
90 #if defined(_MSC_VER) || defined(__BORLANDC__)
91 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
92 const int kStdOutFileno = 1;
93 const int kStdErrFileno = 2;
94 #else
95 const int kStdOutFileno = STDOUT_FILENO;
96 const int kStdErrFileno = STDERR_FILENO;
97 #endif  // _MSC_VER
98 
99 #if GTEST_OS_LINUX
100 
101 namespace {
102 template <typename T>
ReadProcFileField(const std::string & filename,int field)103 T ReadProcFileField(const std::string& filename, int field) {
104   std::string dummy;
105   std::ifstream file(filename.c_str());
106   while (field-- > 0) {
107     file >> dummy;
108   }
109   T output = 0;
110   file >> output;
111   return output;
112 }
113 }  // namespace
114 
115 // Returns the number of active threads, or 0 when there is an error.
GetThreadCount()116 size_t GetThreadCount() {
117   const std::string filename =
118       (Message() << "/proc/" << getpid() << "/stat").GetString();
119   return ReadProcFileField<size_t>(filename, 19);
120 }
121 
122 #elif GTEST_OS_MAC
123 
GetThreadCount()124 size_t GetThreadCount() {
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) {
130     // task_threads allocates resources in thread_list and we need to free them
131     // to avoid leaks.
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);
135   } else {
136     return 0;
137   }
138 }
139 
140 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
141     GTEST_OS_NETBSD
142 
143 #if GTEST_OS_NETBSD
144 #undef KERN_PROC
145 #define KERN_PROC KERN_PROC2
146 #define kinfo_proc kinfo_proc2
147 #endif
148 
149 #if GTEST_OS_DRAGONFLY
150 #define KP_NLWP(kp) (kp.kp_nthreads)
151 #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
152 #define KP_NLWP(kp) (kp.ki_numthreads)
153 #elif GTEST_OS_NETBSD
154 #define KP_NLWP(kp) (kp.p_nlwps)
155 #endif
156 
157 // Returns the number of threads running in the process, or 0 to indicate that
158 // we cannot detect it.
GetThreadCount()159 size_t GetThreadCount() {
160   int mib[] = {
161     CTL_KERN,
162     KERN_PROC,
163     KERN_PROC_PID,
164     getpid(),
165 #if GTEST_OS_NETBSD
166     sizeof(struct kinfo_proc),
167     1,
168 #endif
169   };
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)) {
174     return 0;
175   }
176   return static_cast<size_t>(KP_NLWP(info));
177 }
178 #elif GTEST_OS_OPENBSD
179 
180 // Returns the number of threads running in the process, or 0 to indicate that
181 // we cannot detect it.
GetThreadCount()182 size_t GetThreadCount() {
183   int mib[] = {
184       CTL_KERN,
185       KERN_PROC,
186       KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
187       getpid(),
188       sizeof(struct kinfo_proc),
189       0,
190   };
191   u_int miblen = sizeof(mib) / sizeof(mib[0]);
192 
193   // get number of structs
194   size_t size;
195   if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
196     return 0;
197   }
198   mib[5] = size / mib[4];
199 
200   // populate array of structs
201   struct kinfo_proc info[mib[5]];
202   if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
203     return 0;
204   }
205 
206   // exclude empty members
207   int nthreads = 0;
208   for (int i = 0; i < size / mib[4]; i++) {
209     if (info[i].p_tid != -1) nthreads++;
210   }
211   return nthreads;
212 }
213 
214 #elif GTEST_OS_QNX
215 
216 // Returns the number of threads running in the process, or 0 to indicate that
217 // we cannot detect it.
GetThreadCount()218 size_t GetThreadCount() {
219   const int fd = open("/proc/self/as", O_RDONLY);
220   if (fd < 0) {
221     return 0;
222   }
223   procfs_info process_info;
224   const int status =
225       devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
226   close(fd);
227   if (status == EOK) {
228     return static_cast<size_t>(process_info.num_threads);
229   } else {
230     return 0;
231   }
232 }
233 
234 #elif GTEST_OS_AIX
235 
GetThreadCount()236 size_t GetThreadCount() {
237   struct procentry64 entry;
238   pid_t pid = getpid();
239   int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
240   if (status == 1) {
241     return entry.pi_thcount;
242   } else {
243     return 0;
244   }
245 }
246 
247 #elif GTEST_OS_FUCHSIA
248 
GetThreadCount()249 size_t GetThreadCount() {
250   int dummy_buffer;
251   size_t avail;
252   zx_status_t status =
253       zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS,
254                          &dummy_buffer, 0, nullptr, &avail);
255   if (status == ZX_OK) {
256     return avail;
257   } else {
258     return 0;
259   }
260 }
261 
262 #else
263 
GetThreadCount()264 size_t GetThreadCount() {
265   // There's no portable way to detect the number of threads, so we just
266   // return 0 to indicate that we cannot detect it.
267   return 0;
268 }
269 
270 #endif  // GTEST_OS_LINUX
271 
272 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
273 
SleepMilliseconds(int n)274 void SleepMilliseconds(int n) { ::Sleep(static_cast<DWORD>(n)); }
275 
AutoHandle()276 AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
277 
AutoHandle(Handle handle)278 AutoHandle::AutoHandle(Handle handle) : handle_(handle) {}
279 
~AutoHandle()280 AutoHandle::~AutoHandle() { Reset(); }
281 
Get() const282 AutoHandle::Handle AutoHandle::Get() const { return handle_; }
283 
Reset()284 void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); }
285 
Reset(HANDLE handle)286 void AutoHandle::Reset(HANDLE handle) {
287   // Resetting with the same handle we already own is invalid.
288   if (handle_ != handle) {
289     if (IsCloseable()) {
290       ::CloseHandle(handle_);
291     }
292     handle_ = handle;
293   } else {
294     GTEST_CHECK_(!IsCloseable())
295         << "Resetting a valid handle to itself is likely a programmer error "
296            "and thus not allowed.";
297   }
298 }
299 
IsCloseable() const300 bool AutoHandle::IsCloseable() const {
301   // Different Windows APIs may use either of these values to represent an
302   // invalid handle.
303   return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
304 }
305 
Notification()306 Notification::Notification()
307     : event_(::CreateEvent(nullptr,     // Default security attributes.
308                            TRUE,        // Do not reset automatically.
309                            FALSE,       // Initially unset.
310                            nullptr)) {  // Anonymous event.
311   GTEST_CHECK_(event_.Get() != nullptr);
312 }
313 
Notify()314 void Notification::Notify() { GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); }
315 
WaitForNotification()316 void Notification::WaitForNotification() {
317   GTEST_CHECK_(::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
318 }
319 
Mutex()320 Mutex::Mutex()
321     : owner_thread_id_(0),
322       type_(kDynamic),
323       critical_section_init_phase_(0),
324       critical_section_(new CRITICAL_SECTION) {
325   ::InitializeCriticalSection(critical_section_);
326 }
327 
~Mutex()328 Mutex::~Mutex() {
329   // Static mutexes are leaked intentionally. It is not thread-safe to try
330   // to clean them up.
331   if (type_ == kDynamic) {
332     ::DeleteCriticalSection(critical_section_);
333     delete critical_section_;
334     critical_section_ = nullptr;
335   }
336 }
337 
Lock()338 void Mutex::Lock() {
339   ThreadSafeLazyInit();
340   ::EnterCriticalSection(critical_section_);
341   owner_thread_id_ = ::GetCurrentThreadId();
342 }
343 
Unlock()344 void Mutex::Unlock() {
345   ThreadSafeLazyInit();
346   // We don't protect writing to owner_thread_id_ here, as it's the
347   // caller's responsibility to ensure that the current thread holds the
348   // mutex when this is called.
349   owner_thread_id_ = 0;
350   ::LeaveCriticalSection(critical_section_);
351 }
352 
353 // Does nothing if the current thread holds the mutex. Otherwise, crashes
354 // with high probability.
AssertHeld()355 void Mutex::AssertHeld() {
356   ThreadSafeLazyInit();
357   GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
358       << "The current thread is not holding the mutex @" << this;
359 }
360 
361 namespace {
362 
363 #ifdef _MSC_VER
364 // Use the RAII idiom to flag mem allocs that are intentionally never
365 // deallocated. The motivation is to silence the false positive mem leaks
366 // that are reported by the debug version of MS's CRT which can only detect
367 // if an alloc is missing a matching deallocation.
368 // Example:
369 //    MemoryIsNotDeallocated memory_is_not_deallocated;
370 //    critical_section_ = new CRITICAL_SECTION;
371 //
372 class MemoryIsNotDeallocated {
373  public:
MemoryIsNotDeallocated()374   MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
375     old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
376     // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
377     // doesn't report mem leak if there's no matching deallocation.
378     _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
379   }
380 
~MemoryIsNotDeallocated()381   ~MemoryIsNotDeallocated() {
382     // Restore the original _CRTDBG_ALLOC_MEM_DF flag
383     _CrtSetDbgFlag(old_crtdbg_flag_);
384   }
385 
386  private:
387   int old_crtdbg_flag_;
388 
389   GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
390 };
391 #endif  // _MSC_VER
392 
393 }  // namespace
394 
395 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
ThreadSafeLazyInit()396 void Mutex::ThreadSafeLazyInit() {
397   // Dynamic mutexes are initialized in the constructor.
398   if (type_ == kStatic) {
399     switch (
400         ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
401       case 0:
402         // If critical_section_init_phase_ was 0 before the exchange, we
403         // are the first to test it and need to perform the initialization.
404         owner_thread_id_ = 0;
405         {
406 // Use RAII to flag that following mem alloc is never deallocated.
407 #ifdef _MSC_VER
408           MemoryIsNotDeallocated memory_is_not_deallocated;
409 #endif  // _MSC_VER
410           critical_section_ = new CRITICAL_SECTION;
411         }
412         ::InitializeCriticalSection(critical_section_);
413         // Updates the critical_section_init_phase_ to 2 to signal
414         // initialization complete.
415         GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_,
416                                                   2L, 1L) == 1L);
417         break;
418       case 1:
419         // Somebody else is already initializing the mutex; spin until they
420         // are done.
421         while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L,
422                                             2L) != 2L) {
423           // Possibly yields the rest of the thread's time slice to other
424           // threads.
425           ::Sleep(0);
426         }
427         break;
428 
429       case 2:
430         break;  // The mutex is already initialized and ready for use.
431 
432       default:
433         GTEST_CHECK_(false)
434             << "Unexpected value of critical_section_init_phase_ "
435             << "while initializing a static mutex.";
436     }
437   }
438 }
439 
440 namespace {
441 
442 class ThreadWithParamSupport : public ThreadWithParamBase {
443  public:
CreateThread(Runnable * runnable,Notification * thread_can_start)444   static HANDLE CreateThread(Runnable* runnable,
445                              Notification* thread_can_start) {
446     ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
447     DWORD thread_id;
448     HANDLE thread_handle = ::CreateThread(
449         nullptr,  // Default security.
450         0,        // Default stack size.
451         &ThreadWithParamSupport::ThreadMain,
452         param,        // Parameter to ThreadMainStatic
453         0x0,          // Default creation flags.
454         &thread_id);  // Need a valid pointer for the call to work under Win98.
455     GTEST_CHECK_(thread_handle != nullptr) << "CreateThread failed with error "
456                                            << ::GetLastError() << ".";
457     if (thread_handle == nullptr) {
458       delete param;
459     }
460     return thread_handle;
461   }
462 
463  private:
464   struct ThreadMainParam {
ThreadMainParamtesting::internal::__anon17f608370311::ThreadWithParamSupport::ThreadMainParam465     ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
466         : runnable_(runnable), thread_can_start_(thread_can_start) {}
467     std::unique_ptr<Runnable> runnable_;
468     // Does not own.
469     Notification* thread_can_start_;
470   };
471 
ThreadMain(void * ptr)472   static DWORD WINAPI ThreadMain(void* ptr) {
473     // Transfers ownership.
474     std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
475     if (param->thread_can_start_ != nullptr)
476       param->thread_can_start_->WaitForNotification();
477     param->runnable_->Run();
478     return 0;
479   }
480 
481   // Prohibit instantiation.
482   ThreadWithParamSupport();
483 
484   GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
485 };
486 
487 }  // namespace
488 
ThreadWithParamBase(Runnable * runnable,Notification * thread_can_start)489 ThreadWithParamBase::ThreadWithParamBase(Runnable* runnable,
490                                          Notification* thread_can_start)
491     : thread_(
492           ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {}
493 
~ThreadWithParamBase()494 ThreadWithParamBase::~ThreadWithParamBase() { Join(); }
495 
Join()496 void ThreadWithParamBase::Join() {
497   GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
498       << "Failed to join the thread with error " << ::GetLastError() << ".";
499 }
500 
501 // Maps a thread to a set of ThreadIdToThreadLocals that have values
502 // instantiated on that thread and notifies them when the thread exits.  A
503 // ThreadLocal instance is expected to persist until all threads it has
504 // values on have terminated.
505 class ThreadLocalRegistryImpl {
506  public:
507   // Registers thread_local_instance as having value on the current thread.
508   // Returns a value that can be used to identify the thread from other threads.
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)509   static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
510       const ThreadLocalBase* thread_local_instance) {
511     DWORD current_thread = ::GetCurrentThreadId();
512     MutexLock lock(&mutex_);
513     ThreadIdToThreadLocals* const thread_to_thread_locals =
514         GetThreadLocalsMapLocked();
515     ThreadIdToThreadLocals::iterator thread_local_pos =
516         thread_to_thread_locals->find(current_thread);
517     if (thread_local_pos == thread_to_thread_locals->end()) {
518       thread_local_pos =
519           thread_to_thread_locals
520               ->insert(std::make_pair(current_thread, ThreadLocalValues()))
521               .first;
522       StartWatcherThreadFor(current_thread);
523     }
524     ThreadLocalValues& thread_local_values = thread_local_pos->second;
525     ThreadLocalValues::iterator value_pos =
526         thread_local_values.find(thread_local_instance);
527     if (value_pos == thread_local_values.end()) {
528       value_pos =
529           thread_local_values
530               .insert(std::make_pair(
531                   thread_local_instance,
532                   std::shared_ptr<ThreadLocalValueHolderBase>(
533                       thread_local_instance->NewValueForCurrentThread())))
534               .first;
535     }
536     return value_pos->second.get();
537   }
538 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)539   static void OnThreadLocalDestroyed(
540       const ThreadLocalBase* thread_local_instance) {
541     std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
542     // Clean up the ThreadLocalValues data structure while holding the lock, but
543     // defer the destruction of the ThreadLocalValueHolderBases.
544     {
545       MutexLock lock(&mutex_);
546       ThreadIdToThreadLocals* const thread_to_thread_locals =
547           GetThreadLocalsMapLocked();
548       for (ThreadIdToThreadLocals::iterator it =
549                thread_to_thread_locals->begin();
550            it != thread_to_thread_locals->end(); ++it) {
551         ThreadLocalValues& thread_local_values = it->second;
552         ThreadLocalValues::iterator value_pos =
553             thread_local_values.find(thread_local_instance);
554         if (value_pos != thread_local_values.end()) {
555           value_holders.push_back(value_pos->second);
556           thread_local_values.erase(value_pos);
557           // This 'if' can only be successful at most once, so theoretically we
558           // could break out of the loop here, but we don't bother doing so.
559         }
560       }
561     }
562     // Outside the lock, let the destructor for 'value_holders' deallocate the
563     // ThreadLocalValueHolderBases.
564   }
565 
OnThreadExit(DWORD thread_id)566   static void OnThreadExit(DWORD thread_id) {
567     GTEST_CHECK_(thread_id != 0) << ::GetLastError();
568     std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
569     // Clean up the ThreadIdToThreadLocals data structure while holding the
570     // lock, but defer the destruction of the ThreadLocalValueHolderBases.
571     {
572       MutexLock lock(&mutex_);
573       ThreadIdToThreadLocals* const thread_to_thread_locals =
574           GetThreadLocalsMapLocked();
575       ThreadIdToThreadLocals::iterator thread_local_pos =
576           thread_to_thread_locals->find(thread_id);
577       if (thread_local_pos != thread_to_thread_locals->end()) {
578         ThreadLocalValues& thread_local_values = thread_local_pos->second;
579         for (ThreadLocalValues::iterator value_pos =
580                  thread_local_values.begin();
581              value_pos != thread_local_values.end(); ++value_pos) {
582           value_holders.push_back(value_pos->second);
583         }
584         thread_to_thread_locals->erase(thread_local_pos);
585       }
586     }
587     // Outside the lock, let the destructor for 'value_holders' deallocate the
588     // ThreadLocalValueHolderBases.
589   }
590 
591  private:
592   // In a particular thread, maps a ThreadLocal object to its value.
593   typedef std::map<const ThreadLocalBase*,
594                    std::shared_ptr<ThreadLocalValueHolderBase> >
595       ThreadLocalValues;
596   // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
597   // thread's ID.
598   typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
599 
600   // Holds the thread id and thread handle that we pass from
601   // StartWatcherThreadFor to WatcherThreadFunc.
602   typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
603 
StartWatcherThreadFor(DWORD thread_id)604   static void StartWatcherThreadFor(DWORD thread_id) {
605     // The returned handle will be kept in thread_map and closed by
606     // watcher_thread in WatcherThreadFunc.
607     HANDLE thread =
608         ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id);
609     GTEST_CHECK_(thread != nullptr);
610     // We need to pass a valid thread ID pointer into CreateThread for it
611     // to work correctly under Win98.
612     DWORD watcher_thread_id;
613     HANDLE watcher_thread = ::CreateThread(
614         nullptr,  // Default security.
615         0,        // Default stack size
616         &ThreadLocalRegistryImpl::WatcherThreadFunc,
617         reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
618         CREATE_SUSPENDED, &watcher_thread_id);
619     GTEST_CHECK_(watcher_thread != nullptr);
620     // Give the watcher thread the same priority as ours to avoid being
621     // blocked by it.
622     ::SetThreadPriority(watcher_thread,
623                         ::GetThreadPriority(::GetCurrentThread()));
624     ::ResumeThread(watcher_thread);
625     ::CloseHandle(watcher_thread);
626   }
627 
628   // Monitors exit from a given thread and notifies those
629   // ThreadIdToThreadLocals about thread termination.
WatcherThreadFunc(LPVOID param)630   static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
631     const ThreadIdAndHandle* tah =
632         reinterpret_cast<const ThreadIdAndHandle*>(param);
633     GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
634     OnThreadExit(tah->first);
635     ::CloseHandle(tah->second);
636     delete tah;
637     return 0;
638   }
639 
640   // Returns map of thread local instances.
GetThreadLocalsMapLocked()641   static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
642     mutex_.AssertHeld();
643 #ifdef _MSC_VER
644     MemoryIsNotDeallocated memory_is_not_deallocated;
645 #endif  // _MSC_VER
646     static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
647     return map;
648   }
649 
650   // Protects access to GetThreadLocalsMapLocked() and its return value.
651   static Mutex mutex_;
652   // Protects access to GetThreadMapLocked() and its return value.
653   static Mutex thread_map_mutex_;
654 };
655 
656 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
657 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
658 
GetValueOnCurrentThread(const ThreadLocalBase * thread_local_instance)659 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
660     const ThreadLocalBase* thread_local_instance) {
661   return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
662       thread_local_instance);
663 }
664 
OnThreadLocalDestroyed(const ThreadLocalBase * thread_local_instance)665 void ThreadLocalRegistry::OnThreadLocalDestroyed(
666     const ThreadLocalBase* thread_local_instance) {
667   ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
668 }
669 
670 #endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
671 
672 #if GTEST_USES_POSIX_RE
673 
674 // Implements RE.  Currently only needed for death tests.
675 
~RE()676 RE::~RE() {
677   if (is_valid_) {
678     // regfree'ing an invalid regex might crash because the content
679     // of the regex is undefined. Since the regex's are essentially
680     // the same, one cannot be valid (or invalid) without the other
681     // being so too.
682     regfree(&partial_regex_);
683     regfree(&full_regex_);
684   }
685   free(const_cast<char*>(pattern_));
686 }
687 
688 // Returns true if and only if regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)689 bool RE::FullMatch(const char* str, const RE& re) {
690   if (!re.is_valid_) return false;
691 
692   regmatch_t match;
693   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
694 }
695 
696 // Returns true if and only if regular expression re matches a substring of
697 // str (including str itself).
PartialMatch(const char * str,const RE & re)698 bool RE::PartialMatch(const char* str, const RE& re) {
699   if (!re.is_valid_) return false;
700 
701   regmatch_t match;
702   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
703 }
704 
705 // Initializes an RE from its string representation.
Init(const char * regex)706 void RE::Init(const char* regex) {
707   pattern_ = posix::StrDup(regex);
708 
709   // Reserves enough bytes to hold the regular expression used for a
710   // full match.
711   const size_t full_regex_len = strlen(regex) + 10;
712   char* const full_pattern = new char[full_regex_len];
713 
714   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
715   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
716   // We want to call regcomp(&partial_regex_, ...) even if the
717   // previous expression returns false.  Otherwise partial_regex_ may
718   // not be properly initialized can may cause trouble when it's
719   // freed.
720   //
721   // Some implementation of POSIX regex (e.g. on at least some
722   // versions of Cygwin) doesn't accept the empty string as a valid
723   // regex.  We change it to an equivalent form "()" to be safe.
724   if (is_valid_) {
725     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
726     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
727   }
728   EXPECT_TRUE(is_valid_)
729       << "Regular expression \"" << regex
730       << "\" is not a valid POSIX Extended regular expression.";
731 
732   delete[] full_pattern;
733 }
734 
735 #elif GTEST_USES_SIMPLE_RE
736 
737 // Returns true if and only if ch appears anywhere in str (excluding the
738 // terminating '\0' character).
IsInSet(char ch,const char * str)739 bool IsInSet(char ch, const char* str) {
740   return ch != '\0' && strchr(str, ch) != nullptr;
741 }
742 
743 // Returns true if and only if ch belongs to the given classification.
744 // Unlike similar functions in <ctype.h>, these aren't affected by the
745 // current locale.
IsAsciiDigit(char ch)746 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)747 bool IsAsciiPunct(char ch) {
748   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
749 }
IsRepeat(char ch)750 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)751 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)752 bool IsAsciiWordChar(char ch) {
753   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
754          ('0' <= ch && ch <= '9') || ch == '_';
755 }
756 
757 // Returns true if and only if "\\c" is a supported escape sequence.
IsValidEscape(char c)758 bool IsValidEscape(char c) {
759   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
760 }
761 
762 // Returns true if and only if the given atom (specified by escaped and
763 // pattern) matches ch.  The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)764 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
765   if (escaped) {  // "\\p" where p is pattern_char.
766     switch (pattern_char) {
767       case 'd':
768         return IsAsciiDigit(ch);
769       case 'D':
770         return !IsAsciiDigit(ch);
771       case 'f':
772         return ch == '\f';
773       case 'n':
774         return ch == '\n';
775       case 'r':
776         return ch == '\r';
777       case 's':
778         return IsAsciiWhiteSpace(ch);
779       case 'S':
780         return !IsAsciiWhiteSpace(ch);
781       case 't':
782         return ch == '\t';
783       case 'v':
784         return ch == '\v';
785       case 'w':
786         return IsAsciiWordChar(ch);
787       case 'W':
788         return !IsAsciiWordChar(ch);
789     }
790     return IsAsciiPunct(pattern_char) && pattern_char == ch;
791   }
792 
793   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
794 }
795 
796 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)797 static std::string FormatRegexSyntaxError(const char* regex, int index) {
798   return (Message() << "Syntax error at index " << index
799                     << " in simple regular expression \"" << regex << "\": ")
800       .GetString();
801 }
802 
803 // Generates non-fatal failures and returns false if regex is invalid;
804 // otherwise returns true.
ValidateRegex(const char * regex)805 bool ValidateRegex(const char* regex) {
806   if (regex == nullptr) {
807     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
808     return false;
809   }
810 
811   bool is_valid = true;
812 
813   // True if and only if ?, *, or + can follow the previous atom.
814   bool prev_repeatable = false;
815   for (int i = 0; regex[i]; i++) {
816     if (regex[i] == '\\') {  // An escape sequence
817       i++;
818       if (regex[i] == '\0') {
819         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
820                       << "'\\' cannot appear at the end.";
821         return false;
822       }
823 
824       if (!IsValidEscape(regex[i])) {
825         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
826                       << "invalid escape sequence \"\\" << regex[i] << "\".";
827         is_valid = false;
828       }
829       prev_repeatable = true;
830     } else {  // Not an escape sequence.
831       const char ch = regex[i];
832 
833       if (ch == '^' && i > 0) {
834         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
835                       << "'^' can only appear at the beginning.";
836         is_valid = false;
837       } else if (ch == '$' && regex[i + 1] != '\0') {
838         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
839                       << "'$' can only appear at the end.";
840         is_valid = false;
841       } else if (IsInSet(ch, "()[]{}|")) {
842         ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
843                       << "' is unsupported.";
844         is_valid = false;
845       } else if (IsRepeat(ch) && !prev_repeatable) {
846         ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
847                       << "' can only follow a repeatable token.";
848         is_valid = false;
849       }
850 
851       prev_repeatable = !IsInSet(ch, "^$?*+");
852     }
853   }
854 
855   return is_valid;
856 }
857 
858 // Matches a repeated regex atom followed by a valid simple regular
859 // expression.  The regex atom is defined as c if escaped is false,
860 // or \c otherwise.  repeat is the repetition meta character (?, *,
861 // or +).  The behavior is undefined if str contains too many
862 // characters to be indexable by size_t, in which case the test will
863 // probably time out anyway.  We are fine with this limitation as
864 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)865 bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
866                                    const char* regex, const char* str) {
867   const size_t min_count = (repeat == '+') ? 1 : 0;
868   const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
869   // We cannot call numeric_limits::max() as it conflicts with the
870   // max() macro on Windows.
871 
872   for (size_t i = 0; i <= max_count; ++i) {
873     // We know that the atom matches each of the first i characters in str.
874     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
875       // We have enough matches at the head, and the tail matches too.
876       // Since we only care about *whether* the pattern matches str
877       // (as opposed to *how* it matches), there is no need to find a
878       // greedy match.
879       return true;
880     }
881     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
882   }
883   return false;
884 }
885 
886 // Returns true if and only if regex matches a prefix of str. regex must
887 // be a valid simple regular expression and not start with "^", or the
888 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)889 bool MatchRegexAtHead(const char* regex, const char* str) {
890   if (*regex == '\0')  // An empty regex matches a prefix of anything.
891     return true;
892 
893   // "$" only matches the end of a string.  Note that regex being
894   // valid guarantees that there's nothing after "$" in it.
895   if (*regex == '$') return *str == '\0';
896 
897   // Is the first thing in regex an escape sequence?
898   const bool escaped = *regex == '\\';
899   if (escaped) ++regex;
900   if (IsRepeat(regex[1])) {
901     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
902     // here's an indirect recursion.  It terminates as the regex gets
903     // shorter in each recursion.
904     return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
905                                          str);
906   } else {
907     // regex isn't empty, isn't "$", and doesn't start with a
908     // repetition.  We match the first atom of regex with the first
909     // character of str and recurse.
910     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
911            MatchRegexAtHead(regex + 1, str + 1);
912   }
913 }
914 
915 // Returns true if and only if regex matches any substring of str.  regex must
916 // be a valid simple regular expression, or the result is undefined.
917 //
918 // The algorithm is recursive, but the recursion depth doesn't exceed
919 // the regex length, so we won't need to worry about running out of
920 // stack space normally.  In rare cases the time complexity can be
921 // exponential with respect to the regex length + the string length,
922 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)923 bool MatchRegexAnywhere(const char* regex, const char* str) {
924   if (regex == nullptr || str == nullptr) return false;
925 
926   if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
927 
928   // A successful match can be anywhere in str.
929   do {
930     if (MatchRegexAtHead(regex, str)) return true;
931   } while (*str++ != '\0');
932   return false;
933 }
934 
935 // Implements the RE class.
936 
~RE()937 RE::~RE() {
938   free(const_cast<char*>(pattern_));
939   free(const_cast<char*>(full_pattern_));
940 }
941 
942 // Returns true if and only if regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)943 bool RE::FullMatch(const char* str, const RE& re) {
944   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
945 }
946 
947 // Returns true if and only if regular expression re matches a substring of
948 // str (including str itself).
PartialMatch(const char * str,const RE & re)949 bool RE::PartialMatch(const char* str, const RE& re) {
950   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
951 }
952 
953 // Initializes an RE from its string representation.
Init(const char * regex)954 void RE::Init(const char* regex) {
955   pattern_ = full_pattern_ = nullptr;
956   if (regex != nullptr) {
957     pattern_ = posix::StrDup(regex);
958   }
959 
960   is_valid_ = ValidateRegex(regex);
961   if (!is_valid_) {
962     // No need to calculate the full pattern when the regex is invalid.
963     return;
964   }
965 
966   const size_t len = strlen(regex);
967   // Reserves enough bytes to hold the regular expression used for a
968   // full match: we need space to prepend a '^', append a '$', and
969   // terminate the string with '\0'.
970   char* buffer = static_cast<char*>(malloc(len + 3));
971   full_pattern_ = buffer;
972 
973   if (*regex != '^')
974     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
975 
976   // We don't use snprintf or strncpy, as they trigger a warning when
977   // compiled with VC++ 8.0.
978   memcpy(buffer, regex, len);
979   buffer += len;
980 
981   if (len == 0 || regex[len - 1] != '$')
982     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
983 
984   *buffer = '\0';
985 }
986 
987 #endif  // GTEST_USES_POSIX_RE
988 
989 const char kUnknownFile[] = "unknown file";
990 
991 // Formats a source file path and a line number as they would appear
992 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)993 GTEST_API_::std::string FormatFileLocation(const char* file, int line) {
994   const std::string file_name(file == nullptr ? kUnknownFile : file);
995 
996   if (line < 0) {
997     return file_name + ":";
998   }
999 #ifdef _MSC_VER
1000   return file_name + "(" + StreamableToString(line) + "):";
1001 #else
1002   return file_name + ":" + StreamableToString(line) + ":";
1003 #endif  // _MSC_VER
1004 }
1005 
1006 // Formats a file location for compiler-independent XML output.
1007 // Although this function is not platform dependent, we put it next to
1008 // FormatFileLocation in order to contrast the two functions.
1009 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
1010 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)1011 GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char* file,
1012                                                               int line) {
1013   const std::string file_name(file == nullptr ? kUnknownFile : file);
1014 
1015   if (line < 0)
1016     return file_name;
1017   else
1018     return file_name + ":" + StreamableToString(line);
1019 }
1020 
GTestLog(GTestLogSeverity severity,const char * file,int line)1021 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
1022     : severity_(severity) {
1023   const char* const marker =
1024       severity == GTEST_INFO
1025           ? "[  INFO ]"
1026           : severity == GTEST_WARNING
1027                 ? "[WARNING]"
1028                 : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
1029   GetStream() << ::std::endl
1030               << marker << " " << FormatFileLocation(file, line).c_str()
1031               << ": ";
1032 }
1033 
1034 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()1035 GTestLog::~GTestLog() {
1036   GetStream() << ::std::endl;
1037   if (severity_ == GTEST_FATAL) {
1038     fflush(stderr);
1039     posix::Abort();
1040   }
1041 }
1042 
1043 // Disable Microsoft deprecation warnings for POSIX functions called from
1044 // this class (creat, dup, dup2, and close)
1045 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
1046 
1047 #if GTEST_HAS_STREAM_REDIRECTION
1048 
1049 // Object that captures an output stream (stdout/stderr).
1050 class CapturedStream {
1051  public:
1052   // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)1053   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
1054 #if GTEST_OS_WINDOWS
1055     char temp_dir_path[MAX_PATH + 1] = {'\0'};   // NOLINT
1056     char temp_file_path[MAX_PATH + 1] = {'\0'};  // NOLINT
1057 
1058     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
1059     const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
1060                                             0,  // Generate unique file name.
1061                                             temp_file_path);
1062     GTEST_CHECK_(success != 0) << "Unable to create a temporary file in "
1063                                << temp_dir_path;
1064     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
1065     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
1066                                     << temp_file_path;
1067     filename_ = temp_file_path;
1068 #else
1069 // There's no guarantee that a test has write access to the current
1070 // directory, so we create the temporary file in the /tmp directory
1071 // instead. We use /tmp on most systems, and /sdcard on Android.
1072 // That's because Android doesn't have /tmp.
1073 #if GTEST_OS_LINUX_ANDROID
1074     // Note: Android applications are expected to call the framework's
1075     // Context.getExternalStorageDirectory() method through JNI to get
1076     // the location of the world-writable SD Card directory. However,
1077     // this requires a Context handle, which cannot be retrieved
1078     // globally from native code. Doing so also precludes running the
1079     // code as part of a regular standalone executable, which doesn't
1080     // run in a Dalvik process (e.g. when running it through 'adb shell').
1081     //
1082     // The location /data/local/tmp is directly accessible from native code.
1083     // '/sdcard' and other variants cannot be relied on, as they are not
1084     // guaranteed to be mounted, or may have a delay in mounting.
1085     char name_template[] = "/data/local/tmp/gtest_captured_stream.XXXXXX";
1086 #else
1087     char name_template[] = "/tmp/captured_stream.XXXXXX";
1088 #endif  // GTEST_OS_LINUX_ANDROID
1089     const int captured_fd = mkstemp(name_template);
1090     if (captured_fd == -1) {
1091       GTEST_LOG_(WARNING)
1092           << "Failed to create tmp file " << name_template
1093           << " for test; does the test have access to the /tmp directory?";
1094     }
1095     filename_ = name_template;
1096 #endif  // GTEST_OS_WINDOWS
1097     fflush(nullptr);
1098     dup2(captured_fd, fd_);
1099     close(captured_fd);
1100   }
1101 
~CapturedStream()1102   ~CapturedStream() { remove(filename_.c_str()); }
1103 
GetCapturedString()1104   std::string GetCapturedString() {
1105     if (uncaptured_fd_ != -1) {
1106       // Restores the original stream.
1107       fflush(nullptr);
1108       dup2(uncaptured_fd_, fd_);
1109       close(uncaptured_fd_);
1110       uncaptured_fd_ = -1;
1111     }
1112 
1113     FILE* const file = posix::FOpen(filename_.c_str(), "r");
1114     if (file == nullptr) {
1115       GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
1116                         << " for capturing stream.";
1117     }
1118     const std::string content = ReadEntireFile(file);
1119     posix::FClose(file);
1120     return content;
1121   }
1122 
1123  private:
1124   const int fd_;  // A stream to capture.
1125   int uncaptured_fd_;
1126   // Name of the temporary file holding the stderr output.
1127   ::std::string filename_;
1128 
1129   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
1130 };
1131 
1132 GTEST_DISABLE_MSC_DEPRECATED_POP_()
1133 
1134 static CapturedStream* g_captured_stderr = nullptr;
1135 static CapturedStream* g_captured_stdout = nullptr;
1136 
1137 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)1138 static void CaptureStream(int fd, const char* stream_name,
1139                           CapturedStream** stream) {
1140   if (*stream != nullptr) {
1141     GTEST_LOG_(FATAL) << "Only one " << stream_name
1142                       << " capturer can exist at a time.";
1143   }
1144   *stream = new CapturedStream(fd);
1145 }
1146 
1147 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)1148 static std::string GetCapturedStream(CapturedStream** captured_stream) {
1149   const std::string content = (*captured_stream)->GetCapturedString();
1150 
1151   delete *captured_stream;
1152   *captured_stream = nullptr;
1153 
1154   return content;
1155 }
1156 
1157 // Starts capturing stdout.
CaptureStdout()1158 void CaptureStdout() {
1159   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
1160 }
1161 
1162 // Starts capturing stderr.
CaptureStderr()1163 void CaptureStderr() {
1164   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
1165 }
1166 
1167 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()1168 std::string GetCapturedStdout() {
1169   return GetCapturedStream(&g_captured_stdout);
1170 }
1171 
1172 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()1173 std::string GetCapturedStderr() {
1174   return GetCapturedStream(&g_captured_stderr);
1175 }
1176 
1177 #endif  // GTEST_HAS_STREAM_REDIRECTION
1178 
GetFileSize(FILE * file)1179 size_t GetFileSize(FILE* file) {
1180   fseek(file, 0, SEEK_END);
1181   return static_cast<size_t>(ftell(file));
1182 }
1183 
ReadEntireFile(FILE * file)1184 std::string ReadEntireFile(FILE* file) {
1185   const size_t file_size = GetFileSize(file);
1186   char* const buffer = new char[file_size];
1187 
1188   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
1189   size_t bytes_read = 0;       // # of bytes read so far
1190 
1191   fseek(file, 0, SEEK_SET);
1192 
1193   // Keeps reading the file until we cannot read further or the
1194   // pre-determined file size is reached.
1195   do {
1196     bytes_last_read =
1197         fread(buffer + bytes_read, 1, file_size - bytes_read, file);
1198     bytes_read += bytes_last_read;
1199   } while (bytes_last_read > 0 && bytes_read < file_size);
1200 
1201   const std::string content(buffer, bytes_read);
1202   delete[] buffer;
1203 
1204   return content;
1205 }
1206 
1207 #if GTEST_HAS_DEATH_TEST
1208 static const std::vector<std::string>* g_injected_test_argvs =
1209     nullptr;  // Owned.
1210 
GetInjectableArgvs()1211 std::vector<std::string> GetInjectableArgvs() {
1212   if (g_injected_test_argvs != nullptr) {
1213     return *g_injected_test_argvs;
1214   }
1215   return GetArgvs();
1216 }
1217 
SetInjectableArgvs(const std::vector<std::string> * new_argvs)1218 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
1219   if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
1220   g_injected_test_argvs = new_argvs;
1221 }
1222 
SetInjectableArgvs(const std::vector<std::string> & new_argvs)1223 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
1224   SetInjectableArgvs(
1225       new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
1226 }
1227 
ClearInjectableArgvs()1228 void ClearInjectableArgvs() {
1229   delete g_injected_test_argvs;
1230   g_injected_test_argvs = nullptr;
1231 }
1232 #endif  // GTEST_HAS_DEATH_TEST
1233 
1234 #if GTEST_OS_WINDOWS_MOBILE
1235 namespace posix {
Abort()1236 void Abort() {
1237   DebugBreak();
1238   TerminateProcess(GetCurrentProcess(), 1);
1239 }
1240 }  // namespace posix
1241 #endif  // GTEST_OS_WINDOWS_MOBILE
1242 
1243 // Returns the name of the environment variable corresponding to the
1244 // given flag.  For example, FlagToEnvVar("foo") will return
1245 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)1246 static std::string FlagToEnvVar(const char* flag) {
1247   const std::string full_flag =
1248       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
1249 
1250   Message env_var;
1251   for (size_t i = 0; i != full_flag.length(); i++) {
1252     env_var << ToUpper(full_flag.c_str()[i]);
1253   }
1254 
1255   return env_var.GetString();
1256 }
1257 
1258 // Parses 'str' for a 32-bit signed integer.  If successful, writes
1259 // the result to *value and returns true; otherwise leaves *value
1260 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)1261 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
1262   // Parses the environment variable as a decimal integer.
1263   char* end = nullptr;
1264   const long long_value = strtol(str, &end, 10);  // NOLINT
1265 
1266   // Has strtol() consumed all characters in the string?
1267   if (*end != '\0') {
1268     // No - an invalid character was encountered.
1269     Message msg;
1270     msg << "WARNING: " << src_text
1271         << " is expected to be a 32-bit integer, but actually"
1272         << " has value \"" << str << "\".\n";
1273     printf("%s", msg.GetString().c_str());
1274     fflush(stdout);
1275     return false;
1276   }
1277 
1278   // Is the parsed value in the range of an Int32?
1279   const Int32 result = static_cast<Int32>(long_value);
1280   if (long_value == LONG_MAX || long_value == LONG_MIN ||
1281       // The parsed value overflows as a long.  (strtol() returns
1282       // LONG_MAX or LONG_MIN when the input overflows.)
1283       result != long_value
1284       // The parsed value overflows as an Int32.
1285       ) {
1286     Message msg;
1287     msg << "WARNING: " << src_text
1288         << " is expected to be a 32-bit integer, but actually"
1289         << " has value " << str << ", which overflows.\n";
1290     printf("%s", msg.GetString().c_str());
1291     fflush(stdout);
1292     return false;
1293   }
1294 
1295   *value = result;
1296   return true;
1297 }
1298 
1299 // Reads and returns the Boolean environment variable corresponding to
1300 // the given flag; if it's not set, returns default_value.
1301 //
1302 // The value is considered true if and only if it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)1303 bool BoolFromGTestEnv(const char* flag, bool default_value) {
1304 #if defined(GTEST_GET_BOOL_FROM_ENV_)
1305   return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
1306 #else
1307   const std::string env_var = FlagToEnvVar(flag);
1308   const char* const string_value = posix::GetEnv(env_var.c_str());
1309   return string_value == nullptr ? default_value
1310                                  : strcmp(string_value, "0") != 0;
1311 #endif  // defined(GTEST_GET_BOOL_FROM_ENV_)
1312 }
1313 
1314 // Reads and returns a 32-bit integer stored in the environment
1315 // variable corresponding to the given flag; if it isn't set or
1316 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)1317 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
1318 #if defined(GTEST_GET_INT32_FROM_ENV_)
1319   return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
1320 #else
1321   const std::string env_var = FlagToEnvVar(flag);
1322   const char* const string_value = posix::GetEnv(env_var.c_str());
1323   if (string_value == nullptr) {
1324     // The environment variable is not set.
1325     return default_value;
1326   }
1327 
1328   Int32 result = default_value;
1329   if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
1330                   &result)) {
1331     printf("The default value %s is used.\n",
1332            (Message() << default_value).GetString().c_str());
1333     fflush(stdout);
1334     return default_value;
1335   }
1336 
1337   return result;
1338 #endif  // defined(GTEST_GET_INT32_FROM_ENV_)
1339 }
1340 
1341 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
1342 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
1343 // system.  The value of XML_OUTPUT_FILE is a filename without the
1344 // "xml:" prefix of GTEST_OUTPUT.
1345 // Note that this is meant to be called at the call site so it does
1346 // not check that the flag is 'output'
1347 // In essence this checks an env variable called XML_OUTPUT_FILE
1348 // and if it is set we prepend "xml:" to its value, if it not set we return ""
OutputFlagAlsoCheckEnvVar()1349 std::string OutputFlagAlsoCheckEnvVar() {
1350   std::string default_value_for_output_flag = "";
1351   const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
1352   if (nullptr != xml_output_file_env) {
1353     default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
1354   }
1355   return default_value_for_output_flag;
1356 }
1357 
1358 // Reads and returns the string environment variable corresponding to
1359 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)1360 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
1361 #if defined(GTEST_GET_STRING_FROM_ENV_)
1362   return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
1363 #else
1364   const std::string env_var = FlagToEnvVar(flag);
1365   const char* const value = posix::GetEnv(env_var.c_str());
1366   return value == nullptr ? default_value : value;
1367 #endif  // defined(GTEST_GET_STRING_FROM_ENV_)
1368 }
1369 
1370 }  // namespace internal
1371 }  // namespace testing
1372