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