gtest-port.h 86 KB

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