PageRenderTime 41ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/src/qt/qtbase/src/corelib/global/qglobalstatic.cpp

https://gitlab.com/x33n/phantomjs
C++ | 524 lines | 1 code | 11 blank | 512 comment | 0 complexity | f252ea439133aa9e7bb48b158a89095b MD5 | raw file
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2013 Intel Corporation.
  4. ** Contact: http://www.qt-project.org/legal
  5. **
  6. ** This file is part of the QtCore module of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and Digia. For licensing terms and
  14. ** conditions see http://qt.digia.com/licensing. For further information
  15. ** use the contact form at http://qt.digia.com/contact-us.
  16. **
  17. ** GNU Lesser General Public License Usage
  18. ** Alternatively, this file may be used under the terms of the GNU Lesser
  19. ** General Public License version 2.1 as published by the Free Software
  20. ** Foundation and appearing in the file LICENSE.LGPL included in the
  21. ** packaging of this file. Please review the following information to
  22. ** ensure the GNU Lesser General Public License version 2.1 requirements
  23. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  24. **
  25. ** In addition, as a special exception, Digia gives you certain additional
  26. ** rights. These rights are described in the Digia Qt LGPL Exception
  27. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  28. **
  29. ** GNU General Public License Usage
  30. ** Alternatively, this file may be used under the terms of the GNU
  31. ** General Public License version 3.0 as published by the Free Software
  32. ** Foundation and appearing in the file LICENSE.GPL included in the
  33. ** packaging of this file. Please review the following information to
  34. ** ensure the GNU General Public License version 3.0 requirements will be
  35. ** met: http://www.gnu.org/copyleft/gpl.html.
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include "qglobalstatic.h"
  42. /*!
  43. \macro Q_GLOBAL_STATIC(Type, VariableName)
  44. \since 5.1
  45. \relates QGlobalStatic
  46. Creates a global and static object of type \l QGlobalStatic, of name \a
  47. VariableName and that behaves as a pointer to \a Type. The object created
  48. by Q_GLOBAL_STATIC initializes itself on the first use, which means that it
  49. will not increase the application or the library's load time. Additionally,
  50. the object is initialized in a thread-safe manner on all platforms.
  51. The typical use of this macro is as follows, in a global context (that is,
  52. outside of any function bodies):
  53. \code
  54. Q_GLOBAL_STATIC(MyType, staticType)
  55. \endcode
  56. This macro is intended to replace global static objects that are not POD
  57. (Plain Old Data, or in C++11 terms, not made of a trivial type), hence the
  58. name. For example, the following C++ code creates a global static:
  59. \code
  60. static MyType staticType;
  61. \endcode
  62. Compared to Q_GLOBAL_STATIC, and assuming that \c MyType is a class or
  63. struct that has a constructor, a destructor, or is otherwise non-POD, the
  64. above has the following drawbacks:
  65. \list
  66. \li it requires load-time initialization of \c MyType (that is, the
  67. default constructor for \c MyType is called when the library or
  68. application is loaded);
  69. \li the type will be initialized even if it is never used;
  70. \li the order of initialization and destruction among different
  71. translation units is not determined, leading to possible uses before
  72. initialization or after destruction;
  73. \li if it is found inside a function (that is, not global), it will be
  74. initialized on first use, but many current compilers (as of 2013) do
  75. not guarantee that the initialization will be thread-safe;
  76. \endlist
  77. The Q_GLOBAL_STATIC macro solves all of the above problems by guaranteeing
  78. thread-safe initialization on first use and allowing the user to query for
  79. whether the type has already been destroyed, to avoid the
  80. use-after-destruction problem (see QGlobalStatic::isDestroyed()).
  81. \section1 Constructor and destructor
  82. For Q_GLOBAL_STATIC, the type \c Type must be publicly
  83. default-constructible and publicly destructible. For
  84. Q_GLOBAL_STATIC_WITH_ARGS(), there must be a public constructor that
  85. matches the arguments passed.
  86. It is not possible to use Q_GLOBAL_STATIC with types that have protected or
  87. private default constructors or destructors (for Q_GLOBAL_STATIC_WITH_ARGS(),
  88. a protected or private constructor matching the arguments). If the type in
  89. question has those members as protected, it is possible to overcome the
  90. issue by deriving from the type and creating public a constructor and
  91. destructor. If the type has them as private, a friend declaration is
  92. necessary before deriving.
  93. For example, the following is enough to create \c MyType based on a
  94. previously-defined \c MyOtherType which has a protected default constructor
  95. and/or a protected destructor (or has them as private, but that defines \c
  96. MyType as a friend).
  97. \code
  98. class MyType : public MyOtherType { };
  99. Q_GLOBAL_STATIC(MyType, staticType)
  100. \endcode
  101. No body for \c MyType is required since the destructor is an implicit
  102. member and so is the default constructor if no other constructors are
  103. defined. For use with Q_GLOBAL_STATIC_WITH_ARGS(), however, a suitable
  104. constructor body is necessary:
  105. \code
  106. class MyType : public MyOtherType
  107. {
  108. public:
  109. MyType(int i) : MyOtherType(i) {}
  110. };
  111. Q_GLOBAL_STATIC_WITH_ARGS(MyType, staticType, (42))
  112. \endcode
  113. Alternatively, if the compiler supports C++11 inheriting constructors, one could write:
  114. \code
  115. class MyType : public MyOtherType
  116. {
  117. public:
  118. using MyOtherType::MyOtherType;
  119. };
  120. Q_GLOBAL_STATIC_WITH_ARGS(MyType, staticType, (42))
  121. \endcode
  122. \section1 Placement
  123. The Q_GLOBAL_STATIC macro creates a type that is necessarily static, at the
  124. global scope. It is not possible to place the Q_GLOBAL_STATIC macro inside
  125. a function (doing so will result in compilation errors).
  126. More importantly, this macro should be placed in source files, never in
  127. headers. Since the resulting object is has static linkage, if the macro is
  128. placed in a header and included by multiple source files, the object will
  129. be defined multiple times and will not cause linking errors. Instead, each
  130. translation unit will refer to a different object, which could lead to
  131. subtle and hard-to-track errors.
  132. \section1 Non-recommended uses
  133. Note that the macro is not recommended for use with types that are POD or
  134. that have C++11 constexpr constructors (trivially constructible and
  135. destructible). For those types, it is still recommended to use regular
  136. static, whether global or function-local.
  137. This macro will work, but it will add unnecessary overhead.
  138. \section1 Reentrancy, thread-safety, deadlocks, and exception-safety on construction
  139. The Q_GLOBAL_STATIC macro creates an object that initializes itself on
  140. first use in a thread-safe manner: if multiple threads attempt to
  141. initialize the object at the same time, only one thread will proceed to
  142. initialize, while all other threads wait for completion.
  143. If the initialization process throws an exception, the initialization is
  144. deemed not complete and will be attempted again when control reaches any
  145. use of the object. If there are any threads waiting for initialization, one
  146. of them will be woken up to attempt to initialize.
  147. The macro makes no guarantee about reentrancy from the same thread. If the
  148. global static object is accessed directly or indirectly from inside the
  149. constructor, a deadlock will surely happen.
  150. In addition, if two Q_GLOBAL_STATIC objects are being initialized on two
  151. different threads and each one's initialization sequence accesses the
  152. other, a deadlock might happen. For that reason, it is recommended to keep
  153. global static constructors simple or, failing that, to ensure that there's
  154. no cross-dependency of uses of global static during construction.
  155. \section1 Destruction
  156. If the object is never used during the lifetime of the program, aside from
  157. the QGlobalStatic::exists() and QGlobalStatic::isDestroyed() functions, the
  158. contents of type \a Type will not be created and there will not be any
  159. exit-time operation.
  160. If the object is created, it will be destroyed at exit-time, similar to the
  161. C \c atexit function. On most systems, in fact, the destructor will also be
  162. called if the library or plugin is unloaded from memory before exit.
  163. Since the destruction is meant to happen at program exit, no thread-safety
  164. is provided. This includes the case of plugin or library unload. In
  165. addition, since destructors are not supposed to throw exceptions, no
  166. exception safety is provided either.
  167. However, reentrancy is permitted: during destruction, it is possible to
  168. access the global static object and the pointer returned will be the same
  169. as it was before destruction began. After the destruction has completed,
  170. accessing the global static object is not permitted, except as noted in the
  171. \l QGlobalStatic API.
  172. \omit
  173. \section1 Compatibility with Qt 4 and Qt 5.0
  174. This macro, in its current form and behavior, was introduced in Qt 5.1.
  175. Prior to that version, Qt had another macro with the same name that was
  176. private API. This section is not meant to document how to use
  177. Q_GLOBAL_STATIC in those versions, but instead to serve as a porting guide
  178. for Qt code that used those macros.
  179. The Qt 4 Q_GLOBAL_STATIC macro differed in behavior in the following ways:
  180. \list
  181. \li the object created was not of type \l QGlobalStatic, but instead
  182. it was a function that returned a pointer to \a Type; that means the
  183. \l QGlobalStatic API was not present;
  184. \li the initialization was thread-safe, but not guaranteed to be
  185. unique: instead, if N threads tried to initialize the object at the
  186. same time, N objects would be created on the heap and N-1 would be
  187. destroyed;
  188. \li the object was always created on the heap.
  189. \endlist
  190. \section1 Implementation details
  191. Q_GLOBAL_STATIC is implemented by creating a QBasicAtomicInt called the \c
  192. guard and a free, inline function called \c innerFunction. The guard
  193. variable is initialized to value 0 (chosen so that the guard can be placed
  194. in the .bss section of the binary file), which denotes that construction
  195. has not yet taken place (uninitialized). The inner function is implemented
  196. by the helper macro Q_GLOBAL_STATIC_INTERNAL.
  197. Both the guard variable and the inner function are passed as template
  198. parameters to QGlobalStatic, along with the type \a Type. Both should also
  199. have static linkage or be placed inside an anonymous namespace, so that the
  200. visibility of Q_GLOBAL_STATIC is that of a global static. To permit
  201. multiple Q_GLOBAL_STATIC per translation unit, the guard variable and the
  202. inner function must have unique names, which can be accomplished by
  203. concatenating with \a VariableName or by placing them in a namespace that
  204. has \a VariableName as part of the name. To simplify and improve
  205. readability on Q_GLOBAL_STATIC_INTERNAL, we chose the namespace solution.
  206. It's also required for C++98 builds, since static symbols cannot be used as
  207. template parameters.
  208. The guard variable can assume the following values:
  209. \list
  210. \li -2: object was once initialized but has been destroyed already;
  211. \li -1: object was initialized and is still valid;
  212. \li 0: object was not initialized yet;
  213. \li +1: object is being initialized and any threads encountering this
  214. value must wait for completion (not used in the current implementation).
  215. \endlist
  216. Collectively, all positive values indicate that the initialization is
  217. progressing and must be waited on, whereas all negative values indicate
  218. that the initialization has terminated and must not be attempted again.
  219. Positive values are not used in the current implementation, but were in
  220. earlier versions. They could be used again in the future.
  221. The QGlobalStatic::exists() and QGlobalStatic::isDestroyed() functions
  222. operate solely on the guard variable: the former returns \c true if the guard
  223. is negative, whereas the latter returns \c true only if it is -2.
  224. The Q_GLOBAL_STATIC_INTERNAL macro implements the actual construction and
  225. destruction. There are two implementations of it: one for compilers that
  226. support thread-safe initialization of function-local statics and one for
  227. compilers that don't. Thread-safe initialization is required by C++11 in
  228. [stmt.decl], but as of the time of this writing, only compilers based on
  229. the IA-64 C++ ABI implemented it properly. The implementation requiring
  230. thread-safe initialization is also used on the Qt bootstrapped tools, which
  231. define QT_NO_THREAD.
  232. The implementation requiring thread-safe initialization from the compiler
  233. is the simplest: it creates the \a Type object as a function-local static
  234. and returns its address. The actual object is actually inside a holder
  235. structure so holder's destructor can set the guard variable to the value -2
  236. (destroyed) when the type has finished destruction. Since we need to set
  237. the guard \b after the destruction has finished, this code needs to be in a
  238. base struct's destructor. And it only sets to -2 (destroyed) if it finds
  239. the guard at -1 (initialized): this is done to ensure that the guard isn't
  240. set to -2 in the event the type's constructor threw an exception. A holder
  241. structure is used to avoid creating two statics, which the ABI might
  242. require duplicating the thread-safe control structures for.
  243. The other implementation is similar to Qt 4's Q_GLOBAL_STATIC, but unlike
  244. that one, it uses a \l QBasicMutex to provide locking. It is also more
  245. efficient memory-wise. It use a simple double-checked locking of the mutex
  246. and then creates the contents on the heap. After that, it creates a
  247. function-local structure called "Cleanup", whose destructor will be run at
  248. program exit and will actually destroy the contents.
  249. \endomit
  250. \sa Q_GLOBAL_STATIC_WITH_ARGS(), QGlobalStatic
  251. */
  252. /*!
  253. \macro Q_GLOBAL_STATIC_WITH_ARGS(Type, VariableName, Arguments)
  254. \since 5.1
  255. \relates QGlobalStatic
  256. Creates a global and static object of type \l QGlobalStatic, of name \a
  257. VariableName, initialized by the arguments \a Arguments and that behaves as
  258. a pointer to \a Type. The object created by Q_GLOBAL_STATIC_WITH_ARGS
  259. initializes itself on the first use, which means that it will not increase
  260. the application or the library's load time. Additionally, the object is
  261. initialized in a thread-safe manner on all platforms.
  262. The typical use of this macro is as follows, in a global context (that is,
  263. outside of any function bodies):
  264. \code
  265. Q_GLOBAL_STATIC_WITH_ARGS(MyType, staticType, (42, "Hello", "World"))
  266. \endcode
  267. The \a Arguments macro parameter must always include the parentheses or, if
  268. C++11 uniform initialization is allowed, the braces.
  269. Aside from the actual initialization of the contents with the supplied
  270. arguments, this macro behaves identically to Q_GLOBAL_STATIC(). Please
  271. see that macro's documentation for more information.
  272. \sa Q_GLOBAL_STATIC(), QGlobalStatic
  273. */
  274. /*!
  275. \class QGlobalStatic
  276. \threadsafe
  277. \inmodule QtCore
  278. \since 5.1
  279. \brief The QGlobalStatic class is used to implement a global static object
  280. The QGlobalStatic class is the front-end API exported when
  281. Q_GLOBAL_STATIC() is used. See the documentation for the macro for a
  282. discussion on when to use it and its requirements.
  283. Normally, you will never use this class directly, but instead you will use
  284. the Q_GLOBAL_STATIC() or Q_GLOBAL_STATIC_WITH_ARGS() macros, as
  285. follows:
  286. \code
  287. Q_GLOBAL_STATIC(MyType, staticType)
  288. \endcode
  289. The above example creates an object of type QGlobalStatic called \c
  290. staticType. After the above declaration, the \c staticType object may be
  291. used as if it were a pointer, guaranteed to be initialized exactly once. In
  292. addition to the use as a pointer, the object offers two methods to
  293. determine the current status of the global: exists() and isDestroyed().
  294. \sa Q_GLOBAL_STATIC(), Q_GLOBAL_STATIC_WITH_ARGS()
  295. */
  296. /*!
  297. \typedef QGlobalStatic::Type
  298. This type is equivalent to the \c Type parameter passed to the
  299. Q_GLOBAL_STATIC() or Q_GLOBAL_STATIC_WITH_ARGS() macros. It is used in the
  300. return types of some functions.
  301. */
  302. /*!
  303. \fn bool QGlobalStatic::isDestroyed() const
  304. This function returns \c true if the global static object has already
  305. completed destruction (that is, if the destructor for the type has already
  306. returned). In specific, note that this function returns \c false if
  307. the destruction is still in progress.
  308. Once this function has returned true once, it will never return
  309. false again until either the program is restarted or the plugin or library
  310. containing the global static is unloaded and reloaded.
  311. This function is safe to call at any point in the program execution: it
  312. cannot fail and cannot cause a deadlock. Additionally, it will not cause
  313. the contents to be created if they have not yet been created.
  314. This function is useful in code that may be executed at program shutdown,
  315. to determine whether the contents may still be accessed or not.
  316. \omit
  317. Due to the non-atomic nature of destruction, it's possible that
  318. QGlobalStatic::isDestroyed might return false for a short time after the
  319. destructor has finished. However, since the destructor is only run in an
  320. environment where concurrent multithreaded access is impossible, no one can
  321. see that state. (omitted because it's useless information)
  322. \endomit
  323. \sa exists()
  324. */
  325. /*!
  326. \fn bool QGlobalStatic::exists() const
  327. This function returns \c true if the global static object has already
  328. completed initialization (that is, if the constructor for the type has
  329. already returned). In specific, note that this function returns \c false if
  330. the initialization is still in progress.
  331. Once this function has returned true once, it will never return false again
  332. until either the program is restarted or the plugin or library containing
  333. the global static is unloaded and reloaded.
  334. This function is safe to call at any point in the program execution: it
  335. cannot fail and cannot cause a deadlock. Additionally, it will not cause
  336. the contents to be created if they have not yet been created.
  337. This function is useful if one can determine the initial conditions of the
  338. global static object and would prefer to avoid a possibly expensive
  339. construction operation.
  340. For example, in the following code sample, this function is used to
  341. short-circuit the creation of the global static called \c globalState and
  342. returns a default value:
  343. \code
  344. Q_GLOBAL_STATIC(MyType, globalState)
  345. QString someState()
  346. {
  347. if (globalState.exists())
  348. return globalState->someState;
  349. return QString();
  350. }
  351. \endcode
  352. \b{Thread-safety notice:} this function is thread-safe in the sense that it
  353. may be called from any thread at any time and will always return a valid
  354. reply. But due to the non-atomic nature of construction, this function may
  355. return false for a short time after the construction has completed.
  356. \b{Memory ordering notice:} this function does not impose any memory
  357. ordering guarantees. That is instead provided by the accessor functions
  358. that return the pointer or reference to the contents. If you bypass the
  359. accessor functions and attempt to access some global state set by the
  360. constructor, be sure to use the correct memory ordering semantics provided
  361. by \l QAtomicInt or \l QAtomicPointer.
  362. \sa isDestroyed()
  363. */
  364. /*!
  365. \fn QGlobalStatic::operator Type*()
  366. This function returns the address of the contents of this global static. If
  367. the contents have not yet been created, they will be created thread-safely
  368. by this function. If the contents have already been destroyed, this
  369. function will return a null pointer.
  370. This function can be used, for example, to store the pointer to the
  371. contents of the global static in a local variable, thus avoiding multiple
  372. calls to the function. The implementation of Q_GLOBAL_STATIC() is quite
  373. efficient already, but in performance-critical sections it might be useful
  374. to help the compiler a little. For example:
  375. \code
  376. Q_GLOBAL_STATIC(MyType, globalState)
  377. QString someState()
  378. {
  379. MyType *state = globalState;
  380. if (!state) {
  381. // we're in a post-destruction state
  382. return QString();
  383. }
  384. if (state->condition)
  385. return state->value1;
  386. else
  387. return state->value2;
  388. }
  389. \endcode
  390. \sa operator->(), operator*()
  391. */
  392. /*!
  393. \fn Type *QGlobalStatic::operator()()
  394. \deprecated
  395. This function returns the address of the contents of this global static. If
  396. the contents have not yet been created, they will be created thread-safely
  397. by this function. If the contents have already been destroyed, this
  398. function will return a null pointer.
  399. This function is equivalent to \l {operator Type *()}. It is provided for
  400. compatibility with the private Q_GLOBAL_STATIC implementation that existed
  401. in Qt 4.x and 5.0. New code should avoid using it and should instead treat
  402. the object as a smart pointer.
  403. */
  404. /*!
  405. \fn Type *QGlobalStatic::operator->()
  406. This function returns the address of the contents of this global static. If
  407. the contents have not yet been created, they will be created thread-safely
  408. by this function.
  409. This function does not check if the contents have already been destroyed and
  410. will never return null. If this function is called after the object has
  411. been destroyed, it will return a dangling pointer that should not be
  412. dereferenced.
  413. */
  414. /*!
  415. \fn Type &QGlobalStatic::operator*()
  416. This function returns a reference to the contents of this global static. If
  417. the contents have not yet been created, they will be created thread-safely
  418. by this function.
  419. This function does not check if the contents have already been destroyed.
  420. If this function is called after the object has been destroyed, it will
  421. return an invalid reference that must not be used.
  422. */