ThreadSafetyAnalysis.rst 30 KB

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