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