gtest-port.cc 47 KB

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