gtest-port.h 78 KB

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