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