gtest-port.cc 42 KB

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