gtest-port.h 87 KB

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