1
0

gtest-port.cc 47 KB

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