gtest-port.cc 43 KB

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