gtest-port.h 83 KB

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