gtest-port.h 88 KB

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