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


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:53