2
0

ThreadSafetyAnalysis.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. ======================
  2. Thread Safety Analysis
  3. ======================
  4. Introduction
  5. ============
  6. NOTE: this document applies to the original Clang project, not the DirectX
  7. Compiler. It's made available for informational purposes only.
  8. Clang Thread Safety Analysis is a C++ language extension which warns about
  9. potential race conditions in code. The analysis is completely static (i.e.
  10. compile-time); there is no run-time overhead. The analysis is still
  11. under active development, but it is mature enough to be deployed in an
  12. industrial setting. It is being developed by Google, in collaboration with
  13. CERT/SEI, and is used extensively in Google's internal code base.
  14. Thread safety analysis works very much like a type system for multi-threaded
  15. programs. In addition to declaring the *type* of data (e.g. ``int``, ``float``,
  16. etc.), the programmer can (optionally) declare how access to that data is
  17. controlled in a multi-threaded environment. For example, if ``foo`` is
  18. *guarded by* the mutex ``mu``, then the analysis will issue a warning whenever
  19. a piece of code reads or writes to ``foo`` without first locking ``mu``.
  20. Similarly, if there are particular routines that should only be called by
  21. the GUI thread, then the analysis will warn if other threads call those
  22. routines.
  23. Getting Started
  24. ----------------
  25. .. code-block:: c++
  26. #include "mutex.h"
  27. class BankAccount {
  28. private:
  29. Mutex mu;
  30. int balance GUARDED_BY(mu);
  31. void depositImpl(int amount) {
  32. balance += amount; // WARNING! Cannot write balance without locking mu.
  33. }
  34. void withdrawImpl(int amount) REQUIRES(mu) {
  35. balance -= amount; // OK. Caller must have locked mu.
  36. }
  37. public:
  38. void withdraw(int amount) {
  39. mu.Lock();
  40. withdrawImpl(amount); // OK. We've locked mu.
  41. } // WARNING! Failed to unlock mu.
  42. void transferFrom(BankAccount& b, int amount) {
  43. mu.Lock();
  44. b.withdrawImpl(amount); // WARNING! Calling withdrawImpl() requires locking b.mu.
  45. depositImpl(amount); // OK. depositImpl() has no requirements.
  46. mu.Unlock();
  47. }
  48. };
  49. This example demonstrates the basic concepts behind the analysis. The
  50. ``GUARDED_BY`` attribute declares that a thread must lock ``mu`` before it can
  51. read or write to ``balance``, thus ensuring that the increment and decrement
  52. operations are atomic. Similarly, ``REQUIRES`` declares that
  53. the calling thread must lock ``mu`` before calling ``withdrawImpl``.
  54. Because the caller is assumed to have locked ``mu``, it is safe to modify
  55. ``balance`` within the body of the method.
  56. The ``depositImpl()`` method does not have ``REQUIRES``, so the
  57. analysis issues a warning. Thread safety analysis is not inter-procedural, so
  58. caller requirements must be explicitly declared.
  59. There is also a warning in ``transferFrom()``, because although the method
  60. locks ``this->mu``, it does not lock ``b.mu``. The analysis understands
  61. that these are two separate mutexes, in two different objects.
  62. Finally, there is a warning in the ``withdraw()`` method, because it fails to
  63. unlock ``mu``. Every lock must have a corresponding unlock, and the analysis
  64. will detect both double locks, and double unlocks. A function is allowed to
  65. acquire a lock without releasing it, (or vice versa), but it must be annotated
  66. as such (using ``ACQUIRE``/``RELEASE``).
  67. Running The Analysis
  68. --------------------
  69. To run the analysis, simply compile with the ``-Wthread-safety`` flag, e.g.
  70. .. code-block:: bash
  71. clang -c -Wthread-safety example.cpp
  72. Note that this example assumes the presence of a suitably annotated
  73. :ref:`mutexheader` that declares which methods perform locking,
  74. unlocking, and so on.
  75. Basic Concepts: Capabilities
  76. ============================
  77. Thread safety analysis provides a way of protecting *resources* with
  78. *capabilities*. A resource is either a data member, or a function/method
  79. that provides access to some underlying resource. The analysis ensures that
  80. the calling thread cannot access the *resource* (i.e. call the function, or
  81. read/write the data) unless it has the *capability* to do so.
  82. Capabilities are associated with named C++ objects which declare specific
  83. methods to acquire and release the capability. The name of the object serves
  84. to identify the capability. The most common example is a mutex. For example,
  85. if ``mu`` is a mutex, then calling ``mu.Lock()`` causes the calling thread
  86. to acquire the capability to access data that is protected by ``mu``. Similarly,
  87. calling ``mu.Unlock()`` releases that capability.
  88. A thread may hold a capability either *exclusively* or *shared*. An exclusive
  89. capability can be held by only one thread at a time, while a shared capability
  90. can be held by many threads at the same time. This mechanism enforces a
  91. multiple-reader, single-writer pattern. Write operations to protected data
  92. require exclusive access, while read operations require only shared access.
  93. At any given moment during program execution, a thread holds a specific set of
  94. capabilities (e.g. the set of mutexes that it has locked.) These act like keys
  95. or tokens that allow the thread to access a given resource. Just like physical
  96. security keys, a thread cannot make copy of a capability, nor can it destroy
  97. one. A thread can only release a capability to another thread, or acquire one
  98. from another thread. The annotations are deliberately agnostic about the
  99. exact mechanism used to acquire and release capabilities; it assumes that the
  100. underlying implementation (e.g. the Mutex implementation) does the handoff in
  101. an appropriate manner.
  102. The set of capabilities that are actually held by a given thread at a given
  103. point in program execution is a run-time concept. The static analysis works
  104. by calculating an approximation of that set, called the *capability
  105. environment*. The capability environment is calculated for every program point,
  106. and describes the set of capabilities that are statically known to be held, or
  107. not held, at that particular point. This environment is a conservative
  108. approximation of the full set of capabilities that will actually held by a
  109. thread at run-time.
  110. Reference Guide
  111. ===============
  112. The thread safety analysis uses attributes to declare threading constraints.
  113. Attributes must be attached to named declarations, such as classes, methods,
  114. and data members. Users are *strongly advised* to define macros for the various
  115. attributes; example definitions can be found in :ref:`mutexheader`, below.
  116. The following documentation assumes the use of macros.
  117. For historical reasons, prior versions of thread safety used macro names that
  118. were very lock-centric. These macros have since been renamed to fit a more
  119. general capability model. The prior names are still in use, and will be
  120. mentioned under the tag *previously* where appropriate.
  121. GUARDED_BY(c) and PT_GUARDED_BY(c)
  122. ----------------------------------
  123. ``GUARDED_BY`` is an attribute on data members, which declares that the data
  124. member is protected by the given capability. Read operations on the data
  125. require shared access, while write operations require exclusive access.
  126. ``PT_GUARDED_BY`` is similar, but is intended for use on pointers and smart
  127. pointers. There is no constraint on the data member itself, but the *data that
  128. it points to* is protected by the given capability.
  129. .. code-block:: c++
  130. Mutex mu;
  131. int *p1 GUARDED_BY(mu);
  132. int *p2 PT_GUARDED_BY(mu);
  133. unique_ptr<int> p3 PT_GUARDED_BY(mu);
  134. void test() {
  135. p1 = 0; // Warning!
  136. *p2 = 42; // Warning!
  137. p2 = new int; // OK.
  138. *p3 = 42; // Warning!
  139. p3.reset(new int); // OK.
  140. }
  141. REQUIRES(...), REQUIRES_SHARED(...)
  142. -----------------------------------
  143. *Previously*: ``EXCLUSIVE_LOCKS_REQUIRED``, ``SHARED_LOCKS_REQUIRED``
  144. ``REQUIRES`` is an attribute on functions or methods, which
  145. declares that the calling thread must have exclusive access to the given
  146. capabilities. More than one capability may be specified. The capabilities
  147. must be held on entry to the function, *and must still be held on exit*.
  148. ``REQUIRES_SHARED`` is similar, but requires only shared access.
  149. .. code-block:: c++
  150. Mutex mu1, mu2;
  151. int a GUARDED_BY(mu1);
  152. int b GUARDED_BY(mu2);
  153. void foo() REQUIRES(mu1, mu2) {
  154. a = 0;
  155. b = 0;
  156. }
  157. void test() {
  158. mu1.Lock();
  159. foo(); // Warning! Requires mu2.
  160. mu1.Unlock();
  161. }
  162. ACQUIRE(...), ACQUIRE_SHARED(...), RELEASE(...), RELEASE_SHARED(...)
  163. --------------------------------------------------------------------
  164. *Previously*: ``EXCLUSIVE_LOCK_FUNCTION``, ``SHARED_LOCK_FUNCTION``,
  165. ``UNLOCK_FUNCTION``
  166. ``ACQUIRE`` is an attribute on functions or methods, which
  167. declares that the function acquires a capability, but does not release it. The
  168. caller must not hold the given capability on entry, and it will hold the
  169. capability on exit. ``ACQUIRE_SHARED`` is similar.
  170. ``RELEASE`` and ``RELEASE_SHARED`` declare that the function releases the given
  171. capability. The caller must hold the capability on entry, and will no longer
  172. hold it on exit. It does not matter whether the given capability is shared or
  173. exclusive.
  174. .. code-block:: c++
  175. Mutex mu;
  176. MyClass myObject GUARDED_BY(mu);
  177. void lockAndInit() ACQUIRE(mu) {
  178. mu.Lock();
  179. myObject.init();
  180. }
  181. void cleanupAndUnlock() RELEASE(mu) {
  182. myObject.cleanup();
  183. } // Warning! Need to unlock mu.
  184. void test() {
  185. lockAndInit();
  186. myObject.doSomething();
  187. cleanupAndUnlock();
  188. myObject.doSomething(); // Warning, mu is not locked.
  189. }
  190. If no argument is passed to ``ACQUIRE`` or ``RELEASE``, then the argument is
  191. assumed to be ``this``, and the analysis will not check the body of the
  192. function. This pattern is intended for use by classes which hide locking
  193. details behind an abstract interface. For example:
  194. .. code-block:: c++
  195. template <class T>
  196. class CAPABILITY("mutex") Container {
  197. private:
  198. Mutex mu;
  199. T* data;
  200. public:
  201. // Hide mu from public interface.
  202. void Lock() ACQUIRE() { mu.Lock(); }
  203. void Unlock() RELEASE() { mu.Unlock(); }
  204. T& getElem(int i) { return data[i]; }
  205. };
  206. void test() {
  207. Container<int> c;
  208. c.Lock();
  209. int i = c.getElem(0);
  210. c.Unlock();
  211. }
  212. EXCLUDES(...)
  213. -------------
  214. *Previously*: ``LOCKS_EXCLUDED``
  215. ``EXCLUDES`` is an attribute on functions or methods, which declares that
  216. the caller must *not* hold the given capabilities. This annotation is
  217. used to prevent deadlock. Many mutex implementations are not re-entrant, so
  218. deadlock can occur if the function acquires the mutex a second time.
  219. .. code-block:: c++
  220. Mutex mu;
  221. int a GUARDED_BY(mu);
  222. void clear() EXCLUDES(mu) {
  223. mu.Lock();
  224. a = 0;
  225. mu.Unlock();
  226. }
  227. void reset() {
  228. mu.Lock();
  229. clear(); // Warning! Caller cannot hold 'mu'.
  230. mu.Unlock();
  231. }
  232. Unlike ``REQUIRES``, ``EXCLUDES`` is optional. The analysis will not issue a
  233. warning if the attribute is missing, which can lead to false negatives in some
  234. cases. This issue is discussed further in :ref:`negative`.
  235. NO_THREAD_SAFETY_ANALYSIS
  236. -------------------------
  237. ``NO_THREAD_SAFETY_ANALYSIS`` is an attribute on functions or methods, which
  238. turns off thread safety checking for that method. It provides an escape hatch
  239. for functions which are either (1) deliberately thread-unsafe, or (2) are
  240. thread-safe, but too complicated for the analysis to understand. Reasons for
  241. (2) will be described in the :ref:`limitations`, below.
  242. .. code-block:: c++
  243. class Counter {
  244. Mutex mu;
  245. int a GUARDED_BY(mu);
  246. void unsafeIncrement() NO_THREAD_SAFETY_ANALYSIS { a++; }
  247. };
  248. Unlike the other attributes, NO_THREAD_SAFETY_ANALYSIS is not part of the
  249. interface of a function, and should thus be placed on the function definition
  250. (in the ``.cc`` or ``.cpp`` file) rather than on the function declaration
  251. (in the header).
  252. RETURN_CAPABILITY(c)
  253. --------------------
  254. *Previously*: ``LOCK_RETURNED``
  255. ``RETURN_CAPABILITY`` is an attribute on functions or methods, which declares
  256. that the function returns a reference to the given capability. It is used to
  257. annotate getter methods that return mutexes.
  258. .. code-block:: c++
  259. class MyClass {
  260. private:
  261. Mutex mu;
  262. int a GUARDED_BY(mu);
  263. public:
  264. Mutex* getMu() RETURN_CAPABILITY(mu) { return &mu; }
  265. // analysis knows that getMu() == mu
  266. void clear() REQUIRES(getMu()) { a = 0; }
  267. };
  268. ACQUIRED_BEFORE(...), ACQUIRED_AFTER(...)
  269. -----------------------------------------
  270. ``ACQUIRED_BEFORE`` and ``ACQUIRED_AFTER`` are attributes on member
  271. declarations, specifically declarations of mutexes or other capabilities.
  272. These declarations enforce a particular order in which the mutexes must be
  273. acquired, in order to prevent deadlock.
  274. .. code-block:: c++
  275. Mutex m1;
  276. Mutex m2 ACQUIRED_AFTER(m1);
  277. // Alternative declaration
  278. // Mutex m2;
  279. // Mutex m1 ACQUIRED_BEFORE(m2);
  280. void foo() {
  281. m2.Lock();
  282. m1.Lock(); // Warning! m2 must be acquired after m1.
  283. m1.Unlock();
  284. m2.Unlock();
  285. }
  286. CAPABILITY(<string>)
  287. --------------------
  288. *Previously*: ``LOCKABLE``
  289. ``CAPABILITY`` is an attribute on classes, which specifies that objects of the
  290. class can be used as a capability. The string argument specifies the kind of
  291. capability in error messages, e.g. ``"mutex"``. See the ``Container`` example
  292. given above, or the ``Mutex`` class in :ref:`mutexheader`.
  293. SCOPED_CAPABILITY
  294. -----------------
  295. *Previously*: ``SCOPED_LOCKABLE``
  296. ``SCOPED_CAPABILITY`` is an attribute on classes that implement RAII-style
  297. locking, in which a capability is acquired in the constructor, and released in
  298. the destructor. Such classes require special handling because the constructor
  299. and destructor refer to the capability via different names; see the
  300. ``MutexLocker`` class in :ref:`mutexheader`, below.
  301. TRY_ACQUIRE(<bool>, ...), TRY_ACQUIRE_SHARED(<bool>, ...)
  302. ---------------------------------------------------------
  303. *Previously:* ``EXCLUSIVE_TRYLOCK_FUNCTION``, ``SHARED_TRYLOCK_FUNCTION``
  304. These are attributes on a function or method that tries to acquire the given
  305. capability, and returns a boolean value indicating success or failure.
  306. The first argument must be ``true`` or ``false``, to specify which return value
  307. indicates success, and the remaining arguments are interpreted in the same way
  308. as ``ACQUIRE``. See :ref:`mutexheader`, below, for example uses.
  309. ASSERT_CAPABILITY(...) and ASSERT_SHARED_CAPABILITY(...)
  310. --------------------------------------------------------
  311. *Previously:* ``ASSERT_EXCLUSIVE_LOCK``, ``ASSERT_SHARED_LOCK``
  312. These are attributes on a function or method that does a run-time test to see
  313. whether the calling thread holds the given capability. The function is assumed
  314. to fail (no return) if the capability is not held. See :ref:`mutexheader`,
  315. below, for example uses.
  316. GUARDED_VAR and PT_GUARDED_VAR
  317. ------------------------------
  318. Use of these attributes has been deprecated.
  319. Warning flags
  320. -------------
  321. * ``-Wthread-safety``: Umbrella flag which turns on the following three:
  322. + ``-Wthread-safety-attributes``: Sanity checks on attribute syntax.
  323. + ``-Wthread-safety-analysis``: The core analysis.
  324. + ``-Wthread-safety-precise``: Requires that mutex expressions match precisely.
  325. This warning can be disabled for code which has a lot of aliases.
  326. + ``-Wthread-safety-reference``: Checks when guarded members are passed by reference.
  327. :ref:`negative` are an experimental feature, which are enabled with:
  328. * ``-Wthread-safety-negative``: Negative capabilities. Off by default.
  329. When new features and checks are added to the analysis, they can often introduce
  330. additional warnings. Those warnings are initially released as *beta* warnings
  331. for a period of time, after which they are migrated into the standard analysis.
  332. * ``-Wthread-safety-beta``: New features. Off by default.
  333. .. _negative:
  334. Negative Capabilities
  335. =====================
  336. Thread Safety Analysis is designed to prevent both race conditions and
  337. deadlock. The GUARDED_BY and REQUIRES attributes prevent race conditions, by
  338. ensuring that a capability is held before reading or writing to guarded data,
  339. and the EXCLUDES attribute prevents deadlock, by making sure that a mutex is
  340. *not* held.
  341. However, EXCLUDES is an optional attribute, and does not provide the same
  342. safety guarantee as REQUIRES. In particular:
  343. * A function which acquires a capability does not have to exclude it.
  344. * A function which calls a function that excludes a capability does not
  345. have transitively exclude that capability.
  346. As a result, EXCLUDES can easily produce false negatives:
  347. .. code-block:: c++
  348. class Foo {
  349. Mutex mu;
  350. void foo() {
  351. mu.Lock();
  352. bar(); // No warning.
  353. baz(); // No warning.
  354. mu.Unlock();
  355. }
  356. void bar() { // No warning. (Should have EXCLUDES(mu)).
  357. mu.Lock();
  358. // ...
  359. mu.Unlock();
  360. }
  361. void baz() {
  362. bif(); // No warning. (Should have EXCLUDES(mu)).
  363. }
  364. void bif() EXCLUDES(mu);
  365. };
  366. Negative requirements are an alternative EXCLUDES that provide
  367. a stronger safety guarantee. A negative requirement uses the REQUIRES
  368. attribute, in conjunction with the ``!`` operator, to indicate that a capability
  369. should *not* be held.
  370. For example, using ``REQUIRES(!mu)`` instead of ``EXCLUDES(mu)`` will produce
  371. the appropriate warnings:
  372. .. code-block:: c++
  373. class FooNeg {
  374. Mutex mu;
  375. void foo() REQUIRES(!mu) { // foo() now requires !mu.
  376. mu.Lock();
  377. bar();
  378. baz();
  379. mu.Unlock();
  380. }
  381. void bar() {
  382. mu.Lock(); // WARNING! Missing REQUIRES(!mu).
  383. // ...
  384. mu.Unlock();
  385. }
  386. void baz() {
  387. bif(); // WARNING! Missing REQUIRES(!mu).
  388. }
  389. void bif() REQUIRES(!mu);
  390. };
  391. Negative requirements are an experimental feature which is off by default,
  392. because it will produce many warnings in existing code. It can be enabled
  393. by passing ``-Wthread-safety-negative``.
  394. .. _faq:
  395. Frequently Asked Questions
  396. ==========================
  397. (Q) Should I put attributes in the header file, or in the .cc/.cpp/.cxx file?
  398. (A) Attributes are part of the formal interface of a function, and should
  399. always go in the header, where they are visible to anything that includes
  400. the header. Attributes in the .cpp file are not visible outside of the
  401. immediate translation unit, which leads to false negatives and false positives.
  402. (Q) "*Mutex is not locked on every path through here?*" What does that mean?
  403. (A) See :ref:`conditional_locks`, below.
  404. .. _limitations:
  405. Known Limitations
  406. =================
  407. Lexical scope
  408. -------------
  409. Thread safety attributes contain ordinary C++ expressions, and thus follow
  410. ordinary C++ scoping rules. In particular, this means that mutexes and other
  411. capabilities must be declared before they can be used in an attribute.
  412. Use-before-declaration is okay within a single class, because attributes are
  413. parsed at the same time as method bodies. (C++ delays parsing of method bodies
  414. until the end of the class.) However, use-before-declaration is not allowed
  415. between classes, as illustrated below.
  416. .. code-block:: c++
  417. class Foo;
  418. class Bar {
  419. void bar(Foo* f) REQUIRES(f->mu); // Error: mu undeclared.
  420. };
  421. class Foo {
  422. Mutex mu;
  423. };
  424. Private Mutexes
  425. ---------------
  426. Good software engineering practice dictates that mutexes should be private
  427. members, because the locking mechanism used by a thread-safe class is part of
  428. its internal implementation. However, private mutexes can sometimes leak into
  429. the public interface of a class.
  430. Thread safety attributes follow normal C++ access restrictions, so if ``mu``
  431. is a private member of ``c``, then it is an error to write ``c.mu`` in an
  432. attribute.
  433. One workaround is to (ab)use the ``RETURN_CAPABILITY`` attribute to provide a
  434. public *name* for a private mutex, without actually exposing the underlying
  435. mutex. For example:
  436. .. code-block:: c++
  437. class MyClass {
  438. private:
  439. Mutex mu;
  440. public:
  441. // For thread safety analysis only. Does not actually return mu.
  442. Mutex* getMu() RETURN_CAPABILITY(mu) { return 0; }
  443. void doSomething() REQUIRES(mu);
  444. };
  445. void doSomethingTwice(MyClass& c) REQUIRES(c.getMu()) {
  446. // The analysis thinks that c.getMu() == c.mu
  447. c.doSomething();
  448. c.doSomething();
  449. }
  450. In the above example, ``doSomethingTwice()`` is an external routine that
  451. requires ``c.mu`` to be locked, which cannot be declared directly because ``mu``
  452. is private. This pattern is discouraged because it
  453. violates encapsulation, but it is sometimes necessary, especially when adding
  454. annotations to an existing code base. The workaround is to define ``getMu()``
  455. as a fake getter method, which is provided only for the benefit of thread
  456. safety analysis.
  457. .. _conditional_locks:
  458. No conditionally held locks.
  459. ----------------------------
  460. The analysis must be able to determine whether a lock is held, or not held, at
  461. every program point. Thus, sections of code where a lock *might be held* will
  462. generate spurious warnings (false positives). For example:
  463. .. code-block:: c++
  464. void foo() {
  465. bool b = needsToLock();
  466. if (b) mu.Lock();
  467. ... // Warning! Mutex 'mu' is not held on every path through here.
  468. if (b) mu.Unlock();
  469. }
  470. No checking inside constructors and destructors.
  471. ------------------------------------------------
  472. The analysis currently does not do any checking inside constructors or
  473. destructors. In other words, every constructor and destructor is treated as
  474. if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``.
  475. The reason for this is that during initialization, only one thread typically
  476. has access to the object which is being initialized, and it is thus safe (and
  477. common practice) to initialize guarded members without acquiring any locks.
  478. The same is true of destructors.
  479. Ideally, the analysis would allow initialization of guarded members inside the
  480. object being initialized or destroyed, while still enforcing the usual access
  481. restrictions on everything else. However, this is difficult to enforce in
  482. practice, because in complex pointer-based data structures, it is hard to
  483. determine what data is owned by the enclosing object.
  484. No inlining.
  485. ------------
  486. Thread safety analysis is strictly intra-procedural, just like ordinary type
  487. checking. It relies only on the declared attributes of a function, and will
  488. not attempt to inline any method calls. As a result, code such as the
  489. following will not work:
  490. .. code-block:: c++
  491. template<class T>
  492. class AutoCleanup {
  493. T* object;
  494. void (T::*mp)();
  495. public:
  496. AutoCleanup(T* obj, void (T::*imp)()) : object(obj), mp(imp) { }
  497. ~AutoCleanup() { (object->*mp)(); }
  498. };
  499. Mutex mu;
  500. void foo() {
  501. mu.Lock();
  502. AutoCleanup<Mutex>(&mu, &Mutex::Unlock);
  503. // ...
  504. } // Warning, mu is not unlocked.
  505. In this case, the destructor of ``Autocleanup`` calls ``mu.Unlock()``, so
  506. the warning is bogus. However,
  507. thread safety analysis cannot see the unlock, because it does not attempt to
  508. inline the destructor. Moreover, there is no way to annotate the destructor,
  509. because the destructor is calling a function that is not statically known.
  510. This pattern is simply not supported.
  511. No alias analysis.
  512. ------------------
  513. The analysis currently does not track pointer aliases. Thus, there can be
  514. false positives if two pointers both point to the same mutex.
  515. .. code-block:: c++
  516. class MutexUnlocker {
  517. Mutex* mu;
  518. public:
  519. MutexUnlocker(Mutex* m) RELEASE(m) : mu(m) { mu->Unlock(); }
  520. ~MutexUnlocker() ACQUIRE(mu) { mu->Lock(); }
  521. };
  522. Mutex mutex;
  523. void test() REQUIRES(mutex) {
  524. {
  525. MutexUnlocker munl(&mutex); // unlocks mutex
  526. doSomeIO();
  527. } // Warning: locks munl.mu
  528. }
  529. The MutexUnlocker class is intended to be the dual of the MutexLocker class,
  530. defined in :ref:`mutexheader`. However, it doesn't work because the analysis
  531. doesn't know that munl.mu == mutex. The SCOPED_CAPABILITY attribute handles
  532. aliasing for MutexLocker, but does so only for that particular pattern.
  533. ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) are currently unimplemented.
  534. -------------------------------------------------------------------------
  535. To be fixed in a future update.
  536. .. _mutexheader:
  537. mutex.h
  538. =======
  539. Thread safety analysis can be used with any threading library, but it does
  540. require that the threading API be wrapped in classes and methods which have the
  541. appropriate annotations. The following code provides ``mutex.h`` as an example;
  542. these methods should be filled in to call the appropriate underlying
  543. implementation.
  544. .. code-block:: c++
  545. #ifndef THREAD_SAFETY_ANALYSIS_MUTEX_H
  546. #define THREAD_SAFETY_ANALYSIS_MUTEX_H
  547. // Enable thread safety attributes only with clang.
  548. // The attributes can be safely erased when compiling with other compilers.
  549. #if defined(__clang__) && (!defined(SWIG))
  550. #define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
  551. #else
  552. #define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op
  553. #endif
  554. #define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
  555. #define CAPABILITY(x) \
  556. THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
  557. #define SCOPED_CAPABILITY \
  558. THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
  559. #define GUARDED_BY(x) \
  560. THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
  561. #define PT_GUARDED_BY(x) \
  562. THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
  563. #define ACQUIRED_BEFORE(...) \
  564. THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
  565. #define ACQUIRED_AFTER(...) \
  566. THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
  567. #define REQUIRES(...) \
  568. THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
  569. #define REQUIRES_SHARED(...) \
  570. THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
  571. #define ACQUIRE(...) \
  572. THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
  573. #define ACQUIRE_SHARED(...) \
  574. THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
  575. #define RELEASE(...) \
  576. THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
  577. #define RELEASE_SHARED(...) \
  578. THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
  579. #define TRY_ACQUIRE(...) \
  580. THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
  581. #define TRY_ACQUIRE_SHARED(...) \
  582. THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
  583. #define EXCLUDES(...) \
  584. THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
  585. #define ASSERT_CAPABILITY(x) \
  586. THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
  587. #define ASSERT_SHARED_CAPABILITY(x) \
  588. THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
  589. #define RETURN_CAPABILITY(x) \
  590. THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
  591. #define NO_THREAD_SAFETY_ANALYSIS \
  592. THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
  593. // Defines an annotated interface for mutexes.
  594. // These methods can be implemented to use any internal mutex implementation.
  595. class CAPABILITY("mutex") Mutex {
  596. public:
  597. // Acquire/lock this mutex exclusively. Only one thread can have exclusive
  598. // access at any one time. Write operations to guarded data require an
  599. // exclusive lock.
  600. void Lock() ACQUIRE();
  601. // Acquire/lock this mutex for read operations, which require only a shared
  602. // lock. This assumes a multiple-reader, single writer semantics. Multiple
  603. // threads may acquire the mutex simultaneously as readers, but a writer
  604. // must wait for all of them to release the mutex before it can acquire it
  605. // exclusively.
  606. void ReaderLock() ACQUIRE_SHARED();
  607. // Release/unlock an exclusive mutex.
  608. void Unlock() RELEASE();
  609. // Release/unlock a shared mutex.
  610. void ReaderUnlock() RELEASE_SHARED();
  611. // Try to acquire the mutex. Returns true on success, and false on failure.
  612. bool TryLock() TRY_ACQUIRE(true);
  613. // Try to acquire the mutex for read operations.
  614. bool ReaderTryLock() TRY_ACQUIRE_SHARED(true);
  615. // Assert that this mutex is currently held by the calling thread.
  616. void AssertHeld() ASSERT_CAPABILITY(this);
  617. // Assert that is mutex is currently held for read operations.
  618. void AssertReaderHeld() ASSERT_SHARED_CAPABILITY(this);
  619. // For negative capabilities.
  620. const Mutex& operator!() const { return *this; }
  621. };
  622. // MutexLocker is an RAII class that acquires a mutex in its constructor, and
  623. // releases it in its destructor.
  624. class SCOPED_CAPABILITY MutexLocker {
  625. private:
  626. Mutex* mut;
  627. public:
  628. MutexLocker(Mutex *mu) ACQUIRE(mu) : mut(mu) {
  629. mu->Lock();
  630. }
  631. ~MutexLocker() RELEASE() {
  632. mut->Unlock();
  633. }
  634. };
  635. #ifdef USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
  636. // The original version of thread safety analysis the following attribute
  637. // definitions. These use a lock-based terminology. They are still in use
  638. // by existing thread safety code, and will continue to be supported.
  639. // Deprecated.
  640. #define PT_GUARDED_VAR \
  641. THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded)
  642. // Deprecated.
  643. #define GUARDED_VAR \
  644. THREAD_ANNOTATION_ATTRIBUTE__(guarded)
  645. // Replaced by REQUIRES
  646. #define EXCLUSIVE_LOCKS_REQUIRED(...) \
  647. THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
  648. // Replaced by REQUIRES_SHARED
  649. #define SHARED_LOCKS_REQUIRED(...) \
  650. THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
  651. // Replaced by CAPABILITY
  652. #define LOCKABLE \
  653. THREAD_ANNOTATION_ATTRIBUTE__(lockable)
  654. // Replaced by SCOPED_CAPABILITY
  655. #define SCOPED_LOCKABLE \
  656. THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
  657. // Replaced by ACQUIRE
  658. #define EXCLUSIVE_LOCK_FUNCTION(...) \
  659. THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
  660. // Replaced by ACQUIRE_SHARED
  661. #define SHARED_LOCK_FUNCTION(...) \
  662. THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
  663. // Replaced by RELEASE and RELEASE_SHARED
  664. #define UNLOCK_FUNCTION(...) \
  665. THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
  666. // Replaced by TRY_ACQUIRE
  667. #define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
  668. THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
  669. // Replaced by TRY_ACQUIRE_SHARED
  670. #define SHARED_TRYLOCK_FUNCTION(...) \
  671. THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
  672. // Replaced by ASSERT_CAPABILITY
  673. #define ASSERT_EXCLUSIVE_LOCK(...) \
  674. THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__))
  675. // Replaced by ASSERT_SHARED_CAPABILITY
  676. #define ASSERT_SHARED_LOCK(...) \
  677. THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__))
  678. // Replaced by EXCLUDE_CAPABILITY.
  679. #define LOCKS_EXCLUDED(...) \
  680. THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
  681. // Replaced by RETURN_CAPABILITY
  682. #define LOCK_RETURNED(x) \
  683. THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
  684. #endif // USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
  685. #endif // THREAD_SAFETY_ANALYSIS_MUTEX_H