duckstation

duckstation, but archived from the revision just before upstream changed it to a proprietary software project, this version is the libre one
git clone https://git.neptards.moe/u3shit/duckstation.git
Log | Files | Refs | README | LICENSE

gtest-port.cc (46564B)


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