gtest-port.h 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554
  1. // Copyright 2005, 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. // Authors: wan@google.com (Zhanyong Wan)
  31. //
  32. // Low-level types and utilities for porting Google Test to various
  33. // platforms. All macros ending with _ and symbols defined in an
  34. // internal namespace are subject to change without notice. Code
  35. // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't
  36. // end with _ are part of Google Test's public API and can be used by
  37. // code outside Google Test.
  38. //
  39. // This file is fundamental to Google Test. All other Google Test source
  40. // files are expected to #include this. Therefore, it cannot #include
  41. // any other Google Test header.
  42. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  43. #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  44. // Environment-describing macros
  45. // -----------------------------
  46. //
  47. // Google Test can be used in many different environments. Macros in
  48. // this section tell Google Test what kind of environment it is being
  49. // used in, such that Google Test can provide environment-specific
  50. // features and implementations.
  51. //
  52. // Google Test tries to automatically detect the properties of its
  53. // environment, so users usually don't need to worry about these
  54. // macros. However, the automatic detection is not perfect.
  55. // Sometimes it's necessary for a user to define some of the following
  56. // macros in the build script to override Google Test's decisions.
  57. //
  58. // If the user doesn't define a macro in the list, Google Test will
  59. // provide a default definition. After this header is #included, all
  60. // macros in this list will be defined to either 1 or 0.
  61. //
  62. // Notes to maintainers:
  63. // - Each macro here is a user-tweakable knob; do not grow the list
  64. // lightly.
  65. // - Use #if to key off these macros. Don't use #ifdef or "#if
  66. // defined(...)", which will not work as these macros are ALWAYS
  67. // defined.
  68. //
  69. // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2)
  70. // is/isn't available.
  71. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
  72. // are enabled.
  73. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string
  74. // is/isn't available (some systems define
  75. // ::string, which is different to std::string).
  76. // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
  77. // is/isn't available (some systems define
  78. // ::wstring, which is different to std::wstring).
  79. // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
  80. // expressions are/aren't available.
  81. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
  82. // is/isn't available.
  83. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't
  84. // enabled.
  85. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
  86. // std::wstring does/doesn't work (Google Test can
  87. // be used where std::wstring is unavailable).
  88. // GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple
  89. // is/isn't available.
  90. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
  91. // compiler supports Microsoft's "Structured
  92. // Exception Handling".
  93. // GTEST_HAS_STREAM_REDIRECTION
  94. // - Define it to 1/0 to indicate whether the
  95. // platform supports I/O stream redirection using
  96. // dup() and dup2().
  97. // GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google
  98. // Test's own tr1 tuple implementation should be
  99. // used. Unused when the user sets
  100. // GTEST_HAS_TR1_TUPLE to 0.
  101. // GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test
  102. // is building in C++11/C++98 mode.
  103. // GTEST_LINKED_AS_SHARED_LIBRARY
  104. // - Define to 1 when compiling tests that use
  105. // Google Test as a shared library (known as
  106. // DLL on Windows).
  107. // GTEST_CREATE_SHARED_LIBRARY
  108. // - Define to 1 when compiling Google Test itself
  109. // as a shared library.
  110. // Platform-indicating macros
  111. // --------------------------
  112. //
  113. // Macros indicating the platform on which Google Test is being used
  114. // (a macro is defined to 1 if compiled on the given platform;
  115. // otherwise UNDEFINED -- it's never defined to 0.). Google Test
  116. // defines these macros automatically. Code outside Google Test MUST
  117. // NOT define them.
  118. //
  119. // GTEST_OS_AIX - IBM AIX
  120. // GTEST_OS_CYGWIN - Cygwin
  121. // GTEST_OS_FREEBSD - FreeBSD
  122. // GTEST_OS_HPUX - HP-UX
  123. // GTEST_OS_LINUX - Linux
  124. // GTEST_OS_LINUX_ANDROID - Google Android
  125. // GTEST_OS_MAC - Mac OS X
  126. // GTEST_OS_IOS - iOS
  127. // GTEST_OS_NACL - Google Native Client (NaCl)
  128. // GTEST_OS_OPENBSD - OpenBSD
  129. // GTEST_OS_QNX - QNX
  130. // GTEST_OS_SOLARIS - Sun Solaris
  131. // GTEST_OS_SYMBIAN - Symbian
  132. // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
  133. // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
  134. // GTEST_OS_WINDOWS_MINGW - MinGW
  135. // GTEST_OS_WINDOWS_MOBILE - Windows Mobile
  136. // GTEST_OS_WINDOWS_PHONE - Windows Phone
  137. // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
  138. // GTEST_OS_ZOS - z/OS
  139. //
  140. // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
  141. // most stable support. Since core members of the Google Test project
  142. // don't have access to other platforms, support for them may be less
  143. // stable. If you notice any problems on your platform, please notify
  144. // googletestframework@googlegroups.com (patches for fixing them are
  145. // even more welcome!).
  146. //
  147. // It is possible that none of the GTEST_OS_* macros are defined.
  148. // Feature-indicating macros
  149. // -------------------------
  150. //
  151. // Macros indicating which Google Test features are available (a macro
  152. // is defined to 1 if the corresponding feature is supported;
  153. // otherwise UNDEFINED -- it's never defined to 0.). Google Test
  154. // defines these macros automatically. Code outside Google Test MUST
  155. // NOT define them.
  156. //
  157. // These macros are public so that portable tests can be written.
  158. // Such tests typically surround code using a feature with an #if
  159. // which controls that code. For example:
  160. //
  161. // #if GTEST_HAS_DEATH_TEST
  162. // EXPECT_DEATH(DoSomethingDeadly());
  163. // #endif
  164. //
  165. // GTEST_HAS_COMBINE - the Combine() function (for value-parameterized
  166. // tests)
  167. // GTEST_HAS_DEATH_TEST - death tests
  168. // GTEST_HAS_PARAM_TEST - value-parameterized tests
  169. // GTEST_HAS_TYPED_TEST - typed tests
  170. // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
  171. // GTEST_IS_THREADSAFE - Google Test is thread-safe.
  172. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
  173. // GTEST_HAS_POSIX_RE (see above) which users can
  174. // define themselves.
  175. // GTEST_USES_SIMPLE_RE - our own simple regex is used;
  176. // the above two are mutually exclusive.
  177. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
  178. // Misc public macros
  179. // ------------------
  180. //
  181. // GTEST_FLAG(flag_name) - references the variable corresponding to
  182. // the given Google Test flag.
  183. // Internal utilities
  184. // ------------------
  185. //
  186. // The following macros and utilities are for Google Test's INTERNAL
  187. // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY.
  188. //
  189. // Macros for basic C++ coding:
  190. // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
  191. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
  192. // variable don't have to be used.
  193. // GTEST_DISALLOW_ASSIGN_ - disables operator=.
  194. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
  195. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
  196. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
  197. // suppressed (constant conditional).
  198. // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
  199. // is suppressed.
  200. //
  201. // C++11 feature wrappers:
  202. //
  203. // testing::internal::move - portability wrapper for std::move.
  204. //
  205. // Synchronization:
  206. // Mutex, MutexLock, ThreadLocal, GetThreadCount()
  207. // - synchronization primitives.
  208. //
  209. // Template meta programming:
  210. // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only.
  211. // IteratorTraits - partial implementation of std::iterator_traits, which
  212. // is not available in libCstd when compiled with Sun C++.
  213. //
  214. // Smart pointers:
  215. // scoped_ptr - as in TR2.
  216. //
  217. // Regular expressions:
  218. // RE - a simple regular expression class using the POSIX
  219. // Extended Regular Expression syntax on UNIX-like
  220. // platforms, or a reduced regular exception syntax on
  221. // other platforms, including Windows.
  222. //
  223. // Logging:
  224. // GTEST_LOG_() - logs messages at the specified severity level.
  225. // LogToStderr() - directs all log messages to stderr.
  226. // FlushInfoLog() - flushes informational log messages.
  227. //
  228. // Stdout and stderr capturing:
  229. // CaptureStdout() - starts capturing stdout.
  230. // GetCapturedStdout() - stops capturing stdout and returns the captured
  231. // string.
  232. // CaptureStderr() - starts capturing stderr.
  233. // GetCapturedStderr() - stops capturing stderr and returns the captured
  234. // string.
  235. //
  236. // Integer types:
  237. // TypeWithSize - maps an integer to a int type.
  238. // Int32, UInt32, Int64, UInt64, TimeInMillis
  239. // - integers of known sizes.
  240. // BiggestInt - the biggest signed integer type.
  241. //
  242. // Command-line utilities:
  243. // GTEST_DECLARE_*() - declares a flag.
  244. // GTEST_DEFINE_*() - defines a flag.
  245. // GetInjectableArgvs() - returns the command line as a vector of strings.
  246. //
  247. // Environment variable utilities:
  248. // GetEnv() - gets the value of an environment variable.
  249. // BoolFromGTestEnv() - parses a bool environment variable.
  250. // Int32FromGTestEnv() - parses an Int32 environment variable.
  251. // StringFromGTestEnv() - parses a string environment variable.
  252. #include <ctype.h> // for isspace, etc
  253. #include <stddef.h> // for ptrdiff_t
  254. #include <stdlib.h>
  255. #include <stdio.h>
  256. #include <string.h>
  257. #ifndef _WIN32_WCE
  258. # include <sys/types.h>
  259. # include <sys/stat.h>
  260. #endif // !_WIN32_WCE
  261. #if defined __APPLE__
  262. # include <AvailabilityMacros.h>
  263. # include <TargetConditionals.h>
  264. #endif
  265. #include <algorithm> // NOLINT
  266. #include <iostream> // NOLINT
  267. #include <sstream> // NOLINT
  268. #include <string> // NOLINT
  269. #include <utility>
  270. #include <vector> // NOLINT
  271. #include "gtest/internal/gtest-port-arch.h"
  272. #include "gtest/internal/custom/gtest-port.h"
  273. #if !defined(GTEST_DEV_EMAIL_)
  274. # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
  275. # define GTEST_FLAG_PREFIX_ "gtest_"
  276. # define GTEST_FLAG_PREFIX_DASH_ "gtest-"
  277. # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
  278. # define GTEST_NAME_ "Google Test"
  279. # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
  280. #endif // !defined(GTEST_DEV_EMAIL_)
  281. #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
  282. # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
  283. #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
  284. // Determines the version of gcc that is used to compile this.
  285. #ifdef __GNUC__
  286. // 40302 means version 4.3.2.
  287. # define GTEST_GCC_VER_ \
  288. (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
  289. #endif // __GNUC__
  290. // Macros for disabling Microsoft Visual C++ warnings.
  291. //
  292. // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
  293. // /* code that triggers warnings C4800 and C4385 */
  294. // GTEST_DISABLE_MSC_WARNINGS_POP_()
  295. #if _MSC_VER >= 1500
  296. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
  297. __pragma(warning(push)) \
  298. __pragma(warning(disable: warnings))
  299. # define GTEST_DISABLE_MSC_WARNINGS_POP_() \
  300. __pragma(warning(pop))
  301. #else
  302. // Older versions of MSVC don't have __pragma.
  303. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
  304. # define GTEST_DISABLE_MSC_WARNINGS_POP_()
  305. #endif
  306. #ifndef GTEST_LANG_CXX11
  307. // gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when
  308. // -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a
  309. // value for __cplusplus, and recent versions of clang, gcc, and
  310. // probably other compilers set that too in C++11 mode.
  311. # if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L
  312. // Compiling in at least C++11 mode.
  313. # define GTEST_LANG_CXX11 1
  314. # else
  315. # define GTEST_LANG_CXX11 0
  316. # endif
  317. #endif
  318. // Distinct from C++11 language support, some environments don't provide
  319. // proper C++11 library support. Notably, it's possible to build in
  320. // C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++
  321. // with no C++11 support.
  322. //
  323. // libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__
  324. // 20110325, but maintenance releases in the 4.4 and 4.5 series followed
  325. // this date, so check for those versions by their date stamps.
  326. // https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning
  327. #if GTEST_LANG_CXX11 && \
  328. (!defined(__GLIBCXX__) || ( \
  329. __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \
  330. /* Blacklist of patch releases of older branches: */ \
  331. __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \
  332. __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \
  333. __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \
  334. __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */
  335. # define GTEST_STDLIB_CXX11 1
  336. #endif
  337. // Only use C++11 library features if the library provides them.
  338. #if GTEST_STDLIB_CXX11
  339. # define GTEST_HAS_STD_BEGIN_AND_END_ 1
  340. # define GTEST_HAS_STD_FORWARD_LIST_ 1
  341. # define GTEST_HAS_STD_FUNCTION_ 1
  342. # define GTEST_HAS_STD_INITIALIZER_LIST_ 1
  343. # define GTEST_HAS_STD_MOVE_ 1
  344. # define GTEST_HAS_STD_SHARED_PTR_ 1
  345. # define GTEST_HAS_STD_TYPE_TRAITS_ 1
  346. # define GTEST_HAS_STD_UNIQUE_PTR_ 1
  347. #endif
  348. // C++11 specifies that <tuple> provides std::tuple.
  349. // Some platforms still might not have it, however.
  350. #if GTEST_LANG_CXX11
  351. # define GTEST_HAS_STD_TUPLE_ 1
  352. # if defined(__clang__)
  353. // Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include
  354. # if defined(__has_include) && !__has_include(<tuple>)
  355. # undef GTEST_HAS_STD_TUPLE_
  356. # endif
  357. # elif defined(_MSC_VER)
  358. // Inspired by boost/config/stdlib/dinkumware.hpp
  359. # if defined(_CPPLIB_VER) && _CPPLIB_VER < 520
  360. # undef GTEST_HAS_STD_TUPLE_
  361. # endif
  362. # elif defined(__GLIBCXX__)
  363. // Inspired by boost/config/stdlib/libstdcpp3.hpp,
  364. // http://gcc.gnu.org/gcc-4.2/changes.html and
  365. // http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x
  366. # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
  367. # undef GTEST_HAS_STD_TUPLE_
  368. # endif
  369. # endif
  370. #endif
  371. // Brings in definitions for functions used in the testing::internal::posix
  372. // namespace (read, write, close, chdir, isatty, stat). We do not currently
  373. // use them on Windows Mobile.
  374. #if GTEST_OS_WINDOWS
  375. # if !GTEST_OS_WINDOWS_MOBILE
  376. # include <direct.h>
  377. # include <io.h>
  378. # endif
  379. // In order to avoid having to include <windows.h>, use forward declaration
  380. // assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
  381. // This assumption is verified by
  382. // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
  383. struct _RTL_CRITICAL_SECTION;
  384. #else
  385. // This assumes that non-Windows OSes provide unistd.h. For OSes where this
  386. // is not the case, we need to include headers that provide the functions
  387. // mentioned above.
  388. # include <unistd.h>
  389. # include <strings.h>
  390. #endif // GTEST_OS_WINDOWS
  391. #if GTEST_OS_LINUX_ANDROID
  392. // Used to define __ANDROID_API__ matching the target NDK API level.
  393. # include <android/api-level.h> // NOLINT
  394. #endif
  395. // Defines this to true iff Google Test can use POSIX regular expressions.
  396. #ifndef GTEST_HAS_POSIX_RE
  397. # if GTEST_OS_LINUX_ANDROID
  398. // On Android, <regex.h> is only available starting with Gingerbread.
  399. # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
  400. # else
  401. # define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS)
  402. # endif
  403. #endif
  404. #if GTEST_USES_PCRE
  405. // The appropriate headers have already been included.
  406. #elif GTEST_HAS_POSIX_RE
  407. // On some platforms, <regex.h> needs someone to define size_t, and
  408. // won't compile otherwise. We can #include it here as we already
  409. // included <stdlib.h>, which is guaranteed to define size_t through
  410. // <stddef.h>.
  411. # include <regex.h> // NOLINT
  412. # define GTEST_USES_POSIX_RE 1
  413. #elif GTEST_OS_WINDOWS
  414. // <regex.h> is not available on Windows. Use our own simple regex
  415. // implementation instead.
  416. # define GTEST_USES_SIMPLE_RE 1
  417. #else
  418. // <regex.h> may not be available on this platform. Use our own
  419. // simple regex implementation instead.
  420. # define GTEST_USES_SIMPLE_RE 1
  421. #endif // GTEST_USES_PCRE
  422. #ifndef GTEST_HAS_EXCEPTIONS
  423. // The user didn't tell us whether exceptions are enabled, so we need
  424. // to figure it out.
  425. # if defined(_MSC_VER) || defined(__BORLANDC__)
  426. // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
  427. // macro to enable exceptions, so we'll do the same.
  428. // Assumes that exceptions are enabled by default.
  429. # ifndef _HAS_EXCEPTIONS
  430. # define _HAS_EXCEPTIONS 1
  431. # endif // _HAS_EXCEPTIONS
  432. # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
  433. # elif defined(__clang__)
  434. // clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714,
  435. // but iff cleanups are enabled after that. In Obj-C++ files, there can be
  436. // cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions
  437. // are disabled. clang has __has_feature(cxx_exceptions) which checks for C++
  438. // exceptions starting at clang r206352, but which checked for cleanups prior to
  439. // that. To reliably check for C++ exception availability with clang, check for
  440. // __EXCEPTIONS && __has_feature(cxx_exceptions).
  441. # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
  442. # elif defined(__GNUC__) && __EXCEPTIONS
  443. // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
  444. # define GTEST_HAS_EXCEPTIONS 1
  445. # elif defined(__SUNPRO_CC)
  446. // Sun Pro CC supports exceptions. However, there is no compile-time way of
  447. // detecting whether they are enabled or not. Therefore, we assume that
  448. // they are enabled unless the user tells us otherwise.
  449. # define GTEST_HAS_EXCEPTIONS 1
  450. # elif defined(__IBMCPP__) && __EXCEPTIONS
  451. // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
  452. # define GTEST_HAS_EXCEPTIONS 1
  453. # elif defined(__HP_aCC)
  454. // Exception handling is in effect by default in HP aCC compiler. It has to
  455. // be turned of by +noeh compiler option if desired.
  456. # define GTEST_HAS_EXCEPTIONS 1
  457. # else
  458. // For other compilers, we assume exceptions are disabled to be
  459. // conservative.
  460. # define GTEST_HAS_EXCEPTIONS 0
  461. # endif // defined(_MSC_VER) || defined(__BORLANDC__)
  462. #endif // GTEST_HAS_EXCEPTIONS
  463. #if !defined(GTEST_HAS_STD_STRING)
  464. // Even though we don't use this macro any longer, we keep it in case
  465. // some clients still depend on it.
  466. # define GTEST_HAS_STD_STRING 1
  467. #elif !GTEST_HAS_STD_STRING
  468. // The user told us that ::std::string isn't available.
  469. # error "Google Test cannot be used where ::std::string isn't available."
  470. #endif // !defined(GTEST_HAS_STD_STRING)
  471. #ifndef GTEST_HAS_GLOBAL_STRING
  472. // The user didn't tell us whether ::string is available, so we need
  473. // to figure it out.
  474. # define GTEST_HAS_GLOBAL_STRING 0
  475. #endif // GTEST_HAS_GLOBAL_STRING
  476. #ifndef GTEST_HAS_STD_WSTRING
  477. // The user didn't tell us whether ::std::wstring is available, so we need
  478. // to figure it out.
  479. // TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
  480. // is available.
  481. // Cygwin 1.7 and below doesn't support ::std::wstring.
  482. // Solaris' libc++ doesn't support it either. Android has
  483. // no support for it at least as recent as Froyo (2.2).
  484. # define GTEST_HAS_STD_WSTRING \
  485. (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS))
  486. #endif // GTEST_HAS_STD_WSTRING
  487. #ifndef GTEST_HAS_GLOBAL_WSTRING
  488. // The user didn't tell us whether ::wstring is available, so we need
  489. // to figure it out.
  490. # define GTEST_HAS_GLOBAL_WSTRING \
  491. (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
  492. #endif // GTEST_HAS_GLOBAL_WSTRING
  493. // Determines whether RTTI is available.
  494. #ifndef GTEST_HAS_RTTI
  495. // The user didn't tell us whether RTTI is enabled, so we need to
  496. // figure it out.
  497. # ifdef _MSC_VER
  498. # ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled.
  499. # define GTEST_HAS_RTTI 1
  500. # else
  501. # define GTEST_HAS_RTTI 0
  502. # endif
  503. // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
  504. # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
  505. # ifdef __GXX_RTTI
  506. // When building against STLport with the Android NDK and with
  507. // -frtti -fno-exceptions, the build fails at link time with undefined
  508. // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
  509. // so disable RTTI when detected.
  510. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
  511. !defined(__EXCEPTIONS)
  512. # define GTEST_HAS_RTTI 0
  513. # else
  514. # define GTEST_HAS_RTTI 1
  515. # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
  516. # else
  517. # define GTEST_HAS_RTTI 0
  518. # endif // __GXX_RTTI
  519. // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
  520. // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
  521. // first version with C++ support.
  522. # elif defined(__clang__)
  523. # define GTEST_HAS_RTTI __has_feature(cxx_rtti)
  524. // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
  525. // both the typeid and dynamic_cast features are present.
  526. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
  527. # ifdef __RTTI_ALL__
  528. # define GTEST_HAS_RTTI 1
  529. # else
  530. # define GTEST_HAS_RTTI 0
  531. # endif
  532. # else
  533. // For all other compilers, we assume RTTI is enabled.
  534. # define GTEST_HAS_RTTI 1
  535. # endif // _MSC_VER
  536. #endif // GTEST_HAS_RTTI
  537. // It's this header's responsibility to #include <typeinfo> when RTTI
  538. // is enabled.
  539. #if GTEST_HAS_RTTI
  540. # include <typeinfo>
  541. #endif
  542. // Determines whether Google Test can use the pthreads library.
  543. #ifndef GTEST_HAS_PTHREAD
  544. // The user didn't tell us explicitly, so we make reasonable assumptions about
  545. // which platforms have pthreads support.
  546. //
  547. // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
  548. // to your compiler flags.
  549. # define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \
  550. || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL)
  551. #endif // GTEST_HAS_PTHREAD
  552. #if GTEST_HAS_PTHREAD
  553. // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
  554. // true.
  555. # include <pthread.h> // NOLINT
  556. // For timespec and nanosleep, used below.
  557. # include <time.h> // NOLINT
  558. #endif
  559. // Determines if hash_map/hash_set are available.
  560. // Only used for testing against those containers.
  561. #if !defined(GTEST_HAS_HASH_MAP_)
  562. # if _MSC_VER
  563. # define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available.
  564. # define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available.
  565. # endif // _MSC_VER
  566. #endif // !defined(GTEST_HAS_HASH_MAP_)
  567. // Determines whether Google Test can use tr1/tuple. You can define
  568. // this macro to 0 to prevent Google Test from using tuple (any
  569. // feature depending on tuple with be disabled in this mode).
  570. #ifndef GTEST_HAS_TR1_TUPLE
  571. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR)
  572. // STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>.
  573. # define GTEST_HAS_TR1_TUPLE 0
  574. # else
  575. // The user didn't tell us not to do it, so we assume it's OK.
  576. # define GTEST_HAS_TR1_TUPLE 1
  577. # endif
  578. #endif // GTEST_HAS_TR1_TUPLE
  579. // Determines whether Google Test's own tr1 tuple implementation
  580. // should be used.
  581. #ifndef GTEST_USE_OWN_TR1_TUPLE
  582. // The user didn't tell us, so we need to figure it out.
  583. // We use our own TR1 tuple if we aren't sure the user has an
  584. // implementation of it already. At this time, libstdc++ 4.0.0+ and
  585. // MSVC 2010 are the only mainstream standard libraries that come
  586. // with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler
  587. // pretends to be GCC by defining __GNUC__ and friends, but cannot
  588. // compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1
  589. // tuple in a 323 MB Feature Pack download, which we cannot assume the
  590. // user has. QNX's QCC compiler is a modified GCC but it doesn't
  591. // support TR1 tuple. libc++ only provides std::tuple, in C++11 mode,
  592. // and it can be used with some compilers that define __GNUC__.
  593. # if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
  594. && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
  595. # define GTEST_ENV_HAS_TR1_TUPLE_ 1
  596. # endif
  597. // C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
  598. // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
  599. // can build with clang but need to use gcc4.2's libstdc++).
  600. # if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
  601. # define GTEST_ENV_HAS_STD_TUPLE_ 1
  602. # endif
  603. # if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
  604. # define GTEST_USE_OWN_TR1_TUPLE 0
  605. # else
  606. # define GTEST_USE_OWN_TR1_TUPLE 1
  607. # endif
  608. #endif // GTEST_USE_OWN_TR1_TUPLE
  609. // To avoid conditional compilation everywhere, we make it
  610. // gtest-port.h's responsibility to #include the header implementing
  611. // tuple.
  612. #if GTEST_HAS_STD_TUPLE_
  613. # include <tuple> // IWYU pragma: export
  614. # define GTEST_TUPLE_NAMESPACE_ ::std
  615. #endif // GTEST_HAS_STD_TUPLE_
  616. // We include tr1::tuple even if std::tuple is available to define printers for
  617. // them.
  618. #if GTEST_HAS_TR1_TUPLE
  619. # ifndef GTEST_TUPLE_NAMESPACE_
  620. # define GTEST_TUPLE_NAMESPACE_ ::std::tr1
  621. # endif // GTEST_TUPLE_NAMESPACE_
  622. # if GTEST_USE_OWN_TR1_TUPLE
  623. # include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT
  624. # elif GTEST_ENV_HAS_STD_TUPLE_
  625. # include <tuple>
  626. // C++11 puts its tuple into the ::std namespace rather than
  627. // ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there.
  628. // This causes undefined behavior, but supported compilers react in
  629. // the way we intend.
  630. namespace std {
  631. namespace tr1 {
  632. using ::std::get;
  633. using ::std::make_tuple;
  634. using ::std::tuple;
  635. using ::std::tuple_element;
  636. using ::std::tuple_size;
  637. }
  638. }
  639. # elif GTEST_OS_SYMBIAN
  640. // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
  641. // use STLport's tuple implementation, which unfortunately doesn't
  642. // work as the copy of STLport distributed with Symbian is incomplete.
  643. // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
  644. // use its own tuple implementation.
  645. # ifdef BOOST_HAS_TR1_TUPLE
  646. # undef BOOST_HAS_TR1_TUPLE
  647. # endif // BOOST_HAS_TR1_TUPLE
  648. // This prevents <boost/tr1/detail/config.hpp>, which defines
  649. // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
  650. # define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
  651. # include <tuple> // IWYU pragma: export // NOLINT
  652. # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
  653. // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header. This does
  654. // not conform to the TR1 spec, which requires the header to be <tuple>.
  655. # if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
  656. // Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
  657. // which is #included by <tr1/tuple>, to not compile when RTTI is
  658. // disabled. _TR1_FUNCTIONAL is the header guard for
  659. // <tr1/functional>. Hence the following #define is a hack to prevent
  660. // <tr1/functional> from being included.
  661. # define _TR1_FUNCTIONAL 1
  662. # include <tr1/tuple>
  663. # undef _TR1_FUNCTIONAL // Allows the user to #include
  664. // <tr1/functional> if he chooses to.
  665. # else
  666. # include <tr1/tuple> // NOLINT
  667. # endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
  668. # else
  669. // If the compiler is not GCC 4.0+, we assume the user is using a
  670. // spec-conforming TR1 implementation.
  671. # include <tuple> // IWYU pragma: export // NOLINT
  672. # endif // GTEST_USE_OWN_TR1_TUPLE
  673. #endif // GTEST_HAS_TR1_TUPLE
  674. // Determines whether clone(2) is supported.
  675. // Usually it will only be available on Linux, excluding
  676. // Linux on the Itanium architecture.
  677. // Also see http://linux.die.net/man/2/clone.
  678. #ifndef GTEST_HAS_CLONE
  679. // The user didn't tell us, so we need to figure it out.
  680. # if GTEST_OS_LINUX && !defined(__ia64__)
  681. # if GTEST_OS_LINUX_ANDROID
  682. // On Android, clone() is only available on ARM starting with Gingerbread.
  683. # if defined(__arm__) && __ANDROID_API__ >= 9
  684. # define GTEST_HAS_CLONE 1
  685. # else
  686. # define GTEST_HAS_CLONE 0
  687. # endif
  688. # else
  689. # define GTEST_HAS_CLONE 1
  690. # endif
  691. # else
  692. # define GTEST_HAS_CLONE 0
  693. # endif // GTEST_OS_LINUX && !defined(__ia64__)
  694. #endif // GTEST_HAS_CLONE
  695. // Determines whether to support stream redirection. This is used to test
  696. // output correctness and to implement death tests.
  697. #ifndef GTEST_HAS_STREAM_REDIRECTION
  698. // By default, we assume that stream redirection is supported on all
  699. // platforms except known mobile ones.
  700. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \
  701. GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  702. # define GTEST_HAS_STREAM_REDIRECTION 0
  703. # else
  704. # define GTEST_HAS_STREAM_REDIRECTION 1
  705. # endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
  706. #endif // GTEST_HAS_STREAM_REDIRECTION
  707. // Determines whether to support death tests.
  708. // Google Test does not support death tests for VC 7.1 and earlier as
  709. // abort() in a VC 7.1 application compiled as GUI in debug config
  710. // pops up a dialog window that cannot be suppressed programmatically.
  711. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
  712. (GTEST_OS_MAC && !GTEST_OS_IOS) || \
  713. (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
  714. GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
  715. GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD)
  716. # define GTEST_HAS_DEATH_TEST 1
  717. #endif
  718. // We don't support MSVC 7.1 with exceptions disabled now. Therefore
  719. // all the compilers we care about are adequate for supporting
  720. // value-parameterized tests.
  721. #define GTEST_HAS_PARAM_TEST 1
  722. // Determines whether to support type-driven tests.
  723. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
  724. // Sun Pro CC, IBM Visual Age, and HP aCC support.
  725. #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
  726. defined(__IBMCPP__) || defined(__HP_aCC)
  727. # define GTEST_HAS_TYPED_TEST 1
  728. # define GTEST_HAS_TYPED_TEST_P 1
  729. #endif
  730. // Determines whether to support Combine(). This only makes sense when
  731. // value-parameterized tests are enabled. The implementation doesn't
  732. // work on Sun Studio since it doesn't understand templated conversion
  733. // operators.
  734. #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
  735. # define GTEST_HAS_COMBINE 1
  736. #endif
  737. // Determines whether the system compiler uses UTF-16 for encoding wide strings.
  738. #define GTEST_WIDE_STRING_USES_UTF16_ \
  739. (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
  740. // Determines whether test results can be streamed to a socket.
  741. #if GTEST_OS_LINUX
  742. # define GTEST_CAN_STREAM_RESULTS_ 1
  743. #endif
  744. // Defines some utility macros.
  745. // The GNU compiler emits a warning if nested "if" statements are followed by
  746. // an "else" statement and braces are not used to explicitly disambiguate the
  747. // "else" binding. This leads to problems with code like:
  748. //
  749. // if (gate)
  750. // ASSERT_*(condition) << "Some message";
  751. //
  752. // The "switch (0) case 0:" idiom is used to suppress this.
  753. #ifdef __INTEL_COMPILER
  754. # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
  755. #else
  756. # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
  757. #endif
  758. // Use this annotation at the end of a struct/class definition to
  759. // prevent the compiler from optimizing away instances that are never
  760. // used. This is useful when all interesting logic happens inside the
  761. // c'tor and / or d'tor. Example:
  762. //
  763. // struct Foo {
  764. // Foo() { ... }
  765. // } GTEST_ATTRIBUTE_UNUSED_;
  766. //
  767. // Also use it after a variable or parameter declaration to tell the
  768. // compiler the variable/parameter does not have to be used.
  769. #if defined(__GNUC__) && !defined(COMPILER_ICC)
  770. # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
  771. #elif defined(__clang__)
  772. # if __has_attribute(unused)
  773. # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
  774. # endif
  775. #endif
  776. #ifndef GTEST_ATTRIBUTE_UNUSED_
  777. # define GTEST_ATTRIBUTE_UNUSED_
  778. #endif
  779. // A macro to disallow operator=
  780. // This should be used in the private: declarations for a class.
  781. #define GTEST_DISALLOW_ASSIGN_(type)\
  782. void operator=(type const &)
  783. // A macro to disallow copy constructor and operator=
  784. // This should be used in the private: declarations for a class.
  785. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
  786. type(type const &);\
  787. GTEST_DISALLOW_ASSIGN_(type)
  788. // Tell the compiler to warn about unused return values for functions declared
  789. // with this macro. The macro should be used on function declarations
  790. // following the argument list:
  791. //
  792. // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
  793. #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
  794. # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
  795. #else
  796. # define GTEST_MUST_USE_RESULT_
  797. #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
  798. // MS C++ compiler emits warning when a conditional expression is compile time
  799. // constant. In some contexts this warning is false positive and needs to be
  800. // suppressed. Use the following two macros in such cases:
  801. //
  802. // GTEST_INTENTIONAL_CONST_COND_PUSH_()
  803. // while (true) {
  804. // GTEST_INTENTIONAL_CONST_COND_POP_()
  805. // }
  806. # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
  807. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
  808. # define GTEST_INTENTIONAL_CONST_COND_POP_() \
  809. GTEST_DISABLE_MSC_WARNINGS_POP_()
  810. // Determine whether the compiler supports Microsoft's Structured Exception
  811. // Handling. This is supported by several Windows compilers but generally
  812. // does not exist on any other system.
  813. #ifndef GTEST_HAS_SEH
  814. // The user didn't tell us, so we need to figure it out.
  815. # if defined(_MSC_VER) || defined(__BORLANDC__)
  816. // These two compilers are known to support SEH.
  817. # define GTEST_HAS_SEH 1
  818. # else
  819. // Assume no SEH.
  820. # define GTEST_HAS_SEH 0
  821. # endif
  822. #define GTEST_IS_THREADSAFE \
  823. (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \
  824. || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \
  825. || GTEST_HAS_PTHREAD)
  826. #endif // GTEST_HAS_SEH
  827. #ifdef _MSC_VER
  828. # if GTEST_LINKED_AS_SHARED_LIBRARY
  829. # define GTEST_API_ __declspec(dllimport)
  830. # elif GTEST_CREATE_SHARED_LIBRARY
  831. # define GTEST_API_ __declspec(dllexport)
  832. # endif
  833. #elif __GNUC__ >= 4 || defined(__clang__)
  834. # define GTEST_API_ __attribute__((visibility ("default")))
  835. #endif // _MSC_VER
  836. #ifndef GTEST_API_
  837. # define GTEST_API_
  838. #endif
  839. #ifdef __GNUC__
  840. // Ask the compiler to never inline a given function.
  841. # define GTEST_NO_INLINE_ __attribute__((noinline))
  842. #else
  843. # define GTEST_NO_INLINE_
  844. #endif
  845. // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
  846. #if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
  847. # define GTEST_HAS_CXXABI_H_ 1
  848. #else
  849. # define GTEST_HAS_CXXABI_H_ 0
  850. #endif
  851. // A function level attribute to disable checking for use of uninitialized
  852. // memory when built with MemorySanitizer.
  853. #if defined(__clang__)
  854. # if __has_feature(memory_sanitizer)
  855. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
  856. __attribute__((no_sanitize_memory))
  857. # else
  858. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  859. # endif // __has_feature(memory_sanitizer)
  860. #else
  861. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  862. #endif // __clang__
  863. // A function level attribute to disable AddressSanitizer instrumentation.
  864. #if defined(__clang__)
  865. # if __has_feature(address_sanitizer)
  866. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
  867. __attribute__((no_sanitize_address))
  868. # else
  869. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  870. # endif // __has_feature(address_sanitizer)
  871. #else
  872. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  873. #endif // __clang__
  874. // A function level attribute to disable ThreadSanitizer instrumentation.
  875. #if defined(__clang__)
  876. # if __has_feature(thread_sanitizer)
  877. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
  878. __attribute__((no_sanitize_thread))
  879. # else
  880. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  881. # endif // __has_feature(thread_sanitizer)
  882. #else
  883. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  884. #endif // __clang__
  885. namespace testing {
  886. class Message;
  887. #if defined(GTEST_TUPLE_NAMESPACE_)
  888. // Import tuple and friends into the ::testing namespace.
  889. // It is part of our interface, having them in ::testing allows us to change
  890. // their types as needed.
  891. using GTEST_TUPLE_NAMESPACE_::get;
  892. using GTEST_TUPLE_NAMESPACE_::make_tuple;
  893. using GTEST_TUPLE_NAMESPACE_::tuple;
  894. using GTEST_TUPLE_NAMESPACE_::tuple_size;
  895. using GTEST_TUPLE_NAMESPACE_::tuple_element;
  896. #endif // defined(GTEST_TUPLE_NAMESPACE_)
  897. namespace internal {
  898. // A secret type that Google Test users don't know about. It has no
  899. // definition on purpose. Therefore it's impossible to create a
  900. // Secret object, which is what we want.
  901. class Secret;
  902. // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
  903. // expression is true. For example, you could use it to verify the
  904. // size of a static array:
  905. //
  906. // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
  907. // names_incorrect_size);
  908. //
  909. // or to make sure a struct is smaller than a certain size:
  910. //
  911. // GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
  912. //
  913. // The second argument to the macro is the name of the variable. If
  914. // the expression is false, most compilers will issue a warning/error
  915. // containing the name of the variable.
  916. #if GTEST_LANG_CXX11
  917. # define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
  918. #else // !GTEST_LANG_CXX11
  919. template <bool>
  920. struct CompileAssert {
  921. };
  922. # define GTEST_COMPILE_ASSERT_(expr, msg) \
  923. typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
  924. msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
  925. #endif // !GTEST_LANG_CXX11
  926. // Implementation details of GTEST_COMPILE_ASSERT_:
  927. //
  928. // (In C++11, we simply use static_assert instead of the following)
  929. //
  930. // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
  931. // elements (and thus is invalid) when the expression is false.
  932. //
  933. // - The simpler definition
  934. //
  935. // #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
  936. //
  937. // does not work, as gcc supports variable-length arrays whose sizes
  938. // are determined at run-time (this is gcc's extension and not part
  939. // of the C++ standard). As a result, gcc fails to reject the
  940. // following code with the simple definition:
  941. //
  942. // int foo;
  943. // GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
  944. // // not a compile-time constant.
  945. //
  946. // - By using the type CompileAssert<(bool(expr))>, we ensures that
  947. // expr is a compile-time constant. (Template arguments must be
  948. // determined at compile-time.)
  949. //
  950. // - The outter parentheses in CompileAssert<(bool(expr))> are necessary
  951. // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written
  952. //
  953. // CompileAssert<bool(expr)>
  954. //
  955. // instead, these compilers will refuse to compile
  956. //
  957. // GTEST_COMPILE_ASSERT_(5 > 0, some_message);
  958. //
  959. // (They seem to think the ">" in "5 > 0" marks the end of the
  960. // template argument list.)
  961. //
  962. // - The array size is (bool(expr) ? 1 : -1), instead of simply
  963. //
  964. // ((expr) ? 1 : -1).
  965. //
  966. // This is to avoid running into a bug in MS VC 7.1, which
  967. // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
  968. // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
  969. //
  970. // This template is declared, but intentionally undefined.
  971. template <typename T1, typename T2>
  972. struct StaticAssertTypeEqHelper;
  973. template <typename T>
  974. struct StaticAssertTypeEqHelper<T, T> {
  975. enum { value = true };
  976. };
  977. // Evaluates to the number of elements in 'array'.
  978. #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
  979. #if GTEST_HAS_GLOBAL_STRING
  980. typedef ::string string;
  981. #else
  982. typedef ::std::string string;
  983. #endif // GTEST_HAS_GLOBAL_STRING
  984. #if GTEST_HAS_GLOBAL_WSTRING
  985. typedef ::wstring wstring;
  986. #elif GTEST_HAS_STD_WSTRING
  987. typedef ::std::wstring wstring;
  988. #endif // GTEST_HAS_GLOBAL_WSTRING
  989. // A helper for suppressing warnings on constant condition. It just
  990. // returns 'condition'.
  991. GTEST_API_ bool IsTrue(bool condition);
  992. // Defines scoped_ptr.
  993. // This implementation of scoped_ptr is PARTIAL - it only contains
  994. // enough stuff to satisfy Google Test's need.
  995. template <typename T>
  996. class scoped_ptr {
  997. public:
  998. typedef T element_type;
  999. explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
  1000. ~scoped_ptr() { reset(); }
  1001. T& operator*() const { return *ptr_; }
  1002. T* operator->() const { return ptr_; }
  1003. T* get() const { return ptr_; }
  1004. T* release() {
  1005. T* const ptr = ptr_;
  1006. ptr_ = NULL;
  1007. return ptr;
  1008. }
  1009. void reset(T* p = NULL) {
  1010. if (p != ptr_) {
  1011. if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type.
  1012. delete ptr_;
  1013. }
  1014. ptr_ = p;
  1015. }
  1016. }
  1017. friend void swap(scoped_ptr& a, scoped_ptr& b) {
  1018. using std::swap;
  1019. swap(a.ptr_, b.ptr_);
  1020. }
  1021. private:
  1022. T* ptr_;
  1023. GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
  1024. };
  1025. // Defines RE.
  1026. // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
  1027. // Regular Expression syntax.
  1028. class GTEST_API_ RE {
  1029. public:
  1030. // A copy constructor is required by the Standard to initialize object
  1031. // references from r-values.
  1032. RE(const RE& other) { Init(other.pattern()); }
  1033. // Constructs an RE from a string.
  1034. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
  1035. #if GTEST_HAS_GLOBAL_STRING
  1036. RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT
  1037. #endif // GTEST_HAS_GLOBAL_STRING
  1038. RE(const char* regex) { Init(regex); } // NOLINT
  1039. ~RE();
  1040. // Returns the string representation of the regex.
  1041. const char* pattern() const { return pattern_; }
  1042. // FullMatch(str, re) returns true iff regular expression re matches
  1043. // the entire str.
  1044. // PartialMatch(str, re) returns true iff regular expression re
  1045. // matches a substring of str (including str itself).
  1046. //
  1047. // TODO(wan@google.com): make FullMatch() and PartialMatch() work
  1048. // when str contains NUL characters.
  1049. static bool FullMatch(const ::std::string& str, const RE& re) {
  1050. return FullMatch(str.c_str(), re);
  1051. }
  1052. static bool PartialMatch(const ::std::string& str, const RE& re) {
  1053. return PartialMatch(str.c_str(), re);
  1054. }
  1055. #if GTEST_HAS_GLOBAL_STRING
  1056. static bool FullMatch(const ::string& str, const RE& re) {
  1057. return FullMatch(str.c_str(), re);
  1058. }
  1059. static bool PartialMatch(const ::string& str, const RE& re) {
  1060. return PartialMatch(str.c_str(), re);
  1061. }
  1062. #endif // GTEST_HAS_GLOBAL_STRING
  1063. static bool FullMatch(const char* str, const RE& re);
  1064. static bool PartialMatch(const char* str, const RE& re);
  1065. private:
  1066. void Init(const char* regex);
  1067. // We use a const char* instead of an std::string, as Google Test used to be
  1068. // used where std::string is not available. TODO(wan@google.com): change to
  1069. // std::string.
  1070. const char* pattern_;
  1071. bool is_valid_;
  1072. #if GTEST_USES_POSIX_RE
  1073. regex_t full_regex_; // For FullMatch().
  1074. regex_t partial_regex_; // For PartialMatch().
  1075. #else // GTEST_USES_SIMPLE_RE
  1076. const char* full_pattern_; // For FullMatch();
  1077. #endif
  1078. GTEST_DISALLOW_ASSIGN_(RE);
  1079. };
  1080. // Formats a source file path and a line number as they would appear
  1081. // in an error message from the compiler used to compile this code.
  1082. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
  1083. // Formats a file location for compiler-independent XML output.
  1084. // Although this function is not platform dependent, we put it next to
  1085. // FormatFileLocation in order to contrast the two functions.
  1086. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
  1087. int line);
  1088. // Defines logging utilities:
  1089. // GTEST_LOG_(severity) - logs messages at the specified severity level. The
  1090. // message itself is streamed into the macro.
  1091. // LogToStderr() - directs all log messages to stderr.
  1092. // FlushInfoLog() - flushes informational log messages.
  1093. enum GTestLogSeverity {
  1094. GTEST_INFO,
  1095. GTEST_WARNING,
  1096. GTEST_ERROR,
  1097. GTEST_FATAL
  1098. };
  1099. // Formats log entry severity, provides a stream object for streaming the
  1100. // log message, and terminates the message with a newline when going out of
  1101. // scope.
  1102. class GTEST_API_ GTestLog {
  1103. public:
  1104. GTestLog(GTestLogSeverity severity, const char* file, int line);
  1105. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  1106. ~GTestLog();
  1107. ::std::ostream& GetStream() { return ::std::cerr; }
  1108. private:
  1109. const GTestLogSeverity severity_;
  1110. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
  1111. };
  1112. #if !defined(GTEST_LOG_)
  1113. # define GTEST_LOG_(severity) \
  1114. ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
  1115. __FILE__, __LINE__).GetStream()
  1116. inline void LogToStderr() {}
  1117. inline void FlushInfoLog() { fflush(NULL); }
  1118. #endif // !defined(GTEST_LOG_)
  1119. #if !defined(GTEST_CHECK_)
  1120. // INTERNAL IMPLEMENTATION - DO NOT USE.
  1121. //
  1122. // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
  1123. // is not satisfied.
  1124. // Synopsys:
  1125. // GTEST_CHECK_(boolean_condition);
  1126. // or
  1127. // GTEST_CHECK_(boolean_condition) << "Additional message";
  1128. //
  1129. // This checks the condition and if the condition is not satisfied
  1130. // it prints message about the condition violation, including the
  1131. // condition itself, plus additional message streamed into it, if any,
  1132. // and then it aborts the program. It aborts the program irrespective of
  1133. // whether it is built in the debug mode or not.
  1134. # define GTEST_CHECK_(condition) \
  1135. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1136. if (::testing::internal::IsTrue(condition)) \
  1137. ; \
  1138. else \
  1139. GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
  1140. #endif // !defined(GTEST_CHECK_)
  1141. // An all-mode assert to verify that the given POSIX-style function
  1142. // call returns 0 (indicating success). Known limitation: this
  1143. // doesn't expand to a balanced 'if' statement, so enclose the macro
  1144. // in {} if you need to use it as the only statement in an 'if'
  1145. // branch.
  1146. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
  1147. if (const int gtest_error = (posix_call)) \
  1148. GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
  1149. << gtest_error
  1150. #if GTEST_HAS_STD_MOVE_
  1151. using std::move;
  1152. #else // GTEST_HAS_STD_MOVE_
  1153. template <typename T>
  1154. const T& move(const T& t) {
  1155. return t;
  1156. }
  1157. #endif // GTEST_HAS_STD_MOVE_
  1158. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  1159. //
  1160. // Use ImplicitCast_ as a safe version of static_cast for upcasting in
  1161. // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
  1162. // const Foo*). When you use ImplicitCast_, the compiler checks that
  1163. // the cast is safe. Such explicit ImplicitCast_s are necessary in
  1164. // surprisingly many situations where C++ demands an exact type match
  1165. // instead of an argument type convertable to a target type.
  1166. //
  1167. // The syntax for using ImplicitCast_ is the same as for static_cast:
  1168. //
  1169. // ImplicitCast_<ToType>(expr)
  1170. //
  1171. // ImplicitCast_ would have been part of the C++ standard library,
  1172. // but the proposal was submitted too late. It will probably make
  1173. // its way into the language in the future.
  1174. //
  1175. // This relatively ugly name is intentional. It prevents clashes with
  1176. // similar functions users may have (e.g., implicit_cast). The internal
  1177. // namespace alone is not enough because the function can be found by ADL.
  1178. template<typename To>
  1179. inline To ImplicitCast_(To x) { return x; }
  1180. // When you upcast (that is, cast a pointer from type Foo to type
  1181. // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
  1182. // always succeed. When you downcast (that is, cast a pointer from
  1183. // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
  1184. // how do you know the pointer is really of type SubclassOfFoo? It
  1185. // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
  1186. // when you downcast, you should use this macro. In debug mode, we
  1187. // use dynamic_cast<> to double-check the downcast is legal (we die
  1188. // if it's not). In normal mode, we do the efficient static_cast<>
  1189. // instead. Thus, it's important to test in debug mode to make sure
  1190. // the cast is legal!
  1191. // This is the only place in the code we should use dynamic_cast<>.
  1192. // In particular, you SHOULDN'T be using dynamic_cast<> in order to
  1193. // do RTTI (eg code like this:
  1194. // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
  1195. // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
  1196. // You should design the code some other way not to need this.
  1197. //
  1198. // This relatively ugly name is intentional. It prevents clashes with
  1199. // similar functions users may have (e.g., down_cast). The internal
  1200. // namespace alone is not enough because the function can be found by ADL.
  1201. template<typename To, typename From> // use like this: DownCast_<T*>(foo);
  1202. inline To DownCast_(From* f) { // so we only accept pointers
  1203. // Ensures that To is a sub-type of From *. This test is here only
  1204. // for compile-time type checking, and has no overhead in an
  1205. // optimized build at run-time, as it will be optimized away
  1206. // completely.
  1207. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  1208. if (false) {
  1209. GTEST_INTENTIONAL_CONST_COND_POP_()
  1210. const To to = NULL;
  1211. ::testing::internal::ImplicitCast_<From*>(to);
  1212. }
  1213. #if GTEST_HAS_RTTI
  1214. // RTTI: debug mode only!
  1215. GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL);
  1216. #endif
  1217. return static_cast<To>(f);
  1218. }
  1219. // Downcasts the pointer of type Base to Derived.
  1220. // Derived must be a subclass of Base. The parameter MUST
  1221. // point to a class of type Derived, not any subclass of it.
  1222. // When RTTI is available, the function performs a runtime
  1223. // check to enforce this.
  1224. template <class Derived, class Base>
  1225. Derived* CheckedDowncastToActualType(Base* base) {
  1226. #if GTEST_HAS_RTTI
  1227. GTEST_CHECK_(typeid(*base) == typeid(Derived));
  1228. #endif
  1229. #if GTEST_HAS_DOWNCAST_
  1230. return ::down_cast<Derived*>(base);
  1231. #elif GTEST_HAS_RTTI
  1232. return dynamic_cast<Derived*>(base); // NOLINT
  1233. #else
  1234. return static_cast<Derived*>(base); // Poor man's downcast.
  1235. #endif
  1236. }
  1237. #if GTEST_HAS_STREAM_REDIRECTION
  1238. // Defines the stderr capturer:
  1239. // CaptureStdout - starts capturing stdout.
  1240. // GetCapturedStdout - stops capturing stdout and returns the captured string.
  1241. // CaptureStderr - starts capturing stderr.
  1242. // GetCapturedStderr - stops capturing stderr and returns the captured string.
  1243. //
  1244. GTEST_API_ void CaptureStdout();
  1245. GTEST_API_ std::string GetCapturedStdout();
  1246. GTEST_API_ void CaptureStderr();
  1247. GTEST_API_ std::string GetCapturedStderr();
  1248. #endif // GTEST_HAS_STREAM_REDIRECTION
  1249. // Returns a path to temporary directory.
  1250. GTEST_API_ std::string TempDir();
  1251. // Returns the size (in bytes) of a file.
  1252. GTEST_API_ size_t GetFileSize(FILE* file);
  1253. // Reads the entire content of a file as a string.
  1254. GTEST_API_ std::string ReadEntireFile(FILE* file);
  1255. // All command line arguments.
  1256. GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs();
  1257. #if GTEST_HAS_DEATH_TEST
  1258. const ::std::vector<testing::internal::string>& GetInjectableArgvs();
  1259. void SetInjectableArgvs(const ::std::vector<testing::internal::string>*
  1260. new_argvs);
  1261. #endif // GTEST_HAS_DEATH_TEST
  1262. // Defines synchronization primitives.
  1263. #if GTEST_IS_THREADSAFE
  1264. # if GTEST_HAS_PTHREAD
  1265. // Sleeps for (roughly) n milliseconds. This function is only for testing
  1266. // Google Test's own constructs. Don't use it in user tests, either
  1267. // directly or indirectly.
  1268. inline void SleepMilliseconds(int n) {
  1269. const timespec time = {
  1270. 0, // 0 seconds.
  1271. n * 1000L * 1000L, // And n ms.
  1272. };
  1273. nanosleep(&time, NULL);
  1274. }
  1275. # endif // GTEST_HAS_PTHREAD
  1276. # if GTEST_HAS_NOTIFICATION_
  1277. // Notification has already been imported into the namespace.
  1278. // Nothing to do here.
  1279. # elif GTEST_HAS_PTHREAD
  1280. // Allows a controller thread to pause execution of newly created
  1281. // threads until notified. Instances of this class must be created
  1282. // and destroyed in the controller thread.
  1283. //
  1284. // This class is only for testing Google Test's own constructs. Do not
  1285. // use it in user tests, either directly or indirectly.
  1286. class Notification {
  1287. public:
  1288. Notification() : notified_(false) {
  1289. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
  1290. }
  1291. ~Notification() {
  1292. pthread_mutex_destroy(&mutex_);
  1293. }
  1294. // Notifies all threads created with this notification to start. Must
  1295. // be called from the controller thread.
  1296. void Notify() {
  1297. pthread_mutex_lock(&mutex_);
  1298. notified_ = true;
  1299. pthread_mutex_unlock(&mutex_);
  1300. }
  1301. // Blocks until the controller thread notifies. Must be called from a test
  1302. // thread.
  1303. void WaitForNotification() {
  1304. for (;;) {
  1305. pthread_mutex_lock(&mutex_);
  1306. const bool notified = notified_;
  1307. pthread_mutex_unlock(&mutex_);
  1308. if (notified)
  1309. break;
  1310. SleepMilliseconds(10);
  1311. }
  1312. }
  1313. private:
  1314. pthread_mutex_t mutex_;
  1315. bool notified_;
  1316. GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
  1317. };
  1318. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  1319. GTEST_API_ void SleepMilliseconds(int n);
  1320. // Provides leak-safe Windows kernel handle ownership.
  1321. // Used in death tests and in threading support.
  1322. class GTEST_API_ AutoHandle {
  1323. public:
  1324. // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
  1325. // avoid including <windows.h> in this header file. Including <windows.h> is
  1326. // undesirable because it defines a lot of symbols and macros that tend to
  1327. // conflict with client code. This assumption is verified by
  1328. // WindowsTypesTest.HANDLEIsVoidStar.
  1329. typedef void* Handle;
  1330. AutoHandle();
  1331. explicit AutoHandle(Handle handle);
  1332. ~AutoHandle();
  1333. Handle Get() const;
  1334. void Reset();
  1335. void Reset(Handle handle);
  1336. private:
  1337. // Returns true iff the handle is a valid handle object that can be closed.
  1338. bool IsCloseable() const;
  1339. Handle handle_;
  1340. GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
  1341. };
  1342. // Allows a controller thread to pause execution of newly created
  1343. // threads until notified. Instances of this class must be created
  1344. // and destroyed in the controller thread.
  1345. //
  1346. // This class is only for testing Google Test's own constructs. Do not
  1347. // use it in user tests, either directly or indirectly.
  1348. class GTEST_API_ Notification {
  1349. public:
  1350. Notification();
  1351. void Notify();
  1352. void WaitForNotification();
  1353. private:
  1354. AutoHandle event_;
  1355. GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
  1356. };
  1357. # endif // GTEST_HAS_NOTIFICATION_
  1358. // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
  1359. // defined, but we don't want to use MinGW's pthreads implementation, which
  1360. // has conformance problems with some versions of the POSIX standard.
  1361. # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
  1362. // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
  1363. // Consequently, it cannot select a correct instantiation of ThreadWithParam
  1364. // in order to call its Run(). Introducing ThreadWithParamBase as a
  1365. // non-templated base class for ThreadWithParam allows us to bypass this
  1366. // problem.
  1367. class ThreadWithParamBase {
  1368. public:
  1369. virtual ~ThreadWithParamBase() {}
  1370. virtual void Run() = 0;
  1371. };
  1372. // pthread_create() accepts a pointer to a function type with the C linkage.
  1373. // According to the Standard (7.5/1), function types with different linkages
  1374. // are different even if they are otherwise identical. Some compilers (for
  1375. // example, SunStudio) treat them as different types. Since class methods
  1376. // cannot be defined with C-linkage we need to define a free C-function to
  1377. // pass into pthread_create().
  1378. extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
  1379. static_cast<ThreadWithParamBase*>(thread)->Run();
  1380. return NULL;
  1381. }
  1382. // Helper class for testing Google Test's multi-threading constructs.
  1383. // To use it, write:
  1384. //
  1385. // void ThreadFunc(int param) { /* Do things with param */ }
  1386. // Notification thread_can_start;
  1387. // ...
  1388. // // The thread_can_start parameter is optional; you can supply NULL.
  1389. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
  1390. // thread_can_start.Notify();
  1391. //
  1392. // These classes are only for testing Google Test's own constructs. Do
  1393. // not use them in user tests, either directly or indirectly.
  1394. template <typename T>
  1395. class ThreadWithParam : public ThreadWithParamBase {
  1396. public:
  1397. typedef void UserThreadFunc(T);
  1398. ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
  1399. : func_(func),
  1400. param_(param),
  1401. thread_can_start_(thread_can_start),
  1402. finished_(false) {
  1403. ThreadWithParamBase* const base = this;
  1404. // The thread can be created only after all fields except thread_
  1405. // have been initialized.
  1406. GTEST_CHECK_POSIX_SUCCESS_(
  1407. pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
  1408. }
  1409. ~ThreadWithParam() { Join(); }
  1410. void Join() {
  1411. if (!finished_) {
  1412. GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
  1413. finished_ = true;
  1414. }
  1415. }
  1416. virtual void Run() {
  1417. if (thread_can_start_ != NULL)
  1418. thread_can_start_->WaitForNotification();
  1419. func_(param_);
  1420. }
  1421. private:
  1422. UserThreadFunc* const func_; // User-supplied thread function.
  1423. const T param_; // User-supplied parameter to the thread function.
  1424. // When non-NULL, used to block execution until the controller thread
  1425. // notifies.
  1426. Notification* const thread_can_start_;
  1427. bool finished_; // true iff we know that the thread function has finished.
  1428. pthread_t thread_; // The native thread object.
  1429. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
  1430. };
  1431. # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
  1432. // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1433. # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1434. // Mutex and ThreadLocal have already been imported into the namespace.
  1435. // Nothing to do here.
  1436. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  1437. // Mutex implements mutex on Windows platforms. It is used in conjunction
  1438. // with class MutexLock:
  1439. //
  1440. // Mutex mutex;
  1441. // ...
  1442. // MutexLock lock(&mutex); // Acquires the mutex and releases it at the
  1443. // // end of the current scope.
  1444. //
  1445. // A static Mutex *must* be defined or declared using one of the following
  1446. // macros:
  1447. // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
  1448. // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
  1449. //
  1450. // (A non-static Mutex is defined/declared in the usual way).
  1451. class GTEST_API_ Mutex {
  1452. public:
  1453. enum MutexType { kStatic = 0, kDynamic = 1 };
  1454. // We rely on kStaticMutex being 0 as it is to what the linker initializes
  1455. // type_ in static mutexes. critical_section_ will be initialized lazily
  1456. // in ThreadSafeLazyInit().
  1457. enum StaticConstructorSelector { kStaticMutex = 0 };
  1458. // This constructor intentionally does nothing. It relies on type_ being
  1459. // statically initialized to 0 (effectively setting it to kStatic) and on
  1460. // ThreadSafeLazyInit() to lazily initialize the rest of the members.
  1461. explicit Mutex(StaticConstructorSelector /*dummy*/) {}
  1462. Mutex();
  1463. ~Mutex();
  1464. void Lock();
  1465. void Unlock();
  1466. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  1467. // with high probability.
  1468. void AssertHeld();
  1469. private:
  1470. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  1471. void ThreadSafeLazyInit();
  1472. // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx,
  1473. // we assume that 0 is an invalid value for thread IDs.
  1474. unsigned int owner_thread_id_;
  1475. // For static mutexes, we rely on these members being initialized to zeros
  1476. // by the linker.
  1477. MutexType type_;
  1478. long critical_section_init_phase_; // NOLINT
  1479. _RTL_CRITICAL_SECTION* critical_section_;
  1480. GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
  1481. };
  1482. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1483. extern ::testing::internal::Mutex mutex
  1484. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
  1485. ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
  1486. // We cannot name this class MutexLock because the ctor declaration would
  1487. // conflict with a macro named MutexLock, which is defined on some
  1488. // platforms. That macro is used as a defensive measure to prevent against
  1489. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1490. // "MutexLock l(&mu)". Hence the typedef trick below.
  1491. class GTestMutexLock {
  1492. public:
  1493. explicit GTestMutexLock(Mutex* mutex)
  1494. : mutex_(mutex) { mutex_->Lock(); }
  1495. ~GTestMutexLock() { mutex_->Unlock(); }
  1496. private:
  1497. Mutex* const mutex_;
  1498. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
  1499. };
  1500. typedef GTestMutexLock MutexLock;
  1501. // Base class for ValueHolder<T>. Allows a caller to hold and delete a value
  1502. // without knowing its type.
  1503. class ThreadLocalValueHolderBase {
  1504. public:
  1505. virtual ~ThreadLocalValueHolderBase() {}
  1506. };
  1507. // Provides a way for a thread to send notifications to a ThreadLocal
  1508. // regardless of its parameter type.
  1509. class ThreadLocalBase {
  1510. public:
  1511. // Creates a new ValueHolder<T> object holding a default value passed to
  1512. // this ThreadLocal<T>'s constructor and returns it. It is the caller's
  1513. // responsibility not to call this when the ThreadLocal<T> instance already
  1514. // has a value on the current thread.
  1515. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
  1516. protected:
  1517. ThreadLocalBase() {}
  1518. virtual ~ThreadLocalBase() {}
  1519. private:
  1520. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
  1521. };
  1522. // Maps a thread to a set of ThreadLocals that have values instantiated on that
  1523. // thread and notifies them when the thread exits. A ThreadLocal instance is
  1524. // expected to persist until all threads it has values on have terminated.
  1525. class GTEST_API_ ThreadLocalRegistry {
  1526. public:
  1527. // Registers thread_local_instance as having value on the current thread.
  1528. // Returns a value that can be used to identify the thread from other threads.
  1529. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  1530. const ThreadLocalBase* thread_local_instance);
  1531. // Invoked when a ThreadLocal instance is destroyed.
  1532. static void OnThreadLocalDestroyed(
  1533. const ThreadLocalBase* thread_local_instance);
  1534. };
  1535. class GTEST_API_ ThreadWithParamBase {
  1536. public:
  1537. void Join();
  1538. protected:
  1539. class Runnable {
  1540. public:
  1541. virtual ~Runnable() {}
  1542. virtual void Run() = 0;
  1543. };
  1544. ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
  1545. virtual ~ThreadWithParamBase();
  1546. private:
  1547. AutoHandle thread_;
  1548. };
  1549. // Helper class for testing Google Test's multi-threading constructs.
  1550. template <typename T>
  1551. class ThreadWithParam : public ThreadWithParamBase {
  1552. public:
  1553. typedef void UserThreadFunc(T);
  1554. ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
  1555. : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
  1556. }
  1557. virtual ~ThreadWithParam() {}
  1558. private:
  1559. class RunnableImpl : public Runnable {
  1560. public:
  1561. RunnableImpl(UserThreadFunc* func, T param)
  1562. : func_(func),
  1563. param_(param) {
  1564. }
  1565. virtual ~RunnableImpl() {}
  1566. virtual void Run() {
  1567. func_(param_);
  1568. }
  1569. private:
  1570. UserThreadFunc* const func_;
  1571. const T param_;
  1572. GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
  1573. };
  1574. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
  1575. };
  1576. // Implements thread-local storage on Windows systems.
  1577. //
  1578. // // Thread 1
  1579. // ThreadLocal<int> tl(100); // 100 is the default value for each thread.
  1580. //
  1581. // // Thread 2
  1582. // tl.set(150); // Changes the value for thread 2 only.
  1583. // EXPECT_EQ(150, tl.get());
  1584. //
  1585. // // Thread 1
  1586. // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
  1587. // tl.set(200);
  1588. // EXPECT_EQ(200, tl.get());
  1589. //
  1590. // The template type argument T must have a public copy constructor.
  1591. // In addition, the default ThreadLocal constructor requires T to have
  1592. // a public default constructor.
  1593. //
  1594. // The users of a TheadLocal instance have to make sure that all but one
  1595. // threads (including the main one) using that instance have exited before
  1596. // destroying it. Otherwise, the per-thread objects managed for them by the
  1597. // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
  1598. //
  1599. // Google Test only uses global ThreadLocal objects. That means they
  1600. // will die after main() has returned. Therefore, no per-thread
  1601. // object managed by Google Test will be leaked as long as all threads
  1602. // using Google Test have exited when main() returns.
  1603. template <typename T>
  1604. class ThreadLocal : public ThreadLocalBase {
  1605. public:
  1606. ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
  1607. explicit ThreadLocal(const T& value)
  1608. : default_factory_(new InstanceValueHolderFactory(value)) {}
  1609. ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
  1610. T* pointer() { return GetOrCreateValue(); }
  1611. const T* pointer() const { return GetOrCreateValue(); }
  1612. const T& get() const { return *pointer(); }
  1613. void set(const T& value) { *pointer() = value; }
  1614. private:
  1615. // Holds a value of T. Can be deleted via its base class without the caller
  1616. // knowing the type of T.
  1617. class ValueHolder : public ThreadLocalValueHolderBase {
  1618. public:
  1619. ValueHolder() : value_() {}
  1620. explicit ValueHolder(const T& value) : value_(value) {}
  1621. T* pointer() { return &value_; }
  1622. private:
  1623. T value_;
  1624. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
  1625. };
  1626. T* GetOrCreateValue() const {
  1627. return static_cast<ValueHolder*>(
  1628. ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
  1629. }
  1630. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
  1631. return default_factory_->MakeNewHolder();
  1632. }
  1633. class ValueHolderFactory {
  1634. public:
  1635. ValueHolderFactory() {}
  1636. virtual ~ValueHolderFactory() {}
  1637. virtual ValueHolder* MakeNewHolder() const = 0;
  1638. private:
  1639. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
  1640. };
  1641. class DefaultValueHolderFactory : public ValueHolderFactory {
  1642. public:
  1643. DefaultValueHolderFactory() {}
  1644. virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
  1645. private:
  1646. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
  1647. };
  1648. class InstanceValueHolderFactory : public ValueHolderFactory {
  1649. public:
  1650. explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
  1651. virtual ValueHolder* MakeNewHolder() const {
  1652. return new ValueHolder(value_);
  1653. }
  1654. private:
  1655. const T value_; // The value for each thread.
  1656. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
  1657. };
  1658. scoped_ptr<ValueHolderFactory> default_factory_;
  1659. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
  1660. };
  1661. # elif GTEST_HAS_PTHREAD
  1662. // MutexBase and Mutex implement mutex on pthreads-based platforms.
  1663. class MutexBase {
  1664. public:
  1665. // Acquires this mutex.
  1666. void Lock() {
  1667. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
  1668. owner_ = pthread_self();
  1669. has_owner_ = true;
  1670. }
  1671. // Releases this mutex.
  1672. void Unlock() {
  1673. // Since the lock is being released the owner_ field should no longer be
  1674. // considered valid. We don't protect writing to has_owner_ here, as it's
  1675. // the caller's responsibility to ensure that the current thread holds the
  1676. // mutex when this is called.
  1677. has_owner_ = false;
  1678. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
  1679. }
  1680. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  1681. // with high probability.
  1682. void AssertHeld() const {
  1683. GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
  1684. << "The current thread is not holding the mutex @" << this;
  1685. }
  1686. // A static mutex may be used before main() is entered. It may even
  1687. // be used before the dynamic initialization stage. Therefore we
  1688. // must be able to initialize a static mutex object at link time.
  1689. // This means MutexBase has to be a POD and its member variables
  1690. // have to be public.
  1691. public:
  1692. pthread_mutex_t mutex_; // The underlying pthread mutex.
  1693. // has_owner_ indicates whether the owner_ field below contains a valid thread
  1694. // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
  1695. // accesses to the owner_ field should be protected by a check of this field.
  1696. // An alternative might be to memset() owner_ to all zeros, but there's no
  1697. // guarantee that a zero'd pthread_t is necessarily invalid or even different
  1698. // from pthread_self().
  1699. bool has_owner_;
  1700. pthread_t owner_; // The thread holding the mutex.
  1701. };
  1702. // Forward-declares a static mutex.
  1703. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1704. extern ::testing::internal::MutexBase mutex
  1705. // Defines and statically (i.e. at link time) initializes a static mutex.
  1706. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
  1707. ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, pthread_t() }
  1708. // The Mutex class can only be used for mutexes created at runtime. It
  1709. // shares its API with MutexBase otherwise.
  1710. class Mutex : public MutexBase {
  1711. public:
  1712. Mutex() {
  1713. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
  1714. has_owner_ = false;
  1715. }
  1716. ~Mutex() {
  1717. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
  1718. }
  1719. private:
  1720. GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
  1721. };
  1722. // We cannot name this class MutexLock because the ctor declaration would
  1723. // conflict with a macro named MutexLock, which is defined on some
  1724. // platforms. That macro is used as a defensive measure to prevent against
  1725. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1726. // "MutexLock l(&mu)". Hence the typedef trick below.
  1727. class GTestMutexLock {
  1728. public:
  1729. explicit GTestMutexLock(MutexBase* mutex)
  1730. : mutex_(mutex) { mutex_->Lock(); }
  1731. ~GTestMutexLock() { mutex_->Unlock(); }
  1732. private:
  1733. MutexBase* const mutex_;
  1734. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
  1735. };
  1736. typedef GTestMutexLock MutexLock;
  1737. // Helpers for ThreadLocal.
  1738. // pthread_key_create() requires DeleteThreadLocalValue() to have
  1739. // C-linkage. Therefore it cannot be templatized to access
  1740. // ThreadLocal<T>. Hence the need for class
  1741. // ThreadLocalValueHolderBase.
  1742. class ThreadLocalValueHolderBase {
  1743. public:
  1744. virtual ~ThreadLocalValueHolderBase() {}
  1745. };
  1746. // Called by pthread to delete thread-local data stored by
  1747. // pthread_setspecific().
  1748. extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
  1749. delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
  1750. }
  1751. // Implements thread-local storage on pthreads-based systems.
  1752. template <typename T>
  1753. class ThreadLocal {
  1754. public:
  1755. ThreadLocal()
  1756. : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
  1757. explicit ThreadLocal(const T& value)
  1758. : key_(CreateKey()),
  1759. default_factory_(new InstanceValueHolderFactory(value)) {}
  1760. ~ThreadLocal() {
  1761. // Destroys the managed object for the current thread, if any.
  1762. DeleteThreadLocalValue(pthread_getspecific(key_));
  1763. // Releases resources associated with the key. This will *not*
  1764. // delete managed objects for other threads.
  1765. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
  1766. }
  1767. T* pointer() { return GetOrCreateValue(); }
  1768. const T* pointer() const { return GetOrCreateValue(); }
  1769. const T& get() const { return *pointer(); }
  1770. void set(const T& value) { *pointer() = value; }
  1771. private:
  1772. // Holds a value of type T.
  1773. class ValueHolder : public ThreadLocalValueHolderBase {
  1774. public:
  1775. ValueHolder() : value_() {}
  1776. explicit ValueHolder(const T& value) : value_(value) {}
  1777. T* pointer() { return &value_; }
  1778. private:
  1779. T value_;
  1780. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
  1781. };
  1782. static pthread_key_t CreateKey() {
  1783. pthread_key_t key;
  1784. // When a thread exits, DeleteThreadLocalValue() will be called on
  1785. // the object managed for that thread.
  1786. GTEST_CHECK_POSIX_SUCCESS_(
  1787. pthread_key_create(&key, &DeleteThreadLocalValue));
  1788. return key;
  1789. }
  1790. T* GetOrCreateValue() const {
  1791. ThreadLocalValueHolderBase* const holder =
  1792. static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
  1793. if (holder != NULL) {
  1794. return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
  1795. }
  1796. ValueHolder* const new_holder = default_factory_->MakeNewHolder();
  1797. ThreadLocalValueHolderBase* const holder_base = new_holder;
  1798. GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
  1799. return new_holder->pointer();
  1800. }
  1801. class ValueHolderFactory {
  1802. public:
  1803. ValueHolderFactory() {}
  1804. virtual ~ValueHolderFactory() {}
  1805. virtual ValueHolder* MakeNewHolder() const = 0;
  1806. private:
  1807. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
  1808. };
  1809. class DefaultValueHolderFactory : public ValueHolderFactory {
  1810. public:
  1811. DefaultValueHolderFactory() {}
  1812. virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); }
  1813. private:
  1814. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
  1815. };
  1816. class InstanceValueHolderFactory : public ValueHolderFactory {
  1817. public:
  1818. explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
  1819. virtual ValueHolder* MakeNewHolder() const {
  1820. return new ValueHolder(value_);
  1821. }
  1822. private:
  1823. const T value_; // The value for each thread.
  1824. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
  1825. };
  1826. // A key pthreads uses for looking up per-thread values.
  1827. const pthread_key_t key_;
  1828. scoped_ptr<ValueHolderFactory> default_factory_;
  1829. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
  1830. };
  1831. # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1832. #else // GTEST_IS_THREADSAFE
  1833. // A dummy implementation of synchronization primitives (mutex, lock,
  1834. // and thread-local variable). Necessary for compiling Google Test where
  1835. // mutex is not supported - using Google Test in multiple threads is not
  1836. // supported on such platforms.
  1837. class Mutex {
  1838. public:
  1839. Mutex() {}
  1840. void Lock() {}
  1841. void Unlock() {}
  1842. void AssertHeld() const {}
  1843. };
  1844. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1845. extern ::testing::internal::Mutex mutex
  1846. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
  1847. // We cannot name this class MutexLock because the ctor declaration would
  1848. // conflict with a macro named MutexLock, which is defined on some
  1849. // platforms. That macro is used as a defensive measure to prevent against
  1850. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1851. // "MutexLock l(&mu)". Hence the typedef trick below.
  1852. class GTestMutexLock {
  1853. public:
  1854. explicit GTestMutexLock(Mutex*) {} // NOLINT
  1855. };
  1856. typedef GTestMutexLock MutexLock;
  1857. template <typename T>
  1858. class ThreadLocal {
  1859. public:
  1860. ThreadLocal() : value_() {}
  1861. explicit ThreadLocal(const T& value) : value_(value) {}
  1862. T* pointer() { return &value_; }
  1863. const T* pointer() const { return &value_; }
  1864. const T& get() const { return value_; }
  1865. void set(const T& value) { value_ = value; }
  1866. private:
  1867. T value_;
  1868. };
  1869. #endif // GTEST_IS_THREADSAFE
  1870. // Returns the number of threads running in the process, or 0 to indicate that
  1871. // we cannot detect it.
  1872. GTEST_API_ size_t GetThreadCount();
  1873. // Passing non-POD classes through ellipsis (...) crashes the ARM
  1874. // compiler and generates a warning in Sun Studio. The Nokia Symbian
  1875. // and the IBM XL C/C++ compiler try to instantiate a copy constructor
  1876. // for objects passed through ellipsis (...), failing for uncopyable
  1877. // objects. We define this to ensure that only POD is passed through
  1878. // ellipsis on these systems.
  1879. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC)
  1880. // We lose support for NULL detection where the compiler doesn't like
  1881. // passing non-POD classes through ellipsis (...).
  1882. # define GTEST_ELLIPSIS_NEEDS_POD_ 1
  1883. #else
  1884. # define GTEST_CAN_COMPARE_NULL 1
  1885. #endif
  1886. // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between
  1887. // const T& and const T* in a function template. These compilers
  1888. // _can_ decide between class template specializations for T and T*,
  1889. // so a tr1::type_traits-like is_pointer works.
  1890. #if defined(__SYMBIAN32__) || defined(__IBMCPP__)
  1891. # define GTEST_NEEDS_IS_POINTER_ 1
  1892. #endif
  1893. template <bool bool_value>
  1894. struct bool_constant {
  1895. typedef bool_constant<bool_value> type;
  1896. static const bool value = bool_value;
  1897. };
  1898. template <bool bool_value> const bool bool_constant<bool_value>::value;
  1899. typedef bool_constant<false> false_type;
  1900. typedef bool_constant<true> true_type;
  1901. template <typename T>
  1902. struct is_pointer : public false_type {};
  1903. template <typename T>
  1904. struct is_pointer<T*> : public true_type {};
  1905. template <typename Iterator>
  1906. struct IteratorTraits {
  1907. typedef typename Iterator::value_type value_type;
  1908. };
  1909. template <typename T>
  1910. struct IteratorTraits<T*> {
  1911. typedef T value_type;
  1912. };
  1913. template <typename T>
  1914. struct IteratorTraits<const T*> {
  1915. typedef T value_type;
  1916. };
  1917. #if GTEST_OS_WINDOWS
  1918. # define GTEST_PATH_SEP_ "\\"
  1919. # define GTEST_HAS_ALT_PATH_SEP_ 1
  1920. // The biggest signed integer type the compiler supports.
  1921. typedef __int64 BiggestInt;
  1922. #else
  1923. # define GTEST_PATH_SEP_ "/"
  1924. # define GTEST_HAS_ALT_PATH_SEP_ 0
  1925. typedef long long BiggestInt; // NOLINT
  1926. #endif // GTEST_OS_WINDOWS
  1927. // Utilities for char.
  1928. // isspace(int ch) and friends accept an unsigned char or EOF. char
  1929. // may be signed, depending on the compiler (or compiler flags).
  1930. // Therefore we need to cast a char to unsigned char before calling
  1931. // isspace(), etc.
  1932. inline bool IsAlpha(char ch) {
  1933. return isalpha(static_cast<unsigned char>(ch)) != 0;
  1934. }
  1935. inline bool IsAlNum(char ch) {
  1936. return isalnum(static_cast<unsigned char>(ch)) != 0;
  1937. }
  1938. inline bool IsDigit(char ch) {
  1939. return isdigit(static_cast<unsigned char>(ch)) != 0;
  1940. }
  1941. inline bool IsLower(char ch) {
  1942. return islower(static_cast<unsigned char>(ch)) != 0;
  1943. }
  1944. inline bool IsSpace(char ch) {
  1945. return isspace(static_cast<unsigned char>(ch)) != 0;
  1946. }
  1947. inline bool IsUpper(char ch) {
  1948. return isupper(static_cast<unsigned char>(ch)) != 0;
  1949. }
  1950. inline bool IsXDigit(char ch) {
  1951. return isxdigit(static_cast<unsigned char>(ch)) != 0;
  1952. }
  1953. inline bool IsXDigit(wchar_t ch) {
  1954. const unsigned char low_byte = static_cast<unsigned char>(ch);
  1955. return ch == low_byte && isxdigit(low_byte) != 0;
  1956. }
  1957. inline char ToLower(char ch) {
  1958. return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
  1959. }
  1960. inline char ToUpper(char ch) {
  1961. return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
  1962. }
  1963. inline std::string StripTrailingSpaces(std::string str) {
  1964. std::string::iterator it = str.end();
  1965. while (it != str.begin() && IsSpace(*--it))
  1966. it = str.erase(it);
  1967. return str;
  1968. }
  1969. // The testing::internal::posix namespace holds wrappers for common
  1970. // POSIX functions. These wrappers hide the differences between
  1971. // Windows/MSVC and POSIX systems. Since some compilers define these
  1972. // standard functions as macros, the wrapper cannot have the same name
  1973. // as the wrapped function.
  1974. namespace posix {
  1975. // Functions with a different name on Windows.
  1976. #if GTEST_OS_WINDOWS
  1977. typedef struct _stat StatStruct;
  1978. # ifdef __BORLANDC__
  1979. inline int IsATTY(int fd) { return isatty(fd); }
  1980. inline int StrCaseCmp(const char* s1, const char* s2) {
  1981. return stricmp(s1, s2);
  1982. }
  1983. inline char* StrDup(const char* src) { return strdup(src); }
  1984. # else // !__BORLANDC__
  1985. # if GTEST_OS_WINDOWS_MOBILE
  1986. inline int IsATTY(int /* fd */) { return 0; }
  1987. # else
  1988. inline int IsATTY(int fd) { return _isatty(fd); }
  1989. # endif // GTEST_OS_WINDOWS_MOBILE
  1990. inline int StrCaseCmp(const char* s1, const char* s2) {
  1991. return _stricmp(s1, s2);
  1992. }
  1993. inline char* StrDup(const char* src) { return _strdup(src); }
  1994. # endif // __BORLANDC__
  1995. # if GTEST_OS_WINDOWS_MOBILE
  1996. inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
  1997. // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
  1998. // time and thus not defined there.
  1999. # else
  2000. inline int FileNo(FILE* file) { return _fileno(file); }
  2001. inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
  2002. inline int RmDir(const char* dir) { return _rmdir(dir); }
  2003. inline bool IsDir(const StatStruct& st) {
  2004. return (_S_IFDIR & st.st_mode) != 0;
  2005. }
  2006. # endif // GTEST_OS_WINDOWS_MOBILE
  2007. #else
  2008. typedef struct stat StatStruct;
  2009. inline int FileNo(FILE* file) { return fileno(file); }
  2010. inline int IsATTY(int fd) { return isatty(fd); }
  2011. inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
  2012. inline int StrCaseCmp(const char* s1, const char* s2) {
  2013. return strcasecmp(s1, s2);
  2014. }
  2015. inline char* StrDup(const char* src) { return strdup(src); }
  2016. inline int RmDir(const char* dir) { return rmdir(dir); }
  2017. inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
  2018. #endif // GTEST_OS_WINDOWS
  2019. // Functions deprecated by MSVC 8.0.
  2020. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
  2021. inline const char* StrNCpy(char* dest, const char* src, size_t n) {
  2022. return strncpy(dest, src, n);
  2023. }
  2024. // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
  2025. // StrError() aren't needed on Windows CE at this time and thus not
  2026. // defined there.
  2027. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  2028. inline int ChDir(const char* dir) { return chdir(dir); }
  2029. #endif
  2030. inline FILE* FOpen(const char* path, const char* mode) {
  2031. return fopen(path, mode);
  2032. }
  2033. #if !GTEST_OS_WINDOWS_MOBILE
  2034. inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
  2035. return freopen(path, mode, stream);
  2036. }
  2037. inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
  2038. #endif
  2039. inline int FClose(FILE* fp) { return fclose(fp); }
  2040. #if !GTEST_OS_WINDOWS_MOBILE
  2041. inline int Read(int fd, void* buf, unsigned int count) {
  2042. return static_cast<int>(read(fd, buf, count));
  2043. }
  2044. inline int Write(int fd, const void* buf, unsigned int count) {
  2045. return static_cast<int>(write(fd, buf, count));
  2046. }
  2047. inline int Close(int fd) { return close(fd); }
  2048. inline const char* StrError(int errnum) { return strerror(errnum); }
  2049. #endif
  2050. inline const char* GetEnv(const char* name) {
  2051. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT
  2052. // We are on Windows CE, which has no environment variables.
  2053. static_cast<void>(name); // To prevent 'unused argument' warning.
  2054. return NULL;
  2055. #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
  2056. // Environment variables which we programmatically clear will be set to the
  2057. // empty string rather than unset (NULL). Handle that case.
  2058. const char* const env = getenv(name);
  2059. return (env != NULL && env[0] != '\0') ? env : NULL;
  2060. #else
  2061. return getenv(name);
  2062. #endif
  2063. }
  2064. GTEST_DISABLE_MSC_WARNINGS_POP_()
  2065. #if GTEST_OS_WINDOWS_MOBILE
  2066. // Windows CE has no C library. The abort() function is used in
  2067. // several places in Google Test. This implementation provides a reasonable
  2068. // imitation of standard behaviour.
  2069. void Abort();
  2070. #else
  2071. inline void Abort() { abort(); }
  2072. #endif // GTEST_OS_WINDOWS_MOBILE
  2073. } // namespace posix
  2074. // MSVC "deprecates" snprintf and issues warnings wherever it is used. In
  2075. // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
  2076. // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
  2077. // function in order to achieve that. We use macro definition here because
  2078. // snprintf is a variadic function.
  2079. #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  2080. // MSVC 2005 and above support variadic macros.
  2081. # define GTEST_SNPRINTF_(buffer, size, format, ...) \
  2082. _snprintf_s(buffer, size, size, format, __VA_ARGS__)
  2083. #elif defined(_MSC_VER)
  2084. // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't
  2085. // complain about _snprintf.
  2086. # define GTEST_SNPRINTF_ _snprintf
  2087. #else
  2088. # define GTEST_SNPRINTF_ snprintf
  2089. #endif
  2090. // The maximum number a BiggestInt can represent. This definition
  2091. // works no matter BiggestInt is represented in one's complement or
  2092. // two's complement.
  2093. //
  2094. // We cannot rely on numeric_limits in STL, as __int64 and long long
  2095. // are not part of standard C++ and numeric_limits doesn't need to be
  2096. // defined for them.
  2097. const BiggestInt kMaxBiggestInt =
  2098. ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
  2099. // This template class serves as a compile-time function from size to
  2100. // type. It maps a size in bytes to a primitive type with that
  2101. // size. e.g.
  2102. //
  2103. // TypeWithSize<4>::UInt
  2104. //
  2105. // is typedef-ed to be unsigned int (unsigned integer made up of 4
  2106. // bytes).
  2107. //
  2108. // Such functionality should belong to STL, but I cannot find it
  2109. // there.
  2110. //
  2111. // Google Test uses this class in the implementation of floating-point
  2112. // comparison.
  2113. //
  2114. // For now it only handles UInt (unsigned int) as that's all Google Test
  2115. // needs. Other types can be easily added in the future if need
  2116. // arises.
  2117. template <size_t size>
  2118. class TypeWithSize {
  2119. public:
  2120. // This prevents the user from using TypeWithSize<N> with incorrect
  2121. // values of N.
  2122. typedef void UInt;
  2123. };
  2124. // The specialization for size 4.
  2125. template <>
  2126. class TypeWithSize<4> {
  2127. public:
  2128. // unsigned int has size 4 in both gcc and MSVC.
  2129. //
  2130. // As base/basictypes.h doesn't compile on Windows, we cannot use
  2131. // uint32, uint64, and etc here.
  2132. typedef int Int;
  2133. typedef unsigned int UInt;
  2134. };
  2135. // The specialization for size 8.
  2136. template <>
  2137. class TypeWithSize<8> {
  2138. public:
  2139. #if GTEST_OS_WINDOWS
  2140. typedef __int64 Int;
  2141. typedef unsigned __int64 UInt;
  2142. #else
  2143. typedef long long Int; // NOLINT
  2144. typedef unsigned long long UInt; // NOLINT
  2145. #endif // GTEST_OS_WINDOWS
  2146. };
  2147. // Integer types of known sizes.
  2148. typedef TypeWithSize<4>::Int Int32;
  2149. typedef TypeWithSize<4>::UInt UInt32;
  2150. typedef TypeWithSize<8>::Int Int64;
  2151. typedef TypeWithSize<8>::UInt UInt64;
  2152. typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
  2153. // Utilities for command line flags and environment variables.
  2154. // Macro for referencing flags.
  2155. #if !defined(GTEST_FLAG)
  2156. # define GTEST_FLAG(name) FLAGS_gtest_##name
  2157. #endif // !defined(GTEST_FLAG)
  2158. #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
  2159. # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
  2160. #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
  2161. #if !defined(GTEST_DECLARE_bool_)
  2162. # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
  2163. // Macros for declaring flags.
  2164. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
  2165. # define GTEST_DECLARE_int32_(name) \
  2166. GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name)
  2167. #define GTEST_DECLARE_string_(name) \
  2168. GTEST_API_ extern ::std::string GTEST_FLAG(name)
  2169. // Macros for defining flags.
  2170. #define GTEST_DEFINE_bool_(name, default_val, doc) \
  2171. GTEST_API_ bool GTEST_FLAG(name) = (default_val)
  2172. #define GTEST_DEFINE_int32_(name, default_val, doc) \
  2173. GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
  2174. #define GTEST_DEFINE_string_(name, default_val, doc) \
  2175. GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
  2176. #endif // !defined(GTEST_DECLARE_bool_)
  2177. // Thread annotations
  2178. #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
  2179. # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
  2180. # define GTEST_LOCK_EXCLUDED_(locks)
  2181. #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
  2182. // Parses 'str' for a 32-bit signed integer. If successful, writes the result
  2183. // to *value and returns true; otherwise leaves *value unchanged and returns
  2184. // false.
  2185. // TODO(chandlerc): Find a better way to refactor flag and environment parsing
  2186. // out of both gtest-port.cc and gtest.cc to avoid exporting this utility
  2187. // function.
  2188. bool ParseInt32(const Message& src_text, const char* str, Int32* value);
  2189. // Parses a bool/Int32/string from the environment variable
  2190. // corresponding to the given Google Test flag.
  2191. bool BoolFromGTestEnv(const char* flag, bool default_val);
  2192. GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
  2193. std::string StringFromGTestEnv(const char* flag, const char* default_val);
  2194. } // namespace internal
  2195. } // namespace testing
  2196. #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_