Blame googletest/src/gtest-port.cc

Packit bd1cd8
// Copyright 2008, Google Inc.
Packit bd1cd8
// All rights reserved.
Packit bd1cd8
//
Packit bd1cd8
// Redistribution and use in source and binary forms, with or without
Packit bd1cd8
// modification, are permitted provided that the following conditions are
Packit bd1cd8
// met:
Packit bd1cd8
//
Packit bd1cd8
//     * Redistributions of source code must retain the above copyright
Packit bd1cd8
// notice, this list of conditions and the following disclaimer.
Packit bd1cd8
//     * Redistributions in binary form must reproduce the above
Packit bd1cd8
// copyright notice, this list of conditions and the following disclaimer
Packit bd1cd8
// in the documentation and/or other materials provided with the
Packit bd1cd8
// distribution.
Packit bd1cd8
//     * Neither the name of Google Inc. nor the names of its
Packit bd1cd8
// contributors may be used to endorse or promote products derived from
Packit bd1cd8
// this software without specific prior written permission.
Packit bd1cd8
//
Packit bd1cd8
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
Packit bd1cd8
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
Packit bd1cd8
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
Packit bd1cd8
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
Packit bd1cd8
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
Packit bd1cd8
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
Packit bd1cd8
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
Packit bd1cd8
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
Packit bd1cd8
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
Packit bd1cd8
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
Packit bd1cd8
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Packit bd1cd8
//
Packit bd1cd8
// Author: wan@google.com (Zhanyong Wan)
Packit bd1cd8
Packit bd1cd8
#include "gtest/internal/gtest-port.h"
Packit bd1cd8
Packit bd1cd8
#include <limits.h>
Packit bd1cd8
#include <stdlib.h>
Packit bd1cd8
#include <stdio.h>
Packit bd1cd8
#include <string.h>
Packit bd1cd8
#include <fstream>
Packit bd1cd8
Packit bd1cd8
#if GTEST_OS_WINDOWS
Packit bd1cd8
# include <windows.h>
Packit bd1cd8
# include <io.h>
Packit bd1cd8
# include <sys/stat.h>
Packit bd1cd8
# include <map>  // Used in ThreadLocal.
Packit bd1cd8
#else
Packit bd1cd8
# include <unistd.h>
Packit bd1cd8
#endif  // GTEST_OS_WINDOWS
Packit bd1cd8
Packit bd1cd8
#if GTEST_OS_MAC
Packit bd1cd8
# include <mach/mach_init.h>
Packit bd1cd8
# include <mach/task.h>
Packit bd1cd8
# include <mach/vm_map.h>
Packit bd1cd8
#endif  // GTEST_OS_MAC
Packit bd1cd8
Packit bd1cd8
#if GTEST_OS_QNX
Packit bd1cd8
# include <devctl.h>
Packit bd1cd8
# include <fcntl.h>
Packit bd1cd8
# include <sys/procfs.h>
Packit bd1cd8
#endif  // GTEST_OS_QNX
Packit bd1cd8
Packit bd1cd8
#if GTEST_OS_AIX
Packit bd1cd8
# include <procinfo.h>
Packit bd1cd8
# include <sys/types.h>
Packit bd1cd8
#endif  // GTEST_OS_AIX
Packit bd1cd8
Packit bd1cd8
#include "gtest/gtest-spi.h"
Packit bd1cd8
#include "gtest/gtest-message.h"
Packit bd1cd8
#include "gtest/internal/gtest-internal.h"
Packit bd1cd8
#include "gtest/internal/gtest-string.h"
Packit bd1cd8
Packit bd1cd8
// Indicates that this translation unit is part of Google Test's
Packit bd1cd8
// implementation.  It must come before gtest-internal-inl.h is
Packit bd1cd8
// included, or there will be a compiler error.  This trick exists to
Packit bd1cd8
// prevent the accidental inclusion of gtest-internal-inl.h in the
Packit bd1cd8
// user's code.
Packit bd1cd8
#define GTEST_IMPLEMENTATION_ 1
Packit bd1cd8
#include "src/gtest-internal-inl.h"
Packit bd1cd8
#undef GTEST_IMPLEMENTATION_
Packit bd1cd8
Packit bd1cd8
namespace testing {
Packit bd1cd8
namespace internal {
Packit bd1cd8
Packit bd1cd8
#if defined(_MSC_VER) || defined(__BORLANDC__)
Packit bd1cd8
// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
Packit bd1cd8
const int kStdOutFileno = 1;
Packit bd1cd8
const int kStdErrFileno = 2;
Packit bd1cd8
#else
Packit bd1cd8
const int kStdOutFileno = STDOUT_FILENO;
Packit bd1cd8
const int kStdErrFileno = STDERR_FILENO;
Packit bd1cd8
#endif  // _MSC_VER
Packit bd1cd8
Packit bd1cd8
#if GTEST_OS_LINUX
Packit bd1cd8
Packit bd1cd8
namespace {
Packit bd1cd8
template <typename T>
Packit bd1cd8
T ReadProcFileField(const string& filename, int field) {
Packit bd1cd8
  std::string dummy;
Packit bd1cd8
  std::ifstream file(filename.c_str());
Packit bd1cd8
  while (field-- > 0) {
Packit bd1cd8
    file >> dummy;
Packit bd1cd8
  }
Packit bd1cd8
  T output = 0;
Packit bd1cd8
  file >> output;
Packit bd1cd8
  return output;
Packit bd1cd8
}
Packit bd1cd8
}  // namespace
Packit bd1cd8
Packit bd1cd8
// Returns the number of active threads, or 0 when there is an error.
Packit bd1cd8
size_t GetThreadCount() {
Packit bd1cd8
  const string filename =
Packit bd1cd8
      (Message() << "/proc/" << getpid() << "/stat").GetString();
Packit bd1cd8
  return ReadProcFileField<int>(filename, 19);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#elif GTEST_OS_MAC
Packit bd1cd8
Packit bd1cd8
size_t GetThreadCount() {
Packit bd1cd8
  const task_t task = mach_task_self();
Packit bd1cd8
  mach_msg_type_number_t thread_count;
Packit bd1cd8
  thread_act_array_t thread_list;
Packit bd1cd8
  const kern_return_t status = task_threads(task, &thread_list, &thread_count);
Packit bd1cd8
  if (status == KERN_SUCCESS) {
Packit bd1cd8
    // task_threads allocates resources in thread_list and we need to free them
Packit bd1cd8
    // to avoid leaks.
Packit bd1cd8
    vm_deallocate(task,
Packit bd1cd8
                  reinterpret_cast<vm_address_t>(thread_list),
Packit bd1cd8
                  sizeof(thread_t) * thread_count);
Packit bd1cd8
    return static_cast<size_t>(thread_count);
Packit bd1cd8
  } else {
Packit bd1cd8
    return 0;
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#elif GTEST_OS_QNX
Packit bd1cd8
Packit bd1cd8
// Returns the number of threads running in the process, or 0 to indicate that
Packit bd1cd8
// we cannot detect it.
Packit bd1cd8
size_t GetThreadCount() {
Packit bd1cd8
  const int fd = open("/proc/self/as", O_RDONLY);
Packit bd1cd8
  if (fd < 0) {
Packit bd1cd8
    return 0;
Packit bd1cd8
  }
Packit bd1cd8
  procfs_info process_info;
Packit bd1cd8
  const int status =
Packit bd1cd8
      devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
Packit bd1cd8
  close(fd);
Packit bd1cd8
  if (status == EOK) {
Packit bd1cd8
    return static_cast<size_t>(process_info.num_threads);
Packit bd1cd8
  } else {
Packit bd1cd8
    return 0;
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#elif GTEST_OS_AIX
Packit bd1cd8
Packit bd1cd8
size_t GetThreadCount() {
Packit bd1cd8
  struct procentry64 entry;
Packit bd1cd8
  pid_t pid = getpid();
Packit bd1cd8
  int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
Packit bd1cd8
  if (status == 1) {
Packit bd1cd8
    return entry.pi_thcount;
Packit bd1cd8
  } else {
Packit bd1cd8
    return 0;
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#else
Packit bd1cd8
Packit bd1cd8
size_t GetThreadCount() {
Packit bd1cd8
  // There's no portable way to detect the number of threads, so we just
Packit bd1cd8
  // return 0 to indicate that we cannot detect it.
Packit bd1cd8
  return 0;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#endif  // GTEST_OS_LINUX
Packit bd1cd8
Packit bd1cd8
#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
Packit bd1cd8
Packit bd1cd8
void SleepMilliseconds(int n) {
Packit bd1cd8
  ::Sleep(n);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
AutoHandle::AutoHandle()
Packit bd1cd8
    : handle_(INVALID_HANDLE_VALUE) {}
Packit bd1cd8
Packit bd1cd8
AutoHandle::AutoHandle(Handle handle)
Packit bd1cd8
    : handle_(handle) {}
Packit bd1cd8
Packit bd1cd8
AutoHandle::~AutoHandle() {
Packit bd1cd8
  Reset();
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
AutoHandle::Handle AutoHandle::Get() const {
Packit bd1cd8
  return handle_;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void AutoHandle::Reset() {
Packit bd1cd8
  Reset(INVALID_HANDLE_VALUE);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void AutoHandle::Reset(HANDLE handle) {
Packit bd1cd8
  // Resetting with the same handle we already own is invalid.
Packit bd1cd8
  if (handle_ != handle) {
Packit bd1cd8
    if (IsCloseable()) {
Packit bd1cd8
      ::CloseHandle(handle_);
Packit bd1cd8
    }
Packit bd1cd8
    handle_ = handle;
Packit bd1cd8
  } else {
Packit bd1cd8
    GTEST_CHECK_(!IsCloseable())
Packit bd1cd8
        << "Resetting a valid handle to itself is likely a programmer error "
Packit bd1cd8
            "and thus not allowed.";
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
bool AutoHandle::IsCloseable() const {
Packit bd1cd8
  // Different Windows APIs may use either of these values to represent an
Packit bd1cd8
  // invalid handle.
Packit bd1cd8
  return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
Notification::Notification()
Packit bd1cd8
    : event_(::CreateEvent(NULL,   // Default security attributes.
Packit bd1cd8
                           TRUE,   // Do not reset automatically.
Packit bd1cd8
                           FALSE,  // Initially unset.
Packit bd1cd8
                           NULL)) {  // Anonymous event.
Packit bd1cd8
  GTEST_CHECK_(event_.Get() != NULL);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void Notification::Notify() {
Packit bd1cd8
  GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void Notification::WaitForNotification() {
Packit bd1cd8
  GTEST_CHECK_(
Packit bd1cd8
      ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
Mutex::Mutex()
Packit bd1cd8
    : owner_thread_id_(0),
Packit bd1cd8
      type_(kDynamic),
Packit bd1cd8
      critical_section_init_phase_(0),
Packit bd1cd8
      critical_section_(new CRITICAL_SECTION) {
Packit bd1cd8
  ::InitializeCriticalSection(critical_section_);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
Mutex::~Mutex() {
Packit bd1cd8
  // Static mutexes are leaked intentionally. It is not thread-safe to try
Packit bd1cd8
  // to clean them up.
Packit bd1cd8
  // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
Packit bd1cd8
  // nothing to clean it up but is available only on Vista and later.
Packit bd1cd8
  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
Packit bd1cd8
  if (type_ == kDynamic) {
Packit bd1cd8
    ::DeleteCriticalSection(critical_section_);
Packit bd1cd8
    delete critical_section_;
Packit bd1cd8
    critical_section_ = NULL;
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void Mutex::Lock() {
Packit bd1cd8
  ThreadSafeLazyInit();
Packit bd1cd8
  ::EnterCriticalSection(critical_section_);
Packit bd1cd8
  owner_thread_id_ = ::GetCurrentThreadId();
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void Mutex::Unlock() {
Packit bd1cd8
  ThreadSafeLazyInit();
Packit bd1cd8
  // We don't protect writing to owner_thread_id_ here, as it's the
Packit bd1cd8
  // caller's responsibility to ensure that the current thread holds the
Packit bd1cd8
  // mutex when this is called.
Packit bd1cd8
  owner_thread_id_ = 0;
Packit bd1cd8
  ::LeaveCriticalSection(critical_section_);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Does nothing if the current thread holds the mutex. Otherwise, crashes
Packit bd1cd8
// with high probability.
Packit bd1cd8
void Mutex::AssertHeld() {
Packit bd1cd8
  ThreadSafeLazyInit();
Packit bd1cd8
  GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
Packit bd1cd8
      << "The current thread is not holding the mutex @" << this;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Initializes owner_thread_id_ and critical_section_ in static mutexes.
Packit bd1cd8
void Mutex::ThreadSafeLazyInit() {
Packit bd1cd8
  // Dynamic mutexes are initialized in the constructor.
Packit bd1cd8
  if (type_ == kStatic) {
Packit bd1cd8
    switch (
Packit bd1cd8
        ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
Packit bd1cd8
      case 0:
Packit bd1cd8
        // If critical_section_init_phase_ was 0 before the exchange, we
Packit bd1cd8
        // are the first to test it and need to perform the initialization.
Packit bd1cd8
        owner_thread_id_ = 0;
Packit bd1cd8
        critical_section_ = new CRITICAL_SECTION;
Packit bd1cd8
        ::InitializeCriticalSection(critical_section_);
Packit bd1cd8
        // Updates the critical_section_init_phase_ to 2 to signal
Packit bd1cd8
        // initialization complete.
Packit bd1cd8
        GTEST_CHECK_(::InterlockedCompareExchange(
Packit bd1cd8
                          &critical_section_init_phase_, 2L, 1L) ==
Packit bd1cd8
                      1L);
Packit bd1cd8
        break;
Packit bd1cd8
      case 1:
Packit bd1cd8
        // Somebody else is already initializing the mutex; spin until they
Packit bd1cd8
        // are done.
Packit bd1cd8
        while (::InterlockedCompareExchange(&critical_section_init_phase_,
Packit bd1cd8
                                            2L,
Packit bd1cd8
                                            2L) != 2L) {
Packit bd1cd8
          // Possibly yields the rest of the thread's time slice to other
Packit bd1cd8
          // threads.
Packit bd1cd8
          ::Sleep(0);
Packit bd1cd8
        }
Packit bd1cd8
        break;
Packit bd1cd8
Packit bd1cd8
      case 2:
Packit bd1cd8
        break;  // The mutex is already initialized and ready for use.
Packit bd1cd8
Packit bd1cd8
      default:
Packit bd1cd8
        GTEST_CHECK_(false)
Packit bd1cd8
            << "Unexpected value of critical_section_init_phase_ "
Packit bd1cd8
            << "while initializing a static mutex.";
Packit bd1cd8
    }
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
namespace {
Packit bd1cd8
Packit bd1cd8
class ThreadWithParamSupport : public ThreadWithParamBase {
Packit bd1cd8
 public:
Packit bd1cd8
  static HANDLE CreateThread(Runnable* runnable,
Packit bd1cd8
                             Notification* thread_can_start) {
Packit bd1cd8
    ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
Packit bd1cd8
    DWORD thread_id;
Packit bd1cd8
    // TODO(yukawa): Consider to use _beginthreadex instead.
Packit bd1cd8
    HANDLE thread_handle = ::CreateThread(
Packit bd1cd8
        NULL,    // Default security.
Packit bd1cd8
        0,       // Default stack size.
Packit bd1cd8
        &ThreadWithParamSupport::ThreadMain,
Packit bd1cd8
        param,   // Parameter to ThreadMainStatic
Packit bd1cd8
        0x0,     // Default creation flags.
Packit bd1cd8
        &thread_id);  // Need a valid pointer for the call to work under Win98.
Packit bd1cd8
    GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
Packit bd1cd8
                                        << ::GetLastError() << ".";
Packit bd1cd8
    if (thread_handle == NULL) {
Packit bd1cd8
      delete param;
Packit bd1cd8
    }
Packit bd1cd8
    return thread_handle;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
 private:
Packit bd1cd8
  struct ThreadMainParam {
Packit bd1cd8
    ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
Packit bd1cd8
        : runnable_(runnable),
Packit bd1cd8
          thread_can_start_(thread_can_start) {
Packit bd1cd8
    }
Packit bd1cd8
    scoped_ptr<Runnable> runnable_;
Packit bd1cd8
    // Does not own.
Packit bd1cd8
    Notification* thread_can_start_;
Packit bd1cd8
  };
Packit bd1cd8
Packit bd1cd8
  static DWORD WINAPI ThreadMain(void* ptr) {
Packit bd1cd8
    // Transfers ownership.
Packit bd1cd8
    scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
Packit bd1cd8
    if (param->thread_can_start_ != NULL)
Packit bd1cd8
      param->thread_can_start_->WaitForNotification();
Packit bd1cd8
    param->runnable_->Run();
Packit bd1cd8
    return 0;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Prohibit instantiation.
Packit bd1cd8
  ThreadWithParamSupport();
Packit bd1cd8
Packit bd1cd8
  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
}  // namespace
Packit bd1cd8
Packit bd1cd8
ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
Packit bd1cd8
                                         Notification* thread_can_start)
Packit bd1cd8
      : thread_(ThreadWithParamSupport::CreateThread(runnable,
Packit bd1cd8
                                                     thread_can_start)) {
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
ThreadWithParamBase::~ThreadWithParamBase() {
Packit bd1cd8
  Join();
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void ThreadWithParamBase::Join() {
Packit bd1cd8
  GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
Packit bd1cd8
      << "Failed to join the thread with error " << ::GetLastError() << ".";
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Maps a thread to a set of ThreadIdToThreadLocals that have values
Packit bd1cd8
// instantiated on that thread and notifies them when the thread exits.  A
Packit bd1cd8
// ThreadLocal instance is expected to persist until all threads it has
Packit bd1cd8
// values on have terminated.
Packit bd1cd8
class ThreadLocalRegistryImpl {
Packit bd1cd8
 public:
Packit bd1cd8
  // Registers thread_local_instance as having value on the current thread.
Packit bd1cd8
  // Returns a value that can be used to identify the thread from other threads.
Packit bd1cd8
  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
Packit bd1cd8
      const ThreadLocalBase* thread_local_instance) {
Packit bd1cd8
    DWORD current_thread = ::GetCurrentThreadId();
Packit bd1cd8
    MutexLock lock(&mutex_);
Packit bd1cd8
    ThreadIdToThreadLocals* const thread_to_thread_locals =
Packit bd1cd8
        GetThreadLocalsMapLocked();
Packit bd1cd8
    ThreadIdToThreadLocals::iterator thread_local_pos =
Packit bd1cd8
        thread_to_thread_locals->find(current_thread);
Packit bd1cd8
    if (thread_local_pos == thread_to_thread_locals->end()) {
Packit bd1cd8
      thread_local_pos = thread_to_thread_locals->insert(
Packit bd1cd8
          std::make_pair(current_thread, ThreadLocalValues())).first;
Packit bd1cd8
      StartWatcherThreadFor(current_thread);
Packit bd1cd8
    }
Packit bd1cd8
    ThreadLocalValues& thread_local_values = thread_local_pos->second;
Packit bd1cd8
    ThreadLocalValues::iterator value_pos =
Packit bd1cd8
        thread_local_values.find(thread_local_instance);
Packit bd1cd8
    if (value_pos == thread_local_values.end()) {
Packit bd1cd8
      value_pos =
Packit bd1cd8
          thread_local_values
Packit bd1cd8
              .insert(std::make_pair(
Packit bd1cd8
                  thread_local_instance,
Packit bd1cd8
                  linked_ptr<ThreadLocalValueHolderBase>(
Packit bd1cd8
                      thread_local_instance->NewValueForCurrentThread())))
Packit bd1cd8
              .first;
Packit bd1cd8
    }
Packit bd1cd8
    return value_pos->second.get();
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  static void OnThreadLocalDestroyed(
Packit bd1cd8
      const ThreadLocalBase* thread_local_instance) {
Packit bd1cd8
    std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
Packit bd1cd8
    // Clean up the ThreadLocalValues data structure while holding the lock, but
Packit bd1cd8
    // defer the destruction of the ThreadLocalValueHolderBases.
Packit bd1cd8
    {
Packit bd1cd8
      MutexLock lock(&mutex_);
Packit bd1cd8
      ThreadIdToThreadLocals* const thread_to_thread_locals =
Packit bd1cd8
          GetThreadLocalsMapLocked();
Packit bd1cd8
      for (ThreadIdToThreadLocals::iterator it =
Packit bd1cd8
          thread_to_thread_locals->begin();
Packit bd1cd8
          it != thread_to_thread_locals->end();
Packit bd1cd8
          ++it) {
Packit bd1cd8
        ThreadLocalValues& thread_local_values = it->second;
Packit bd1cd8
        ThreadLocalValues::iterator value_pos =
Packit bd1cd8
            thread_local_values.find(thread_local_instance);
Packit bd1cd8
        if (value_pos != thread_local_values.end()) {
Packit bd1cd8
          value_holders.push_back(value_pos->second);
Packit bd1cd8
          thread_local_values.erase(value_pos);
Packit bd1cd8
          // This 'if' can only be successful at most once, so theoretically we
Packit bd1cd8
          // could break out of the loop here, but we don't bother doing so.
Packit bd1cd8
        }
Packit bd1cd8
      }
Packit bd1cd8
    }
Packit bd1cd8
    // Outside the lock, let the destructor for 'value_holders' deallocate the
Packit bd1cd8
    // ThreadLocalValueHolderBases.
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  static void OnThreadExit(DWORD thread_id) {
Packit bd1cd8
    GTEST_CHECK_(thread_id != 0) << ::GetLastError();
Packit bd1cd8
    std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
Packit bd1cd8
    // Clean up the ThreadIdToThreadLocals data structure while holding the
Packit bd1cd8
    // lock, but defer the destruction of the ThreadLocalValueHolderBases.
Packit bd1cd8
    {
Packit bd1cd8
      MutexLock lock(&mutex_);
Packit bd1cd8
      ThreadIdToThreadLocals* const thread_to_thread_locals =
Packit bd1cd8
          GetThreadLocalsMapLocked();
Packit bd1cd8
      ThreadIdToThreadLocals::iterator thread_local_pos =
Packit bd1cd8
          thread_to_thread_locals->find(thread_id);
Packit bd1cd8
      if (thread_local_pos != thread_to_thread_locals->end()) {
Packit bd1cd8
        ThreadLocalValues& thread_local_values = thread_local_pos->second;
Packit bd1cd8
        for (ThreadLocalValues::iterator value_pos =
Packit bd1cd8
            thread_local_values.begin();
Packit bd1cd8
            value_pos != thread_local_values.end();
Packit bd1cd8
            ++value_pos) {
Packit bd1cd8
          value_holders.push_back(value_pos->second);
Packit bd1cd8
        }
Packit bd1cd8
        thread_to_thread_locals->erase(thread_local_pos);
Packit bd1cd8
      }
Packit bd1cd8
    }
Packit bd1cd8
    // Outside the lock, let the destructor for 'value_holders' deallocate the
Packit bd1cd8
    // ThreadLocalValueHolderBases.
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
 private:
Packit bd1cd8
  // In a particular thread, maps a ThreadLocal object to its value.
Packit bd1cd8
  typedef std::map
Packit bd1cd8
                   linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
Packit bd1cd8
  // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
Packit bd1cd8
  // thread's ID.
Packit bd1cd8
  typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
Packit bd1cd8
Packit bd1cd8
  // Holds the thread id and thread handle that we pass from
Packit bd1cd8
  // StartWatcherThreadFor to WatcherThreadFunc.
Packit bd1cd8
  typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
Packit bd1cd8
Packit bd1cd8
  static void StartWatcherThreadFor(DWORD thread_id) {
Packit bd1cd8
    // The returned handle will be kept in thread_map and closed by
Packit bd1cd8
    // watcher_thread in WatcherThreadFunc.
Packit bd1cd8
    HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
Packit bd1cd8
                                 FALSE,
Packit bd1cd8
                                 thread_id);
Packit bd1cd8
    GTEST_CHECK_(thread != NULL);
Packit bd1cd8
    // We need to to pass a valid thread ID pointer into CreateThread for it
Packit bd1cd8
    // to work correctly under Win98.
Packit bd1cd8
    DWORD watcher_thread_id;
Packit bd1cd8
    HANDLE watcher_thread = ::CreateThread(
Packit bd1cd8
        NULL,   // Default security.
Packit bd1cd8
        0,      // Default stack size
Packit bd1cd8
        &ThreadLocalRegistryImpl::WatcherThreadFunc,
Packit bd1cd8
        reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
Packit bd1cd8
        CREATE_SUSPENDED,
Packit bd1cd8
        &watcher_thread_id);
Packit bd1cd8
    GTEST_CHECK_(watcher_thread != NULL);
Packit bd1cd8
    // Give the watcher thread the same priority as ours to avoid being
Packit bd1cd8
    // blocked by it.
Packit bd1cd8
    ::SetThreadPriority(watcher_thread,
Packit bd1cd8
                        ::GetThreadPriority(::GetCurrentThread()));
Packit bd1cd8
    ::ResumeThread(watcher_thread);
Packit bd1cd8
    ::CloseHandle(watcher_thread);
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Monitors exit from a given thread and notifies those
Packit bd1cd8
  // ThreadIdToThreadLocals about thread termination.
Packit bd1cd8
  static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
Packit bd1cd8
    const ThreadIdAndHandle* tah =
Packit bd1cd8
        reinterpret_cast<const ThreadIdAndHandle*>(param);
Packit bd1cd8
    GTEST_CHECK_(
Packit bd1cd8
        ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
Packit bd1cd8
    OnThreadExit(tah->first);
Packit bd1cd8
    ::CloseHandle(tah->second);
Packit bd1cd8
    delete tah;
Packit bd1cd8
    return 0;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Returns map of thread local instances.
Packit bd1cd8
  static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
Packit bd1cd8
    mutex_.AssertHeld();
Packit bd1cd8
    static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;
Packit bd1cd8
    return map;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Protects access to GetThreadLocalsMapLocked() and its return value.
Packit bd1cd8
  static Mutex mutex_;
Packit bd1cd8
  // Protects access to GetThreadMapLocked() and its return value.
Packit bd1cd8
  static Mutex thread_map_mutex_;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
Packit bd1cd8
Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
Packit bd1cd8
Packit bd1cd8
ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
Packit bd1cd8
      const ThreadLocalBase* thread_local_instance) {
Packit bd1cd8
  return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
Packit bd1cd8
      thread_local_instance);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
void ThreadLocalRegistry::OnThreadLocalDestroyed(
Packit bd1cd8
      const ThreadLocalBase* thread_local_instance) {
Packit bd1cd8
  ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
Packit bd1cd8
Packit bd1cd8
#if GTEST_USES_POSIX_RE
Packit bd1cd8
Packit bd1cd8
// Implements RE.  Currently only needed for death tests.
Packit bd1cd8
Packit bd1cd8
RE::~RE() {
Packit bd1cd8
  if (is_valid_) {
Packit bd1cd8
    // regfree'ing an invalid regex might crash because the content
Packit bd1cd8
    // of the regex is undefined. Since the regex's are essentially
Packit bd1cd8
    // the same, one cannot be valid (or invalid) without the other
Packit bd1cd8
    // being so too.
Packit bd1cd8
    regfree(&partial_regex_);
Packit bd1cd8
    regfree(&full_regex_);
Packit bd1cd8
  }
Packit bd1cd8
  free(const_cast<char*>(pattern_));
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff regular expression re matches the entire str.
Packit bd1cd8
bool RE::FullMatch(const char* str, const RE& re) {
Packit bd1cd8
  if (!re.is_valid_) return false;
Packit bd1cd8
Packit bd1cd8
  regmatch_t match;
Packit bd1cd8
  return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff regular expression re matches a substring of str
Packit bd1cd8
// (including str itself).
Packit bd1cd8
bool RE::PartialMatch(const char* str, const RE& re) {
Packit bd1cd8
  if (!re.is_valid_) return false;
Packit bd1cd8
Packit bd1cd8
  regmatch_t match;
Packit bd1cd8
  return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Initializes an RE from its string representation.
Packit bd1cd8
void RE::Init(const char* regex) {
Packit bd1cd8
  pattern_ = posix::StrDup(regex);
Packit bd1cd8
Packit bd1cd8
  // Reserves enough bytes to hold the regular expression used for a
Packit bd1cd8
  // full match.
Packit bd1cd8
  const size_t full_regex_len = strlen(regex) + 10;
Packit bd1cd8
  char* const full_pattern = new char[full_regex_len];
Packit bd1cd8
Packit bd1cd8
  snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
Packit bd1cd8
  is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
Packit bd1cd8
  // We want to call regcomp(&partial_regex_, ...) even if the
Packit bd1cd8
  // previous expression returns false.  Otherwise partial_regex_ may
Packit bd1cd8
  // not be properly initialized can may cause trouble when it's
Packit bd1cd8
  // freed.
Packit bd1cd8
  //
Packit bd1cd8
  // Some implementation of POSIX regex (e.g. on at least some
Packit bd1cd8
  // versions of Cygwin) doesn't accept the empty string as a valid
Packit bd1cd8
  // regex.  We change it to an equivalent form "()" to be safe.
Packit bd1cd8
  if (is_valid_) {
Packit bd1cd8
    const char* const partial_regex = (*regex == '\0') ? "()" : regex;
Packit bd1cd8
    is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
Packit bd1cd8
  }
Packit bd1cd8
  EXPECT_TRUE(is_valid_)
Packit bd1cd8
      << "Regular expression \"" << regex
Packit bd1cd8
      << "\" is not a valid POSIX Extended regular expression.";
Packit bd1cd8
Packit bd1cd8
  delete[] full_pattern;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#elif GTEST_USES_SIMPLE_RE
Packit bd1cd8
Packit bd1cd8
// Returns true iff ch appears anywhere in str (excluding the
Packit bd1cd8
// terminating '\0' character).
Packit bd1cd8
bool IsInSet(char ch, const char* str) {
Packit bd1cd8
  return ch != '\0' && strchr(str, ch) != NULL;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff ch belongs to the given classification.  Unlike
Packit bd1cd8
// similar functions in <ctype.h>, these aren't affected by the
Packit bd1cd8
// current locale.
Packit bd1cd8
bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
Packit bd1cd8
bool IsAsciiPunct(char ch) {
Packit bd1cd8
  return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
Packit bd1cd8
}
Packit bd1cd8
bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
Packit bd1cd8
bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
Packit bd1cd8
bool IsAsciiWordChar(char ch) {
Packit bd1cd8
  return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
Packit bd1cd8
      ('0' <= ch && ch <= '9') || ch == '_';
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff "\\c" is a supported escape sequence.
Packit bd1cd8
bool IsValidEscape(char c) {
Packit bd1cd8
  return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff the given atom (specified by escaped and pattern)
Packit bd1cd8
// matches ch.  The result is undefined if the atom is invalid.
Packit bd1cd8
bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
Packit bd1cd8
  if (escaped) {  // "\\p" where p is pattern_char.
Packit bd1cd8
    switch (pattern_char) {
Packit bd1cd8
      case 'd': return IsAsciiDigit(ch);
Packit bd1cd8
      case 'D': return !IsAsciiDigit(ch);
Packit bd1cd8
      case 'f': return ch == '\f';
Packit bd1cd8
      case 'n': return ch == '\n';
Packit bd1cd8
      case 'r': return ch == '\r';
Packit bd1cd8
      case 's': return IsAsciiWhiteSpace(ch);
Packit bd1cd8
      case 'S': return !IsAsciiWhiteSpace(ch);
Packit bd1cd8
      case 't': return ch == '\t';
Packit bd1cd8
      case 'v': return ch == '\v';
Packit bd1cd8
      case 'w': return IsAsciiWordChar(ch);
Packit bd1cd8
      case 'W': return !IsAsciiWordChar(ch);
Packit bd1cd8
    }
Packit bd1cd8
    return IsAsciiPunct(pattern_char) && pattern_char == ch;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Helper function used by ValidateRegex() to format error messages.
Packit bd1cd8
std::string FormatRegexSyntaxError(const char* regex, int index) {
Packit bd1cd8
  return (Message() << "Syntax error at index " << index
Packit bd1cd8
          << " in simple regular expression \"" << regex << "\": ").GetString();
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Generates non-fatal failures and returns false if regex is invalid;
Packit bd1cd8
// otherwise returns true.
Packit bd1cd8
bool ValidateRegex(const char* regex) {
Packit bd1cd8
  if (regex == NULL) {
Packit bd1cd8
    // TODO(wan@google.com): fix the source file location in the
Packit bd1cd8
    // assertion failures to match where the regex is used in user
Packit bd1cd8
    // code.
Packit bd1cd8
    ADD_FAILURE() << "NULL is not a valid simple regular expression.";
Packit bd1cd8
    return false;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  bool is_valid = true;
Packit bd1cd8
Packit bd1cd8
  // True iff ?, *, or + can follow the previous atom.
Packit bd1cd8
  bool prev_repeatable = false;
Packit bd1cd8
  for (int i = 0; regex[i]; i++) {
Packit bd1cd8
    if (regex[i] == '\\') {  // An escape sequence
Packit bd1cd8
      i++;
Packit bd1cd8
      if (regex[i] == '\0') {
Packit bd1cd8
        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
Packit bd1cd8
                      << "'\\' cannot appear at the end.";
Packit bd1cd8
        return false;
Packit bd1cd8
      }
Packit bd1cd8
Packit bd1cd8
      if (!IsValidEscape(regex[i])) {
Packit bd1cd8
        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
Packit bd1cd8
                      << "invalid escape sequence \"\\" << regex[i] << "\".";
Packit bd1cd8
        is_valid = false;
Packit bd1cd8
      }
Packit bd1cd8
      prev_repeatable = true;
Packit bd1cd8
    } else {  // Not an escape sequence.
Packit bd1cd8
      const char ch = regex[i];
Packit bd1cd8
Packit bd1cd8
      if (ch == '^' && i > 0) {
Packit bd1cd8
        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
Packit bd1cd8
                      << "'^' can only appear at the beginning.";
Packit bd1cd8
        is_valid = false;
Packit bd1cd8
      } else if (ch == '$' && regex[i + 1] != '\0') {
Packit bd1cd8
        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
Packit bd1cd8
                      << "'$' can only appear at the end.";
Packit bd1cd8
        is_valid = false;
Packit bd1cd8
      } else if (IsInSet(ch, "()[]{}|")) {
Packit bd1cd8
        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
Packit bd1cd8
                      << "'" << ch << "' is unsupported.";
Packit bd1cd8
        is_valid = false;
Packit bd1cd8
      } else if (IsRepeat(ch) && !prev_repeatable) {
Packit bd1cd8
        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
Packit bd1cd8
                      << "'" << ch << "' can only follow a repeatable token.";
Packit bd1cd8
        is_valid = false;
Packit bd1cd8
      }
Packit bd1cd8
Packit bd1cd8
      prev_repeatable = !IsInSet(ch, "^$?*+");
Packit bd1cd8
    }
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  return is_valid;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Matches a repeated regex atom followed by a valid simple regular
Packit bd1cd8
// expression.  The regex atom is defined as c if escaped is false,
Packit bd1cd8
// or \c otherwise.  repeat is the repetition meta character (?, *,
Packit bd1cd8
// or +).  The behavior is undefined if str contains too many
Packit bd1cd8
// characters to be indexable by size_t, in which case the test will
Packit bd1cd8
// probably time out anyway.  We are fine with this limitation as
Packit bd1cd8
// std::string has it too.
Packit bd1cd8
bool MatchRepetitionAndRegexAtHead(
Packit bd1cd8
    bool escaped, char c, char repeat, const char* regex,
Packit bd1cd8
    const char* str) {
Packit bd1cd8
  const size_t min_count = (repeat == '+') ? 1 : 0;
Packit bd1cd8
  const size_t max_count = (repeat == '?') ? 1 :
Packit bd1cd8
      static_cast<size_t>(-1) - 1;
Packit bd1cd8
  // We cannot call numeric_limits::max() as it conflicts with the
Packit bd1cd8
  // max() macro on Windows.
Packit bd1cd8
Packit bd1cd8
  for (size_t i = 0; i <= max_count; ++i) {
Packit bd1cd8
    // We know that the atom matches each of the first i characters in str.
Packit bd1cd8
    if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
Packit bd1cd8
      // We have enough matches at the head, and the tail matches too.
Packit bd1cd8
      // Since we only care about *whether* the pattern matches str
Packit bd1cd8
      // (as opposed to *how* it matches), there is no need to find a
Packit bd1cd8
      // greedy match.
Packit bd1cd8
      return true;
Packit bd1cd8
    }
Packit bd1cd8
    if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
Packit bd1cd8
      return false;
Packit bd1cd8
  }
Packit bd1cd8
  return false;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff regex matches a prefix of str.  regex must be a
Packit bd1cd8
// valid simple regular expression and not start with "^", or the
Packit bd1cd8
// result is undefined.
Packit bd1cd8
bool MatchRegexAtHead(const char* regex, const char* str) {
Packit bd1cd8
  if (*regex == '\0')  // An empty regex matches a prefix of anything.
Packit bd1cd8
    return true;
Packit bd1cd8
Packit bd1cd8
  // "$" only matches the end of a string.  Note that regex being
Packit bd1cd8
  // valid guarantees that there's nothing after "$" in it.
Packit bd1cd8
  if (*regex == '$')
Packit bd1cd8
    return *str == '\0';
Packit bd1cd8
Packit bd1cd8
  // Is the first thing in regex an escape sequence?
Packit bd1cd8
  const bool escaped = *regex == '\\';
Packit bd1cd8
  if (escaped)
Packit bd1cd8
    ++regex;
Packit bd1cd8
  if (IsRepeat(regex[1])) {
Packit bd1cd8
    // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
Packit bd1cd8
    // here's an indirect recursion.  It terminates as the regex gets
Packit bd1cd8
    // shorter in each recursion.
Packit bd1cd8
    return MatchRepetitionAndRegexAtHead(
Packit bd1cd8
        escaped, regex[0], regex[1], regex + 2, str);
Packit bd1cd8
  } else {
Packit bd1cd8
    // regex isn't empty, isn't "$", and doesn't start with a
Packit bd1cd8
    // repetition.  We match the first atom of regex with the first
Packit bd1cd8
    // character of str and recurse.
Packit bd1cd8
    return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
Packit bd1cd8
        MatchRegexAtHead(regex + 1, str + 1);
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff regex matches any substring of str.  regex must be
Packit bd1cd8
// a valid simple regular expression, or the result is undefined.
Packit bd1cd8
//
Packit bd1cd8
// The algorithm is recursive, but the recursion depth doesn't exceed
Packit bd1cd8
// the regex length, so we won't need to worry about running out of
Packit bd1cd8
// stack space normally.  In rare cases the time complexity can be
Packit bd1cd8
// exponential with respect to the regex length + the string length,
Packit bd1cd8
// but usually it's must faster (often close to linear).
Packit bd1cd8
bool MatchRegexAnywhere(const char* regex, const char* str) {
Packit bd1cd8
  if (regex == NULL || str == NULL)
Packit bd1cd8
    return false;
Packit bd1cd8
Packit bd1cd8
  if (*regex == '^')
Packit bd1cd8
    return MatchRegexAtHead(regex + 1, str);
Packit bd1cd8
Packit bd1cd8
  // A successful match can be anywhere in str.
Packit bd1cd8
  do {
Packit bd1cd8
    if (MatchRegexAtHead(regex, str))
Packit bd1cd8
      return true;
Packit bd1cd8
  } while (*str++ != '\0');
Packit bd1cd8
  return false;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Implements the RE class.
Packit bd1cd8
Packit bd1cd8
RE::~RE() {
Packit bd1cd8
  free(const_cast<char*>(pattern_));
Packit bd1cd8
  free(const_cast<char*>(full_pattern_));
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff regular expression re matches the entire str.
Packit bd1cd8
bool RE::FullMatch(const char* str, const RE& re) {
Packit bd1cd8
  return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Returns true iff regular expression re matches a substring of str
Packit bd1cd8
// (including str itself).
Packit bd1cd8
bool RE::PartialMatch(const char* str, const RE& re) {
Packit bd1cd8
  return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Initializes an RE from its string representation.
Packit bd1cd8
void RE::Init(const char* regex) {
Packit bd1cd8
  pattern_ = full_pattern_ = NULL;
Packit bd1cd8
  if (regex != NULL) {
Packit bd1cd8
    pattern_ = posix::StrDup(regex);
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  is_valid_ = ValidateRegex(regex);
Packit bd1cd8
  if (!is_valid_) {
Packit bd1cd8
    // No need to calculate the full pattern when the regex is invalid.
Packit bd1cd8
    return;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  const size_t len = strlen(regex);
Packit bd1cd8
  // Reserves enough bytes to hold the regular expression used for a
Packit bd1cd8
  // full match: we need space to prepend a '^', append a '$', and
Packit bd1cd8
  // terminate the string with '\0'.
Packit bd1cd8
  char* buffer = static_cast<char*>(malloc(len + 3));
Packit bd1cd8
  full_pattern_ = buffer;
Packit bd1cd8
Packit bd1cd8
  if (*regex != '^')
Packit bd1cd8
    *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
Packit bd1cd8
Packit bd1cd8
  // We don't use snprintf or strncpy, as they trigger a warning when
Packit bd1cd8
  // compiled with VC++ 8.0.
Packit bd1cd8
  memcpy(buffer, regex, len);
Packit bd1cd8
  buffer += len;
Packit bd1cd8
Packit bd1cd8
  if (len == 0 || regex[len - 1] != '$')
Packit bd1cd8
    *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
Packit bd1cd8
Packit bd1cd8
  *buffer = '\0';
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#endif  // GTEST_USES_POSIX_RE
Packit bd1cd8
Packit bd1cd8
const char kUnknownFile[] = "unknown file";
Packit bd1cd8
Packit bd1cd8
// Formats a source file path and a line number as they would appear
Packit bd1cd8
// in an error message from the compiler used to compile this code.
Packit bd1cd8
GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
Packit bd1cd8
  const std::string file_name(file == NULL ? kUnknownFile : file);
Packit bd1cd8
Packit bd1cd8
  if (line < 0) {
Packit bd1cd8
    return file_name + ":";
Packit bd1cd8
  }
Packit bd1cd8
#ifdef _MSC_VER
Packit bd1cd8
  return file_name + "(" + StreamableToString(line) + "):";
Packit bd1cd8
#else
Packit bd1cd8
  return file_name + ":" + StreamableToString(line) + ":";
Packit bd1cd8
#endif  // _MSC_VER
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Formats a file location for compiler-independent XML output.
Packit bd1cd8
// Although this function is not platform dependent, we put it next to
Packit bd1cd8
// FormatFileLocation in order to contrast the two functions.
Packit bd1cd8
// Note that FormatCompilerIndependentFileLocation() does NOT append colon
Packit bd1cd8
// to the file location it produces, unlike FormatFileLocation().
Packit bd1cd8
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
Packit bd1cd8
    const char* file, int line) {
Packit bd1cd8
  const std::string file_name(file == NULL ? kUnknownFile : file);
Packit bd1cd8
Packit bd1cd8
  if (line < 0)
Packit bd1cd8
    return file_name;
Packit bd1cd8
  else
Packit bd1cd8
    return file_name + ":" + StreamableToString(line);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
Packit bd1cd8
    : severity_(severity) {
Packit bd1cd8
  const char* const marker =
Packit bd1cd8
      severity == GTEST_INFO ?    "[  INFO ]" :
Packit bd1cd8
      severity == GTEST_WARNING ? "[WARNING]" :
Packit bd1cd8
      severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
Packit bd1cd8
  GetStream() << ::std::endl << marker << " "
Packit bd1cd8
              << FormatFileLocation(file, line).c_str() << ": ";
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
Packit bd1cd8
GTestLog::~GTestLog() {
Packit bd1cd8
  GetStream() << ::std::endl;
Packit bd1cd8
  if (severity_ == GTEST_FATAL) {
Packit bd1cd8
    fflush(stderr);
Packit bd1cd8
    posix::Abort();
Packit bd1cd8
  }
Packit bd1cd8
}
Packit bd1cd8
// Disable Microsoft deprecation warnings for POSIX functions called from
Packit bd1cd8
// this class (creat, dup, dup2, and close)
Packit bd1cd8
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
Packit bd1cd8
Packit bd1cd8
#if GTEST_HAS_STREAM_REDIRECTION
Packit bd1cd8
Packit bd1cd8
// Object that captures an output stream (stdout/stderr).
Packit bd1cd8
class CapturedStream {
Packit bd1cd8
 public:
Packit bd1cd8
  // The ctor redirects the stream to a temporary file.
Packit bd1cd8
  explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
Packit bd1cd8
# if GTEST_OS_WINDOWS
Packit bd1cd8
    char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
Packit bd1cd8
    char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
Packit bd1cd8
Packit bd1cd8
    ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
Packit bd1cd8
    const UINT success = ::GetTempFileNameA(temp_dir_path,
Packit bd1cd8
                                            "gtest_redir",
Packit bd1cd8
                                            0,  // Generate unique file name.
Packit bd1cd8
                                            temp_file_path);
Packit bd1cd8
    GTEST_CHECK_(success != 0)
Packit bd1cd8
        << "Unable to create a temporary file in " << temp_dir_path;
Packit bd1cd8
    const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
Packit bd1cd8
    GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
Packit bd1cd8
                                    << temp_file_path;
Packit bd1cd8
    filename_ = temp_file_path;
Packit bd1cd8
# else
Packit bd1cd8
    // There's no guarantee that a test has write access to the current
Packit bd1cd8
    // directory, so we create the temporary file in the /tmp directory
Packit bd1cd8
    // instead. We use /tmp on most systems, and /sdcard on Android.
Packit bd1cd8
    // That's because Android doesn't have /tmp.
Packit bd1cd8
#  if GTEST_OS_LINUX_ANDROID
Packit bd1cd8
    // Note: Android applications are expected to call the framework's
Packit bd1cd8
    // Context.getExternalStorageDirectory() method through JNI to get
Packit bd1cd8
    // the location of the world-writable SD Card directory. However,
Packit bd1cd8
    // this requires a Context handle, which cannot be retrieved
Packit bd1cd8
    // globally from native code. Doing so also precludes running the
Packit bd1cd8
    // code as part of a regular standalone executable, which doesn't
Packit bd1cd8
    // run in a Dalvik process (e.g. when running it through 'adb shell').
Packit bd1cd8
    //
Packit bd1cd8
    // The location /sdcard is directly accessible from native code
Packit bd1cd8
    // and is the only location (unofficially) supported by the Android
Packit bd1cd8
    // team. It's generally a symlink to the real SD Card mount point
Packit bd1cd8
    // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
Packit bd1cd8
    // other OEM-customized locations. Never rely on these, and always
Packit bd1cd8
    // use /sdcard.
Packit bd1cd8
    char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
Packit bd1cd8
#  else
Packit bd1cd8
    char name_template[] = "/tmp/captured_stream.XXXXXX";
Packit bd1cd8
#  endif  // GTEST_OS_LINUX_ANDROID
Packit bd1cd8
    const int captured_fd = mkstemp(name_template);
Packit bd1cd8
    filename_ = name_template;
Packit bd1cd8
# endif  // GTEST_OS_WINDOWS
Packit bd1cd8
    fflush(NULL);
Packit bd1cd8
    dup2(captured_fd, fd_);
Packit bd1cd8
    close(captured_fd);
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  ~CapturedStream() {
Packit bd1cd8
    remove(filename_.c_str());
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  std::string GetCapturedString() {
Packit bd1cd8
    if (uncaptured_fd_ != -1) {
Packit bd1cd8
      // Restores the original stream.
Packit bd1cd8
      fflush(NULL);
Packit bd1cd8
      dup2(uncaptured_fd_, fd_);
Packit bd1cd8
      close(uncaptured_fd_);
Packit bd1cd8
      uncaptured_fd_ = -1;
Packit bd1cd8
    }
Packit bd1cd8
Packit bd1cd8
    FILE* const file = posix::FOpen(filename_.c_str(), "r");
Packit bd1cd8
    const std::string content = ReadEntireFile(file);
Packit bd1cd8
    posix::FClose(file);
Packit bd1cd8
    return content;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
 private:
Packit bd1cd8
  const int fd_;  // A stream to capture.
Packit bd1cd8
  int uncaptured_fd_;
Packit bd1cd8
  // Name of the temporary file holding the stderr output.
Packit bd1cd8
  ::std::string filename_;
Packit bd1cd8
Packit bd1cd8
  GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
GTEST_DISABLE_MSC_WARNINGS_POP_()
Packit bd1cd8
Packit bd1cd8
static CapturedStream* g_captured_stderr = NULL;
Packit bd1cd8
static CapturedStream* g_captured_stdout = NULL;
Packit bd1cd8
Packit bd1cd8
// Starts capturing an output stream (stdout/stderr).
Packit bd1cd8
void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
Packit bd1cd8
  if (*stream != NULL) {
Packit bd1cd8
    GTEST_LOG_(FATAL) << "Only one " << stream_name
Packit bd1cd8
                      << " capturer can exist at a time.";
Packit bd1cd8
  }
Packit bd1cd8
  *stream = new CapturedStream(fd);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Stops capturing the output stream and returns the captured string.
Packit bd1cd8
std::string GetCapturedStream(CapturedStream** captured_stream) {
Packit bd1cd8
  const std::string content = (*captured_stream)->GetCapturedString();
Packit bd1cd8
Packit bd1cd8
  delete *captured_stream;
Packit bd1cd8
  *captured_stream = NULL;
Packit bd1cd8
Packit bd1cd8
  return content;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Starts capturing stdout.
Packit bd1cd8
void CaptureStdout() {
Packit bd1cd8
  CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Starts capturing stderr.
Packit bd1cd8
void CaptureStderr() {
Packit bd1cd8
  CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Stops capturing stdout and returns the captured string.
Packit bd1cd8
std::string GetCapturedStdout() {
Packit bd1cd8
  return GetCapturedStream(&g_captured_stdout);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Stops capturing stderr and returns the captured string.
Packit bd1cd8
std::string GetCapturedStderr() {
Packit bd1cd8
  return GetCapturedStream(&g_captured_stderr);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#endif  // GTEST_HAS_STREAM_REDIRECTION
Packit bd1cd8
Packit bd1cd8
std::string TempDir() {
Packit bd1cd8
#if GTEST_OS_WINDOWS_MOBILE
Packit bd1cd8
  return "\\temp\\";
Packit bd1cd8
#elif GTEST_OS_WINDOWS
Packit bd1cd8
  const char* temp_dir = posix::GetEnv("TEMP");
Packit bd1cd8
  if (temp_dir == NULL || temp_dir[0] == '\0')
Packit bd1cd8
    return "\\temp\\";
Packit bd1cd8
  else if (temp_dir[strlen(temp_dir) - 1] == '\\')
Packit bd1cd8
    return temp_dir;
Packit bd1cd8
  else
Packit bd1cd8
    return std::string(temp_dir) + "\\";
Packit bd1cd8
#elif GTEST_OS_LINUX_ANDROID
Packit bd1cd8
  return "/sdcard/";
Packit bd1cd8
#else
Packit bd1cd8
  return "/tmp/";
Packit bd1cd8
#endif  // GTEST_OS_WINDOWS_MOBILE
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
size_t GetFileSize(FILE* file) {
Packit bd1cd8
  fseek(file, 0, SEEK_END);
Packit bd1cd8
  return static_cast<size_t>(ftell(file));
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
std::string ReadEntireFile(FILE* file) {
Packit bd1cd8
  const size_t file_size = GetFileSize(file);
Packit bd1cd8
  char* const buffer = new char[file_size];
Packit bd1cd8
Packit bd1cd8
  size_t bytes_last_read = 0;  // # of bytes read in the last fread()
Packit bd1cd8
  size_t bytes_read = 0;       // # of bytes read so far
Packit bd1cd8
Packit bd1cd8
  fseek(file, 0, SEEK_SET);
Packit bd1cd8
Packit bd1cd8
  // Keeps reading the file until we cannot read further or the
Packit bd1cd8
  // pre-determined file size is reached.
Packit bd1cd8
  do {
Packit bd1cd8
    bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
Packit bd1cd8
    bytes_read += bytes_last_read;
Packit bd1cd8
  } while (bytes_last_read > 0 && bytes_read < file_size);
Packit bd1cd8
Packit bd1cd8
  const std::string content(buffer, bytes_read);
Packit bd1cd8
  delete[] buffer;
Packit bd1cd8
Packit bd1cd8
  return content;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
#if GTEST_HAS_DEATH_TEST
Packit bd1cd8
Packit bd1cd8
static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
Packit bd1cd8
                                        NULL;  // Owned.
Packit bd1cd8
Packit bd1cd8
void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
Packit bd1cd8
  if (g_injected_test_argvs != argvs)
Packit bd1cd8
    delete g_injected_test_argvs;
Packit bd1cd8
  g_injected_test_argvs = argvs;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
Packit bd1cd8
  if (g_injected_test_argvs != NULL) {
Packit bd1cd8
    return *g_injected_test_argvs;
Packit bd1cd8
  }
Packit bd1cd8
  return GetArgvs();
Packit bd1cd8
}
Packit bd1cd8
#endif  // GTEST_HAS_DEATH_TEST
Packit bd1cd8
Packit bd1cd8
#if GTEST_OS_WINDOWS_MOBILE
Packit bd1cd8
namespace posix {
Packit bd1cd8
void Abort() {
Packit bd1cd8
  DebugBreak();
Packit bd1cd8
  TerminateProcess(GetCurrentProcess(), 1);
Packit bd1cd8
}
Packit bd1cd8
}  // namespace posix
Packit bd1cd8
#endif  // GTEST_OS_WINDOWS_MOBILE
Packit bd1cd8
Packit bd1cd8
// Returns the name of the environment variable corresponding to the
Packit bd1cd8
// given flag.  For example, FlagToEnvVar("foo") will return
Packit bd1cd8
// "GTEST_FOO" in the open-source version.
Packit bd1cd8
static std::string FlagToEnvVar(const char* flag) {
Packit bd1cd8
  const std::string full_flag =
Packit bd1cd8
      (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
Packit bd1cd8
Packit bd1cd8
  Message env_var;
Packit bd1cd8
  for (size_t i = 0; i != full_flag.length(); i++) {
Packit bd1cd8
    env_var << ToUpper(full_flag.c_str()[i]);
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  return env_var.GetString();
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Parses 'str' for a 32-bit signed integer.  If successful, writes
Packit bd1cd8
// the result to *value and returns true; otherwise leaves *value
Packit bd1cd8
// unchanged and returns false.
Packit bd1cd8
bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
Packit bd1cd8
  // Parses the environment variable as a decimal integer.
Packit bd1cd8
  char* end = NULL;
Packit bd1cd8
  const long long_value = strtol(str, &end, 10);  // NOLINT
Packit bd1cd8
Packit bd1cd8
  // Has strtol() consumed all characters in the string?
Packit bd1cd8
  if (*end != '\0') {
Packit bd1cd8
    // No - an invalid character was encountered.
Packit bd1cd8
    Message msg;
Packit bd1cd8
    msg << "WARNING: " << src_text
Packit bd1cd8
        << " is expected to be a 32-bit integer, but actually"
Packit bd1cd8
        << " has value \"" << str << "\".\n";
Packit bd1cd8
    printf("%s", msg.GetString().c_str());
Packit bd1cd8
    fflush(stdout);
Packit bd1cd8
    return false;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Is the parsed value in the range of an Int32?
Packit bd1cd8
  const Int32 result = static_cast<Int32>(long_value);
Packit bd1cd8
  if (long_value == LONG_MAX || long_value == LONG_MIN ||
Packit bd1cd8
      // The parsed value overflows as a long.  (strtol() returns
Packit bd1cd8
      // LONG_MAX or LONG_MIN when the input overflows.)
Packit bd1cd8
      result != long_value
Packit bd1cd8
      // The parsed value overflows as an Int32.
Packit bd1cd8
      ) {
Packit bd1cd8
    Message msg;
Packit bd1cd8
    msg << "WARNING: " << src_text
Packit bd1cd8
        << " is expected to be a 32-bit integer, but actually"
Packit bd1cd8
        << " has value " << str << ", which overflows.\n";
Packit bd1cd8
    printf("%s", msg.GetString().c_str());
Packit bd1cd8
    fflush(stdout);
Packit bd1cd8
    return false;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  *value = result;
Packit bd1cd8
  return true;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Reads and returns the Boolean environment variable corresponding to
Packit bd1cd8
// the given flag; if it's not set, returns default_value.
Packit bd1cd8
//
Packit bd1cd8
// The value is considered true iff it's not "0".
Packit bd1cd8
bool BoolFromGTestEnv(const char* flag, bool default_value) {
Packit bd1cd8
#if defined(GTEST_GET_BOOL_FROM_ENV_)
Packit bd1cd8
  return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
Packit bd1cd8
#endif  // defined(GTEST_GET_BOOL_FROM_ENV_)
Packit bd1cd8
  const std::string env_var = FlagToEnvVar(flag);
Packit bd1cd8
  const char* const string_value = posix::GetEnv(env_var.c_str());
Packit bd1cd8
  return string_value == NULL ?
Packit bd1cd8
      default_value : strcmp(string_value, "0") != 0;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Reads and returns a 32-bit integer stored in the environment
Packit bd1cd8
// variable corresponding to the given flag; if it isn't set or
Packit bd1cd8
// doesn't represent a valid 32-bit integer, returns default_value.
Packit bd1cd8
Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
Packit bd1cd8
#if defined(GTEST_GET_INT32_FROM_ENV_)
Packit bd1cd8
  return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
Packit bd1cd8
#endif  // defined(GTEST_GET_INT32_FROM_ENV_)
Packit bd1cd8
  const std::string env_var = FlagToEnvVar(flag);
Packit bd1cd8
  const char* const string_value = posix::GetEnv(env_var.c_str());
Packit bd1cd8
  if (string_value == NULL) {
Packit bd1cd8
    // The environment variable is not set.
Packit bd1cd8
    return default_value;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  Int32 result = default_value;
Packit bd1cd8
  if (!ParseInt32(Message() << "Environment variable " << env_var,
Packit bd1cd8
                  string_value, &result)) {
Packit bd1cd8
    printf("The default value %s is used.\n",
Packit bd1cd8
           (Message() << default_value).GetString().c_str());
Packit bd1cd8
    fflush(stdout);
Packit bd1cd8
    return default_value;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  return result;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Reads and returns the string environment variable corresponding to
Packit bd1cd8
// the given flag; if it's not set, returns default_value.
Packit bd1cd8
std::string StringFromGTestEnv(const char* flag, const char* default_value) {
Packit bd1cd8
#if defined(GTEST_GET_STRING_FROM_ENV_)
Packit bd1cd8
  return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
Packit bd1cd8
#endif  // defined(GTEST_GET_STRING_FROM_ENV_)
Packit bd1cd8
  const std::string env_var = FlagToEnvVar(flag);
Packit bd1cd8
  const char* value = posix::GetEnv(env_var.c_str());
Packit bd1cd8
  if (value != NULL) {
Packit bd1cd8
    return value;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // As a special case for the 'output' flag, if GTEST_OUTPUT is not
Packit bd1cd8
  // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
Packit bd1cd8
  // system.  The value of XML_OUTPUT_FILE is a filename without the
Packit bd1cd8
  // "xml:" prefix of GTEST_OUTPUT.
Packit bd1cd8
  //
Packit bd1cd8
  // The net priority order after flag processing is thus:
Packit bd1cd8
  //   --gtest_output command line flag
Packit bd1cd8
  //   GTEST_OUTPUT environment variable
Packit bd1cd8
  //   XML_OUTPUT_FILE environment variable
Packit bd1cd8
  //   'default_value'
Packit bd1cd8
  if (strcmp(flag, "output") == 0) {
Packit bd1cd8
    value = posix::GetEnv("XML_OUTPUT_FILE");
Packit bd1cd8
    if (value != NULL) {
Packit bd1cd8
      return std::string("xml:") + value;
Packit bd1cd8
    }
Packit bd1cd8
  }
Packit bd1cd8
  return default_value;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
}  // namespace internal
Packit bd1cd8
}  // namespace testing