1 2====================== 3Thread Safety Analysis 4====================== 5 6Introduction 7============ 8 9Clang Thread Safety Analysis is a C++ language extension which warns about 10potential race conditions in code. The analysis is completely static (i.e. 11compile-time); there is no run-time overhead. The analysis is still 12under active development, but it is mature enough to be deployed in an 13industrial setting. It is being developed by Google, in collaboration with 14CERT/SEI, and is used extensively in Google's internal code base. 15 16Thread safety analysis works very much like a type system for multi-threaded 17programs. In addition to declaring the *type* of data (e.g. ``int``, ``float``, 18etc.), the programmer can (optionally) declare how access to that data is 19controlled in a multi-threaded environment. For example, if ``foo`` is 20*guarded by* the mutex ``mu``, then the analysis will issue a warning whenever 21a piece of code reads or writes to ``foo`` without first locking ``mu``. 22Similarly, if there are particular routines that should only be called by 23the GUI thread, then the analysis will warn if other threads call those 24routines. 25 26Getting Started 27---------------- 28 29.. code-block:: c++ 30 31 #include "mutex.h" 32 33 class BankAccount { 34 private: 35 Mutex mu; 36 int balance GUARDED_BY(mu); 37 38 void depositImpl(int amount) { 39 balance += amount; // WARNING! Cannot write balance without locking mu. 40 } 41 42 void withdrawImpl(int amount) REQUIRES(mu) { 43 balance -= amount; // OK. Caller must have locked mu. 44 } 45 46 public: 47 void withdraw(int amount) { 48 mu.Lock(); 49 withdrawImpl(amount); // OK. We've locked mu. 50 } // WARNING! Failed to unlock mu. 51 52 void transferFrom(BankAccount& b, int amount) { 53 mu.Lock(); 54 b.withdrawImpl(amount); // WARNING! Calling withdrawImpl() requires locking b.mu. 55 depositImpl(amount); // OK. depositImpl() has no requirements. 56 mu.Unlock(); 57 } 58 }; 59 60This example demonstrates the basic concepts behind the analysis. The 61``GUARDED_BY`` attribute declares that a thread must lock ``mu`` before it can 62read or write to ``balance``, thus ensuring that the increment and decrement 63operations are atomic. Similarly, ``REQUIRES`` declares that 64the calling thread must lock ``mu`` before calling ``withdrawImpl``. 65Because the caller is assumed to have locked ``mu``, it is safe to modify 66``balance`` within the body of the method. 67 68The ``depositImpl()`` method does not have ``REQUIRES``, so the 69analysis issues a warning. Thread safety analysis is not inter-procedural, so 70caller requirements must be explicitly declared. 71There is also a warning in ``transferFrom()``, because although the method 72locks ``this->mu``, it does not lock ``b.mu``. The analysis understands 73that these are two separate mutexes, in two different objects. 74 75Finally, there is a warning in the ``withdraw()`` method, because it fails to 76unlock ``mu``. Every lock must have a corresponding unlock, and the analysis 77will detect both double locks, and double unlocks. A function is allowed to 78acquire a lock without releasing it, (or vice versa), but it must be annotated 79as such (using ``ACQUIRE``/``RELEASE``). 80 81 82Running The Analysis 83-------------------- 84 85To run the analysis, simply compile with the ``-Wthread-safety`` flag, e.g. 86 87.. code-block:: bash 88 89 clang -c -Wthread-safety example.cpp 90 91Note that this example assumes the presence of a suitably annotated 92:ref:`mutexheader` that declares which methods perform locking, 93unlocking, and so on. 94 95 96Basic Concepts: Capabilities 97============================ 98 99Thread safety analysis provides a way of protecting *resources* with 100*capabilities*. A resource is either a data member, or a function/method 101that provides access to some underlying resource. The analysis ensures that 102the calling thread cannot access the *resource* (i.e. call the function, or 103read/write the data) unless it has the *capability* to do so. 104 105Capabilities are associated with named C++ objects which declare specific 106methods to acquire and release the capability. The name of the object serves 107to identify the capability. The most common example is a mutex. For example, 108if ``mu`` is a mutex, then calling ``mu.Lock()`` causes the calling thread 109to acquire the capability to access data that is protected by ``mu``. Similarly, 110calling ``mu.Unlock()`` releases that capability. 111 112A thread may hold a capability either *exclusively* or *shared*. An exclusive 113capability can be held by only one thread at a time, while a shared capability 114can be held by many threads at the same time. This mechanism enforces a 115multiple-reader, single-writer pattern. Write operations to protected data 116require exclusive access, while read operations require only shared access. 117 118At any given moment during program execution, a thread holds a specific set of 119capabilities (e.g. the set of mutexes that it has locked.) These act like keys 120or tokens that allow the thread to access a given resource. Just like physical 121security keys, a thread cannot make copy of a capability, nor can it destroy 122one. A thread can only release a capability to another thread, or acquire one 123from another thread. The annotations are deliberately agnostic about the 124exact mechanism used to acquire and release capabilities; it assumes that the 125underlying implementation (e.g. the Mutex implementation) does the handoff in 126an appropriate manner. 127 128The set of capabilities that are actually held by a given thread at a given 129point in program execution is a run-time concept. The static analysis works 130by calculating an approximation of that set, called the *capability 131environment*. The capability environment is calculated for every program point, 132and describes the set of capabilities that are statically known to be held, or 133not held, at that particular point. This environment is a conservative 134approximation of the full set of capabilities that will actually held by a 135thread at run-time. 136 137 138Reference Guide 139=============== 140 141The thread safety analysis uses attributes to declare threading constraints. 142Attributes must be attached to named declarations, such as classes, methods, 143and data members. Users are *strongly advised* to define macros for the various 144attributes; example definitions can be found in :ref:`mutexheader`, below. 145The following documentation assumes the use of macros. 146 147The attributes only control assumptions made by thread safety analysis and the 148warnings it issues. They don't affect generated code or behavior at run-time. 149 150For historical reasons, prior versions of thread safety used macro names that 151were very lock-centric. These macros have since been renamed to fit a more 152general capability model. The prior names are still in use, and will be 153mentioned under the tag *previously* where appropriate. 154 155 156GUARDED_BY(c) and PT_GUARDED_BY(c) 157---------------------------------- 158 159``GUARDED_BY`` is an attribute on data members, which declares that the data 160member is protected by the given capability. Read operations on the data 161require shared access, while write operations require exclusive access. 162 163``PT_GUARDED_BY`` is similar, but is intended for use on pointers and smart 164pointers. There is no constraint on the data member itself, but the *data that 165it points to* is protected by the given capability. 166 167.. code-block:: c++ 168 169 Mutex mu; 170 int *p1 GUARDED_BY(mu); 171 int *p2 PT_GUARDED_BY(mu); 172 unique_ptr<int> p3 PT_GUARDED_BY(mu); 173 174 void test() { 175 p1 = 0; // Warning! 176 177 *p2 = 42; // Warning! 178 p2 = new int; // OK. 179 180 *p3 = 42; // Warning! 181 p3.reset(new int); // OK. 182 } 183 184 185REQUIRES(...), REQUIRES_SHARED(...) 186----------------------------------- 187 188*Previously*: ``EXCLUSIVE_LOCKS_REQUIRED``, ``SHARED_LOCKS_REQUIRED`` 189 190``REQUIRES`` is an attribute on functions or methods, which 191declares that the calling thread must have exclusive access to the given 192capabilities. More than one capability may be specified. The capabilities 193must be held on entry to the function, *and must still be held on exit*. 194 195``REQUIRES_SHARED`` is similar, but requires only shared access. 196 197.. code-block:: c++ 198 199 Mutex mu1, mu2; 200 int a GUARDED_BY(mu1); 201 int b GUARDED_BY(mu2); 202 203 void foo() REQUIRES(mu1, mu2) { 204 a = 0; 205 b = 0; 206 } 207 208 void test() { 209 mu1.Lock(); 210 foo(); // Warning! Requires mu2. 211 mu1.Unlock(); 212 } 213 214 215ACQUIRE(...), ACQUIRE_SHARED(...), RELEASE(...), RELEASE_SHARED(...), RELEASE_GENERIC(...) 216------------------------------------------------------------------------------------------ 217 218*Previously*: ``EXCLUSIVE_LOCK_FUNCTION``, ``SHARED_LOCK_FUNCTION``, 219``UNLOCK_FUNCTION`` 220 221``ACQUIRE`` and ``ACQUIRE_SHARED`` are attributes on functions or methods 222declaring that the function acquires a capability, but does not release it. 223The given capability must not be held on entry, and will be held on exit 224(exclusively for ``ACQUIRE``, shared for ``ACQUIRE_SHARED``). 225 226``RELEASE``, ``RELEASE_SHARED``, and ``RELEASE_GENERIC`` declare that the 227function releases the given capability. The capability must be held on entry 228(exclusively for ``RELEASE``, shared for ``RELEASE_SHARED``, exclusively or 229shared for ``RELEASE_GENERIC``), and will no longer be held on exit. 230 231.. code-block:: c++ 232 233 Mutex mu; 234 MyClass myObject GUARDED_BY(mu); 235 236 void lockAndInit() ACQUIRE(mu) { 237 mu.Lock(); 238 myObject.init(); 239 } 240 241 void cleanupAndUnlock() RELEASE(mu) { 242 myObject.cleanup(); 243 } // Warning! Need to unlock mu. 244 245 void test() { 246 lockAndInit(); 247 myObject.doSomething(); 248 cleanupAndUnlock(); 249 myObject.doSomething(); // Warning, mu is not locked. 250 } 251 252If no argument is passed to ``ACQUIRE`` or ``RELEASE``, then the argument is 253assumed to be ``this``, and the analysis will not check the body of the 254function. This pattern is intended for use by classes which hide locking 255details behind an abstract interface. For example: 256 257.. code-block:: c++ 258 259 template <class T> 260 class CAPABILITY("mutex") Container { 261 private: 262 Mutex mu; 263 T* data; 264 265 public: 266 // Hide mu from public interface. 267 void Lock() ACQUIRE() { mu.Lock(); } 268 void Unlock() RELEASE() { mu.Unlock(); } 269 270 T& getElem(int i) { return data[i]; } 271 }; 272 273 void test() { 274 Container<int> c; 275 c.Lock(); 276 int i = c.getElem(0); 277 c.Unlock(); 278 } 279 280 281EXCLUDES(...) 282------------- 283 284*Previously*: ``LOCKS_EXCLUDED`` 285 286``EXCLUDES`` is an attribute on functions or methods, which declares that 287the caller must *not* hold the given capabilities. This annotation is 288used to prevent deadlock. Many mutex implementations are not re-entrant, so 289deadlock can occur if the function acquires the mutex a second time. 290 291.. code-block:: c++ 292 293 Mutex mu; 294 int a GUARDED_BY(mu); 295 296 void clear() EXCLUDES(mu) { 297 mu.Lock(); 298 a = 0; 299 mu.Unlock(); 300 } 301 302 void reset() { 303 mu.Lock(); 304 clear(); // Warning! Caller cannot hold 'mu'. 305 mu.Unlock(); 306 } 307 308Unlike ``REQUIRES``, ``EXCLUDES`` is optional. The analysis will not issue a 309warning if the attribute is missing, which can lead to false negatives in some 310cases. This issue is discussed further in :ref:`negative`. 311 312 313NO_THREAD_SAFETY_ANALYSIS 314------------------------- 315 316``NO_THREAD_SAFETY_ANALYSIS`` is an attribute on functions or methods, which 317turns off thread safety checking for that method. It provides an escape hatch 318for functions which are either (1) deliberately thread-unsafe, or (2) are 319thread-safe, but too complicated for the analysis to understand. Reasons for 320(2) will be described in the :ref:`limitations`, below. 321 322.. code-block:: c++ 323 324 class Counter { 325 Mutex mu; 326 int a GUARDED_BY(mu); 327 328 void unsafeIncrement() NO_THREAD_SAFETY_ANALYSIS { a++; } 329 }; 330 331Unlike the other attributes, NO_THREAD_SAFETY_ANALYSIS is not part of the 332interface of a function, and should thus be placed on the function definition 333(in the ``.cc`` or ``.cpp`` file) rather than on the function declaration 334(in the header). 335 336 337RETURN_CAPABILITY(c) 338-------------------- 339 340*Previously*: ``LOCK_RETURNED`` 341 342``RETURN_CAPABILITY`` is an attribute on functions or methods, which declares 343that the function returns a reference to the given capability. It is used to 344annotate getter methods that return mutexes. 345 346.. code-block:: c++ 347 348 class MyClass { 349 private: 350 Mutex mu; 351 int a GUARDED_BY(mu); 352 353 public: 354 Mutex* getMu() RETURN_CAPABILITY(mu) { return μ } 355 356 // analysis knows that getMu() == mu 357 void clear() REQUIRES(getMu()) { a = 0; } 358 }; 359 360 361ACQUIRED_BEFORE(...), ACQUIRED_AFTER(...) 362----------------------------------------- 363 364``ACQUIRED_BEFORE`` and ``ACQUIRED_AFTER`` are attributes on member 365declarations, specifically declarations of mutexes or other capabilities. 366These declarations enforce a particular order in which the mutexes must be 367acquired, in order to prevent deadlock. 368 369.. code-block:: c++ 370 371 Mutex m1; 372 Mutex m2 ACQUIRED_AFTER(m1); 373 374 // Alternative declaration 375 // Mutex m2; 376 // Mutex m1 ACQUIRED_BEFORE(m2); 377 378 void foo() { 379 m2.Lock(); 380 m1.Lock(); // Warning! m2 must be acquired after m1. 381 m1.Unlock(); 382 m2.Unlock(); 383 } 384 385 386CAPABILITY(<string>) 387-------------------- 388 389*Previously*: ``LOCKABLE`` 390 391``CAPABILITY`` is an attribute on classes, which specifies that objects of the 392class can be used as a capability. The string argument specifies the kind of 393capability in error messages, e.g. ``"mutex"``. See the ``Container`` example 394given above, or the ``Mutex`` class in :ref:`mutexheader`. 395 396 397SCOPED_CAPABILITY 398----------------- 399 400*Previously*: ``SCOPED_LOCKABLE`` 401 402``SCOPED_CAPABILITY`` is an attribute on classes that implement RAII-style 403locking, in which a capability is acquired in the constructor, and released in 404the destructor. Such classes require special handling because the constructor 405and destructor refer to the capability via different names; see the 406``MutexLocker`` class in :ref:`mutexheader`, below. 407 408Scoped capabilities are treated as capabilities that are implicitly acquired 409on construction and released on destruction. They are associated with 410the set of (regular) capabilities named in thread safety attributes on the 411constructor or function returning them by value (using C++17 guaranteed copy 412elision). Acquire-type attributes on other member functions are treated as 413applying to that set of associated capabilities, while ``RELEASE`` implies that 414a function releases all associated capabilities in whatever mode they're held. 415 416 417TRY_ACQUIRE(<bool>, ...), TRY_ACQUIRE_SHARED(<bool>, ...) 418--------------------------------------------------------- 419 420*Previously:* ``EXCLUSIVE_TRYLOCK_FUNCTION``, ``SHARED_TRYLOCK_FUNCTION`` 421 422These are attributes on a function or method that tries to acquire the given 423capability, and returns a boolean value indicating success or failure. 424The first argument must be ``true`` or ``false``, to specify which return value 425indicates success, and the remaining arguments are interpreted in the same way 426as ``ACQUIRE``. See :ref:`mutexheader`, below, for example uses. 427 428Because the analysis doesn't support conditional locking, a capability is 429treated as acquired after the first branch on the return value of a try-acquire 430function. 431 432.. code-block:: c++ 433 434 Mutex mu; 435 int a GUARDED_BY(mu); 436 437 void foo() { 438 bool success = mu.TryLock(); 439 a = 0; // Warning, mu is not locked. 440 if (success) { 441 a = 0; // Ok. 442 mu.Unlock(); 443 } else { 444 a = 0; // Warning, mu is not locked. 445 } 446 } 447 448 449ASSERT_CAPABILITY(...) and ASSERT_SHARED_CAPABILITY(...) 450-------------------------------------------------------- 451 452*Previously:* ``ASSERT_EXCLUSIVE_LOCK``, ``ASSERT_SHARED_LOCK`` 453 454These are attributes on a function or method which asserts the calling thread 455already holds the given capability, for example by performing a run-time test 456and terminating if the capability is not held. Presence of this annotation 457causes the analysis to assume the capability is held after calls to the 458annotated function. See :ref:`mutexheader`, below, for example uses. 459 460 461GUARDED_VAR and PT_GUARDED_VAR 462------------------------------ 463 464Use of these attributes has been deprecated. 465 466 467Warning flags 468------------- 469 470* ``-Wthread-safety``: Umbrella flag which turns on the following: 471 472 + ``-Wthread-safety-attributes``: Semantic checks for thread safety attributes. 473 + ``-Wthread-safety-analysis``: The core analysis. 474 + ``-Wthread-safety-precise``: Requires that mutex expressions match precisely. 475 This warning can be disabled for code which has a lot of aliases. 476 + ``-Wthread-safety-reference``: Checks when guarded members are passed by reference. 477 478 479:ref:`negative` are an experimental feature, which are enabled with: 480 481* ``-Wthread-safety-negative``: Negative capabilities. Off by default. 482 483When new features and checks are added to the analysis, they can often introduce 484additional warnings. Those warnings are initially released as *beta* warnings 485for a period of time, after which they are migrated into the standard analysis. 486 487* ``-Wthread-safety-beta``: New features. Off by default. 488 489 490.. _negative: 491 492Negative Capabilities 493===================== 494 495Thread Safety Analysis is designed to prevent both race conditions and 496deadlock. The GUARDED_BY and REQUIRES attributes prevent race conditions, by 497ensuring that a capability is held before reading or writing to guarded data, 498and the EXCLUDES attribute prevents deadlock, by making sure that a mutex is 499*not* held. 500 501However, EXCLUDES is an optional attribute, and does not provide the same 502safety guarantee as REQUIRES. In particular: 503 504 * A function which acquires a capability does not have to exclude it. 505 * A function which calls a function that excludes a capability does not 506 have transitively exclude that capability. 507 508As a result, EXCLUDES can easily produce false negatives: 509 510.. code-block:: c++ 511 512 class Foo { 513 Mutex mu; 514 515 void foo() { 516 mu.Lock(); 517 bar(); // No warning. 518 baz(); // No warning. 519 mu.Unlock(); 520 } 521 522 void bar() { // No warning. (Should have EXCLUDES(mu)). 523 mu.Lock(); 524 // ... 525 mu.Unlock(); 526 } 527 528 void baz() { 529 bif(); // No warning. (Should have EXCLUDES(mu)). 530 } 531 532 void bif() EXCLUDES(mu); 533 }; 534 535 536Negative requirements are an alternative EXCLUDES that provide 537a stronger safety guarantee. A negative requirement uses the REQUIRES 538attribute, in conjunction with the ``!`` operator, to indicate that a capability 539should *not* be held. 540 541For example, using ``REQUIRES(!mu)`` instead of ``EXCLUDES(mu)`` will produce 542the appropriate warnings: 543 544.. code-block:: c++ 545 546 class FooNeg { 547 Mutex mu; 548 549 void foo() REQUIRES(!mu) { // foo() now requires !mu. 550 mu.Lock(); 551 bar(); 552 baz(); 553 mu.Unlock(); 554 } 555 556 void bar() { 557 mu.Lock(); // WARNING! Missing REQUIRES(!mu). 558 // ... 559 mu.Unlock(); 560 } 561 562 void baz() { 563 bif(); // WARNING! Missing REQUIRES(!mu). 564 } 565 566 void bif() REQUIRES(!mu); 567 }; 568 569 570Negative requirements are an experimental feature which is off by default, 571because it will produce many warnings in existing code. It can be enabled 572by passing ``-Wthread-safety-negative``. 573 574 575.. _faq: 576 577Frequently Asked Questions 578========================== 579 580(Q) Should I put attributes in the header file, or in the .cc/.cpp/.cxx file? 581 582(A) Attributes are part of the formal interface of a function, and should 583always go in the header, where they are visible to anything that includes 584the header. Attributes in the .cpp file are not visible outside of the 585immediate translation unit, which leads to false negatives and false positives. 586 587 588(Q) "*Mutex is not locked on every path through here?*" What does that mean? 589 590(A) See :ref:`conditional_locks`, below. 591 592 593.. _limitations: 594 595Known Limitations 596================= 597 598Lexical scope 599------------- 600 601Thread safety attributes contain ordinary C++ expressions, and thus follow 602ordinary C++ scoping rules. In particular, this means that mutexes and other 603capabilities must be declared before they can be used in an attribute. 604Use-before-declaration is okay within a single class, because attributes are 605parsed at the same time as method bodies. (C++ delays parsing of method bodies 606until the end of the class.) However, use-before-declaration is not allowed 607between classes, as illustrated below. 608 609.. code-block:: c++ 610 611 class Foo; 612 613 class Bar { 614 void bar(Foo* f) REQUIRES(f->mu); // Error: mu undeclared. 615 }; 616 617 class Foo { 618 Mutex mu; 619 }; 620 621 622Private Mutexes 623--------------- 624 625Good software engineering practice dictates that mutexes should be private 626members, because the locking mechanism used by a thread-safe class is part of 627its internal implementation. However, private mutexes can sometimes leak into 628the public interface of a class. 629Thread safety attributes follow normal C++ access restrictions, so if ``mu`` 630is a private member of ``c``, then it is an error to write ``c.mu`` in an 631attribute. 632 633One workaround is to (ab)use the ``RETURN_CAPABILITY`` attribute to provide a 634public *name* for a private mutex, without actually exposing the underlying 635mutex. For example: 636 637.. code-block:: c++ 638 639 class MyClass { 640 private: 641 Mutex mu; 642 643 public: 644 // For thread safety analysis only. Does not need to be defined. 645 Mutex* getMu() RETURN_CAPABILITY(mu); 646 647 void doSomething() REQUIRES(mu); 648 }; 649 650 void doSomethingTwice(MyClass& c) REQUIRES(c.getMu()) { 651 // The analysis thinks that c.getMu() == c.mu 652 c.doSomething(); 653 c.doSomething(); 654 } 655 656In the above example, ``doSomethingTwice()`` is an external routine that 657requires ``c.mu`` to be locked, which cannot be declared directly because ``mu`` 658is private. This pattern is discouraged because it 659violates encapsulation, but it is sometimes necessary, especially when adding 660annotations to an existing code base. The workaround is to define ``getMu()`` 661as a fake getter method, which is provided only for the benefit of thread 662safety analysis. 663 664 665.. _conditional_locks: 666 667No conditionally held locks. 668---------------------------- 669 670The analysis must be able to determine whether a lock is held, or not held, at 671every program point. Thus, sections of code where a lock *might be held* will 672generate spurious warnings (false positives). For example: 673 674.. code-block:: c++ 675 676 void foo() { 677 bool b = needsToLock(); 678 if (b) mu.Lock(); 679 ... // Warning! Mutex 'mu' is not held on every path through here. 680 if (b) mu.Unlock(); 681 } 682 683 684No checking inside constructors and destructors. 685------------------------------------------------ 686 687The analysis currently does not do any checking inside constructors or 688destructors. In other words, every constructor and destructor is treated as 689if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``. 690The reason for this is that during initialization, only one thread typically 691has access to the object which is being initialized, and it is thus safe (and 692common practice) to initialize guarded members without acquiring any locks. 693The same is true of destructors. 694 695Ideally, the analysis would allow initialization of guarded members inside the 696object being initialized or destroyed, while still enforcing the usual access 697restrictions on everything else. However, this is difficult to enforce in 698practice, because in complex pointer-based data structures, it is hard to 699determine what data is owned by the enclosing object. 700 701No inlining. 702------------ 703 704Thread safety analysis is strictly intra-procedural, just like ordinary type 705checking. It relies only on the declared attributes of a function, and will 706not attempt to inline any method calls. As a result, code such as the 707following will not work: 708 709.. code-block:: c++ 710 711 template<class T> 712 class AutoCleanup { 713 T* object; 714 void (T::*mp)(); 715 716 public: 717 AutoCleanup(T* obj, void (T::*imp)()) : object(obj), mp(imp) { } 718 ~AutoCleanup() { (object->*mp)(); } 719 }; 720 721 Mutex mu; 722 void foo() { 723 mu.Lock(); 724 AutoCleanup<Mutex>(&mu, &Mutex::Unlock); 725 // ... 726 } // Warning, mu is not unlocked. 727 728In this case, the destructor of ``Autocleanup`` calls ``mu.Unlock()``, so 729the warning is bogus. However, 730thread safety analysis cannot see the unlock, because it does not attempt to 731inline the destructor. Moreover, there is no way to annotate the destructor, 732because the destructor is calling a function that is not statically known. 733This pattern is simply not supported. 734 735 736No alias analysis. 737------------------ 738 739The analysis currently does not track pointer aliases. Thus, there can be 740false positives if two pointers both point to the same mutex. 741 742 743.. code-block:: c++ 744 745 class MutexUnlocker { 746 Mutex* mu; 747 748 public: 749 MutexUnlocker(Mutex* m) RELEASE(m) : mu(m) { mu->Unlock(); } 750 ~MutexUnlocker() ACQUIRE(mu) { mu->Lock(); } 751 }; 752 753 Mutex mutex; 754 void test() REQUIRES(mutex) { 755 { 756 MutexUnlocker munl(&mutex); // unlocks mutex 757 doSomeIO(); 758 } // Warning: locks munl.mu 759 } 760 761The MutexUnlocker class is intended to be the dual of the MutexLocker class, 762defined in :ref:`mutexheader`. However, it doesn't work because the analysis 763doesn't know that munl.mu == mutex. The SCOPED_CAPABILITY attribute handles 764aliasing for MutexLocker, but does so only for that particular pattern. 765 766 767ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) are currently unimplemented. 768------------------------------------------------------------------------- 769 770To be fixed in a future update. 771 772 773.. _mutexheader: 774 775mutex.h 776======= 777 778Thread safety analysis can be used with any threading library, but it does 779require that the threading API be wrapped in classes and methods which have the 780appropriate annotations. The following code provides ``mutex.h`` as an example; 781these methods should be filled in to call the appropriate underlying 782implementation. 783 784 785.. code-block:: c++ 786 787 788 #ifndef THREAD_SAFETY_ANALYSIS_MUTEX_H 789 #define THREAD_SAFETY_ANALYSIS_MUTEX_H 790 791 // Enable thread safety attributes only with clang. 792 // The attributes can be safely erased when compiling with other compilers. 793 #if defined(__clang__) && (!defined(SWIG)) 794 #define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) 795 #else 796 #define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op 797 #endif 798 799 #define CAPABILITY(x) \ 800 THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) 801 802 #define SCOPED_CAPABILITY \ 803 THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) 804 805 #define GUARDED_BY(x) \ 806 THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) 807 808 #define PT_GUARDED_BY(x) \ 809 THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) 810 811 #define ACQUIRED_BEFORE(...) \ 812 THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) 813 814 #define ACQUIRED_AFTER(...) \ 815 THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) 816 817 #define REQUIRES(...) \ 818 THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) 819 820 #define REQUIRES_SHARED(...) \ 821 THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) 822 823 #define ACQUIRE(...) \ 824 THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) 825 826 #define ACQUIRE_SHARED(...) \ 827 THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) 828 829 #define RELEASE(...) \ 830 THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) 831 832 #define RELEASE_SHARED(...) \ 833 THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) 834 835 #define RELEASE_GENERIC(...) \ 836 THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(__VA_ARGS__)) 837 838 #define TRY_ACQUIRE(...) \ 839 THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) 840 841 #define TRY_ACQUIRE_SHARED(...) \ 842 THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) 843 844 #define EXCLUDES(...) \ 845 THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) 846 847 #define ASSERT_CAPABILITY(x) \ 848 THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) 849 850 #define ASSERT_SHARED_CAPABILITY(x) \ 851 THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) 852 853 #define RETURN_CAPABILITY(x) \ 854 THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) 855 856 #define NO_THREAD_SAFETY_ANALYSIS \ 857 THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) 858 859 860 // Defines an annotated interface for mutexes. 861 // These methods can be implemented to use any internal mutex implementation. 862 class CAPABILITY("mutex") Mutex { 863 public: 864 // Acquire/lock this mutex exclusively. Only one thread can have exclusive 865 // access at any one time. Write operations to guarded data require an 866 // exclusive lock. 867 void Lock() ACQUIRE(); 868 869 // Acquire/lock this mutex for read operations, which require only a shared 870 // lock. This assumes a multiple-reader, single writer semantics. Multiple 871 // threads may acquire the mutex simultaneously as readers, but a writer 872 // must wait for all of them to release the mutex before it can acquire it 873 // exclusively. 874 void ReaderLock() ACQUIRE_SHARED(); 875 876 // Release/unlock an exclusive mutex. 877 void Unlock() RELEASE(); 878 879 // Release/unlock a shared mutex. 880 void ReaderUnlock() RELEASE_SHARED(); 881 882 // Generic unlock, can unlock exclusive and shared mutexes. 883 void GenericUnlock() RELEASE_GENERIC(); 884 885 // Try to acquire the mutex. Returns true on success, and false on failure. 886 bool TryLock() TRY_ACQUIRE(true); 887 888 // Try to acquire the mutex for read operations. 889 bool ReaderTryLock() TRY_ACQUIRE_SHARED(true); 890 891 // Assert that this mutex is currently held by the calling thread. 892 void AssertHeld() ASSERT_CAPABILITY(this); 893 894 // Assert that is mutex is currently held for read operations. 895 void AssertReaderHeld() ASSERT_SHARED_CAPABILITY(this); 896 897 // For negative capabilities. 898 const Mutex& operator!() const { return *this; } 899 }; 900 901 // Tag types for selecting a constructor. 902 struct adopt_lock_t {} inline constexpr adopt_lock = {}; 903 struct defer_lock_t {} inline constexpr defer_lock = {}; 904 struct shared_lock_t {} inline constexpr shared_lock = {}; 905 906 // MutexLocker is an RAII class that acquires a mutex in its constructor, and 907 // releases it in its destructor. 908 class SCOPED_CAPABILITY MutexLocker { 909 private: 910 Mutex* mut; 911 bool locked; 912 913 public: 914 // Acquire mu, implicitly acquire *this and associate it with mu. 915 MutexLocker(Mutex *mu) ACQUIRE(mu) : mut(mu), locked(true) { 916 mu->Lock(); 917 } 918 919 // Assume mu is held, implicitly acquire *this and associate it with mu. 920 MutexLocker(Mutex *mu, adopt_lock_t) REQUIRES(mu) : mut(mu), locked(true) {} 921 922 // Acquire mu in shared mode, implicitly acquire *this and associate it with mu. 923 MutexLocker(Mutex *mu, shared_lock_t) ACQUIRE_SHARED(mu) : mut(mu), locked(true) { 924 mu->ReaderLock(); 925 } 926 927 // Assume mu is held in shared mode, implicitly acquire *this and associate it with mu. 928 MutexLocker(Mutex *mu, adopt_lock_t, shared_lock_t) REQUIRES_SHARED(mu) 929 : mut(mu), locked(true) {} 930 931 // Assume mu is not held, implicitly acquire *this and associate it with mu. 932 MutexLocker(Mutex *mu, defer_lock_t) EXCLUDES(mu) : mut(mu), locked(false) {} 933 934 // Same as constructors, but without tag types. (Requires C++17 copy elision.) 935 static MutexLocker Lock(Mutex *mu) ACQUIRE(mu); 936 static MutexLocker Adopt(Mutex *mu) REQUIRES(mu); 937 static MutexLocker ReaderLock(Mutex *mu) ACQUIRE_SHARED(mu); 938 static MutexLocker AdoptReaderLock(Mutex *mu) REQUIRES_SHARED(mu); 939 static MutexLocker DeferLock(Mutex *mu) EXCLUDES(mu); 940 941 // Release *this and all associated mutexes, if they are still held. 942 // There is no warning if the scope was already unlocked before. 943 ~MutexLocker() RELEASE() { 944 if (locked) 945 mut->GenericUnlock(); 946 } 947 948 // Acquire all associated mutexes exclusively. 949 void Lock() ACQUIRE() { 950 mut->Lock(); 951 locked = true; 952 } 953 954 // Try to acquire all associated mutexes exclusively. 955 bool TryLock() TRY_ACQUIRE(true) { 956 return locked = mut->TryLock(); 957 } 958 959 // Acquire all associated mutexes in shared mode. 960 void ReaderLock() ACQUIRE_SHARED() { 961 mut->ReaderLock(); 962 locked = true; 963 } 964 965 // Try to acquire all associated mutexes in shared mode. 966 bool ReaderTryLock() TRY_ACQUIRE_SHARED(true) { 967 return locked = mut->ReaderTryLock(); 968 } 969 970 // Release all associated mutexes. Warn on double unlock. 971 void Unlock() RELEASE() { 972 mut->Unlock(); 973 locked = false; 974 } 975 976 // Release all associated mutexes. Warn on double unlock. 977 void ReaderUnlock() RELEASE() { 978 mut->ReaderUnlock(); 979 locked = false; 980 } 981 }; 982 983 984 #ifdef USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES 985 // The original version of thread safety analysis the following attribute 986 // definitions. These use a lock-based terminology. They are still in use 987 // by existing thread safety code, and will continue to be supported. 988 989 // Deprecated. 990 #define PT_GUARDED_VAR \ 991 THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_var) 992 993 // Deprecated. 994 #define GUARDED_VAR \ 995 THREAD_ANNOTATION_ATTRIBUTE__(guarded_var) 996 997 // Replaced by REQUIRES 998 #define EXCLUSIVE_LOCKS_REQUIRED(...) \ 999 THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__)) 1000 1001 // Replaced by REQUIRES_SHARED 1002 #define SHARED_LOCKS_REQUIRED(...) \ 1003 THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__)) 1004 1005 // Replaced by CAPABILITY 1006 #define LOCKABLE \ 1007 THREAD_ANNOTATION_ATTRIBUTE__(lockable) 1008 1009 // Replaced by SCOPED_CAPABILITY 1010 #define SCOPED_LOCKABLE \ 1011 THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) 1012 1013 // Replaced by ACQUIRE 1014 #define EXCLUSIVE_LOCK_FUNCTION(...) \ 1015 THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__)) 1016 1017 // Replaced by ACQUIRE_SHARED 1018 #define SHARED_LOCK_FUNCTION(...) \ 1019 THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__)) 1020 1021 // Replaced by RELEASE and RELEASE_SHARED 1022 #define UNLOCK_FUNCTION(...) \ 1023 THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__)) 1024 1025 // Replaced by TRY_ACQUIRE 1026 #define EXCLUSIVE_TRYLOCK_FUNCTION(...) \ 1027 THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__)) 1028 1029 // Replaced by TRY_ACQUIRE_SHARED 1030 #define SHARED_TRYLOCK_FUNCTION(...) \ 1031 THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__)) 1032 1033 // Replaced by ASSERT_CAPABILITY 1034 #define ASSERT_EXCLUSIVE_LOCK(...) \ 1035 THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__)) 1036 1037 // Replaced by ASSERT_SHARED_CAPABILITY 1038 #define ASSERT_SHARED_LOCK(...) \ 1039 THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__)) 1040 1041 // Replaced by EXCLUDE_CAPABILITY. 1042 #define LOCKS_EXCLUDED(...) \ 1043 THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) 1044 1045 // Replaced by RETURN_CAPABILITY 1046 #define LOCK_RETURNED(x) \ 1047 THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) 1048 1049 #endif // USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES 1050 1051 #endif // THREAD_SAFETY_ANALYSIS_MUTEX_H 1052