gtest-port.cc 48 KB

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