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