r218420 - Thread Safety Analysis: Update to documentation.

DeLesley Hutchins delesley at google.com
Wed Sep 24 15:13:34 PDT 2014


Author: delesley
Date: Wed Sep 24 17:13:34 2014
New Revision: 218420

URL: http://llvm.org/viewvc/llvm-project?rev=218420&view=rev
Log:
Thread Safety Analysis:  Update to documentation.

The attribute documentation now conforms to Aaron Ballman's renaming of the
thread safety attributes, as well as the new paper that is due to be published
in the conference on Source Code Analysis and Manipulation (SCAM 2014) later
this week.  In addition, recent changes to the analysis, such as checking
of references and negative capabilities, are now documented.

Modified:
    cfe/trunk/docs/ThreadSafetyAnalysis.rst

Modified: cfe/trunk/docs/ThreadSafetyAnalysis.rst
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ThreadSafetyAnalysis.rst?rev=218420&r1=218419&r2=218420&view=diff
==============================================================================
--- cfe/trunk/docs/ThreadSafetyAnalysis.rst (original)
+++ cfe/trunk/docs/ThreadSafetyAnalysis.rst Wed Sep 24 17:13:34 2014
@@ -21,7 +21,7 @@ controlled in a multi-threaded environme
 a piece of code reads or writes to ``foo`` without first locking ``mu``.
 Similarly, if there are particular routines that should only be called by
 the GUI thread, then the analysis will warn if other threads call those
-routines. 
+routines.
 
 Getting Started
 ----------------
@@ -34,21 +34,21 @@ Getting Started
   private:
     Mutex mu;
     int   balance GUARDED_BY(mu);
-  
+
     void depositImpl(int amount) {
       balance += amount;       // WARNING! Cannot write balance without locking mu.
     }
-  
-    void withdrawImpl(int amount) EXCLUSIVE_LOCKS_REQUIRED(mu) {
+
+    void withdrawImpl(int amount) REQUIRES(mu) {
       balance -= amount;       // OK. Caller must have locked mu.
     }
-  
+
   public:
     void withdraw(int amount) {
       mu.Lock();
       withdrawImpl(amount);    // OK.  We've locked mu.
     }                          // WARNING!  Failed to unlock mu.
-  
+
     void transferFrom(BankAccount& b, int amount) {
       mu.Lock();
       b.withdrawImpl(amount);  // WARNING!  Calling withdrawImpl() requires locking b.mu.
@@ -60,23 +60,23 @@ Getting Started
 This example demonstrates the basic concepts behind the analysis.  The
 ``GUARDED_BY`` attribute declares that a thread must lock ``mu`` before it can
 read or write to ``balance``, thus ensuring that the increment and decrement
-operations are atomic.  Similarly, ``EXCLUSIVE_LOCKS_REQUIRED`` declares that
+operations are atomic.  Similarly, ``REQUIRES`` declares that
 the calling thread must lock ``mu`` before calling ``withdrawImpl``.
 Because the caller is assumed to have locked ``mu``, it is safe to modify
 ``balance`` within the body of the method.
 
-The ``depositImpl()`` method does not have ``EXCLUSIVE_LOCKS_REQUIRED``, so the
+The ``depositImpl()`` method does not have ``REQUIRES``, so the
 analysis issues a warning.  Thread safety analysis is not inter-procedural, so
 caller requirements must be explicitly declared.
 There is also a warning in ``transferFrom()``, because although the method
 locks ``this->mu``, it does not lock ``b.mu``.  The analysis understands
-that these are two separate mutexes, in two different objects.  
+that these are two separate mutexes, in two different objects.
 
 Finally, there is a warning in the ``withdraw()`` method, because it fails to
 unlock ``mu``.  Every lock must have a corresponding unlock, and the analysis
 will detect both double locks, and double unlocks.  A function is allowed to
 acquire a lock without releasing it, (or vice versa), but it must be annotated
-as such (using ``LOCK``/``UNLOCK_FUNCTION``).
+as such (using ``ACQUIRE``/``RELEASE``).
 
 
 Running The Analysis
@@ -90,7 +90,7 @@ To run the analysis, simply compile with
 
 Note that this example assumes the presence of a suitably annotated
 :ref:`mutexheader` that declares which methods perform locking,
-unlocking, and so on. 
+unlocking, and so on.
 
 
 Basic Concepts: Capabilities
@@ -106,14 +106,14 @@ Capabilities are associated with named C
 methods to acquire and release the capability.  The name of the object serves
 to identify the capability.  The most common example is a mutex.  For example,
 if ``mu`` is a mutex, then calling ``mu.Lock()`` causes the calling thread
-to acquire the capability to access data that is protected by ``mu``. Similarly, 
+to acquire the capability to access data that is protected by ``mu``. Similarly,
 calling ``mu.Unlock()`` releases that capability.
 
 A thread may hold a capability either *exclusively* or *shared*.  An exclusive
 capability can be held by only one thread at a time, while a shared capability
 can be held by many threads at the same time.  This mechanism enforces a
 multiple-reader, single-writer pattern.  Write operations to protected data
-require exclusive access, while read operations require only shared access.  
+require exclusive access, while read operations require only shared access.
 
 At any given moment during program execution, a thread holds a specific set of
 capabilities (e.g. the set of mutexes that it has locked.)  These act like keys
@@ -121,7 +121,7 @@ or tokens that allow the thread to acces
 security keys, a thread cannot make copy of a capability, nor can it destroy
 one.  A thread can only release a capability to another thread, or acquire one
 from another thread.  The annotations are deliberately agnostic about the
-exact mechanism used to acquire and release capabilities; it assumes that the 
+exact mechanism used to acquire and release capabilities; it assumes that the
 underlying implementation (e.g. the Mutex implementation) does the handoff in
 an appropriate manner.
 
@@ -144,6 +144,11 @@ and data members. Users are *strongly ad
 attributes; example definitions can be found in :ref:`mutexheader`, below.
 The following documentation assumes the use of macros.
 
+For historical reasons, prior versions of thread safety used macro names that
+were very lock-centric.  These macros have since been renamed to fit a more
+general capability model.  The prior names are still in use, and will be
+mentioned under the tag *previously* where appropriate.
+
 
 GUARDED_BY(c) and PT_GUARDED_BY(c)
 ----------------------------------
@@ -154,47 +159,49 @@ require shared access, while write opera
 
 ``PT_GUARDED_BY`` is similar, but is intended for use on pointers and smart
 pointers. There is no constraint on the data member itself, but the *data that
-it points to* is protected by the given capability.  
+it points to* is protected by the given capability.
 
 .. code-block:: c++
 
   Mutex mu;
-  int *p1            GUARDED_BY(mu);
-  int *p2            PT_GUARDED_BY(mu);
-  unique_ptr<int> p3 PT_GUARDED_BY(mu);
-  
+  int *p1             GUARDED_BY(mu);
+  int *p2             PT_GUARDED_BY(mu);
+  unique_ptr<int> p3  PT_GUARDED_BY(mu);
+
   void test() {
     p1 = 0;             // Warning!
-  
-    p2 = new int;       // OK.
+
     *p2 = 42;           // Warning!
-  
-    p3.reset(new int);  // OK.
+    p2 = new int;       // OK.
+
     *p3 = 42;           // Warning!
+    p3.reset(new int);  // OK.
   }
 
 
-EXCLUSIVE_LOCKS_REQUIRED(...), SHARED_LOCKS_REQUIRED(...)
----------------------------------------------------------
+REQUIRES(...), REQUIRES_SHARED(...)
+-----------------------------------
+
+*Previously*: ``EXCLUSIVE_LOCKS_REQUIRED``, ``SHARED_LOCKS_REQUIRED``
 
-``EXCLUSIVE_LOCKS_REQUIRED`` is an attribute on functions or methods, which
+``REQUIRES`` is an attribute on functions or methods, which
 declares that the calling thread must have exclusive access to the given
 capabilities.  More than one capability may be specified.  The capabilities
-must be held on entry to the function, *and must still be held on exit*.  
+must be held on entry to the function, *and must still be held on exit*.
 
-``SHARED_LOCKS_REQUIRED`` is similar, but requires only shared access.
+``REQUIRES_SHARED`` is similar, but requires only shared access.
 
 .. code-block:: c++
 
   Mutex mu1, mu2;
   int a GUARDED_BY(mu1);
   int b GUARDED_BY(mu2);
-  
-  void foo() EXCLUSIVE_LOCKS_REQUIRED(mu1, mu2) {
+
+  void foo() REQUIRES(mu1, mu2) {
     a = 0;
     b = 0;
   }
-  
+
   void test() {
     mu1.Lock();
     foo();         // Warning!  Requires mu2.
@@ -202,32 +209,36 @@ must be held on entry to the function, *
   }
 
 
-EXCLUSIVE_LOCK_FUNCTION(...), SHARED_LOCK_FUNCTION(...), UNLOCK_FUNCTION(...)
------------------------------------------------------------------------------
+ACQUIRE(...), ACQUIRE_SHARED(...), RELEASE(...), RELEASE_SHARED(...)
+--------------------------------------------------------------------
+
+*Previously*: ``EXCLUSIVE_LOCK_FUNCTION``, ``SHARED_LOCK_FUNCTION``,
+``UNLOCK_FUNCTION``
 
-``EXCLUSIVE_LOCK_FUNCTION`` is an attribute on functions or methods, which
+``ACQUIRE`` is an attribute on functions or methods, which
 declares that the function acquires a capability, but does not release it.  The
 caller must not hold the given capability on entry, and it will hold the
-capability on exit.  ``SHARED_LOCK_FUNCTION`` is similar. 
+capability on exit.  ``ACQUIRE_SHARED`` is similar.
 
-``UNLOCK_FUNCTION`` declares that the function releases the given capability.
-The caller must hold the capability on entry, and will no longer hold it on
-exit. It does not matter whether the given capability is shared or exclusive.
+``RELEASE`` and ``RELEASE_SHARED`` declare that the function releases the given
+capability.  The caller must hold the capability on entry, and will no longer
+hold it on exit. It does not matter whether the given capability is shared or
+exclusive.
 
 .. code-block:: c++
 
   Mutex mu;
   MyClass myObject GUARDED_BY(mu);
-  
-  void lockAndInit() EXCLUSIVE_LOCK_FUNCTION(mu) {
+
+  void lockAndInit() ACQUIRE(mu) {
     mu.Lock();
     myObject.init();
   }
-  
-  void cleanupAndUnlock() UNLOCK_FUNCTION(mu) {
+
+  void cleanupAndUnlock() RELEASE(mu) {
     myObject.cleanup();
-  }  // Warning!  Need to unlock mu.
-  
+  }                          // Warning!  Need to unlock mu.
+
   void test() {
     lockAndInit();
     myObject.doSomething();
@@ -235,27 +246,27 @@ exit. It does not matter whether the giv
     myObject.doSomething();  // Warning, mu is not locked.
   }
 
-If no argument is passed to ``(UN)LOCK_FUNCTION``, then the argument is assumed
-to be ``this``, and the analysis will not check the body of the function.  This
-pattern is intended for use by classes which hide locking details behind an
-abstract interface.  E.g.
+If no argument is passed to ``ACQUIRE`` or ``RELEASE``, then the argument is
+assumed to be ``this``, and the analysis will not check the body of the
+function.  This pattern is intended for use by classes which hide locking
+details behind an abstract interface.  For example:
 
 .. code-block:: c++
 
   template <class T>
-  class LOCKABLE Container {
+  class CAPABILITY("mutex") Container {
   private:
     Mutex mu;
     T* data;
-  
+
   public:
     // Hide mu from public interface.
-    void Lock() EXCLUSIVE_LOCK_FUNCTION() { mu.Lock(); }
-    void Unlock() UNLOCK_FUNCTION() { mu.Unlock(); }
-  
+    void Lock()   ACQUIRE() { mu.Lock(); }
+    void Unlock() RELEASE() { mu.Unlock(); }
+
     T& getElem(int i) { return data[i]; }
   };
-  
+
   void test() {
     Container<int> c;
     c.Lock();
@@ -264,33 +275,36 @@ abstract interface.  E.g.
   }
 
 
-LOCKS_EXCLUDED(...)
--------------------
+EXCLUDES(...)
+-------------
+
+*Previously*: ``LOCKS_EXCLUDED``
 
-``LOCKS_EXCLUDED`` is an attribute on functions or methods, which declares that
+``EXCLUDES`` is an attribute on functions or methods, which declares that
 the caller must *not* hold the given capabilities.  This annotation is
 used to prevent deadlock.  Many mutex implementations are not re-entrant, so
-deadlock can occur if the function in question acquires the mutex a second time.
+deadlock can occur if the function acquires the mutex a second time.
 
 .. code-block:: c++
 
   Mutex mu;
   int a GUARDED_BY(mu);
-  
-  void clear() LOCKS_EXCLUDED(mu) {
+
+  void clear() EXCLUDES(mu) {
     mu.Lock();
     a = 0;
     mu.Unlock();
   }
-  
+
   void reset() {
     mu.Lock();
     clear();     // Warning!  Caller cannot hold 'mu'.
     mu.Unlock();
   }
 
-Unlike ``LOCKS_REQUIRED``, ``LOCKS_EXCLUDED`` is optional.  The analysis will
-not issue a warning if the attribute is missing.  See :ref:`limitations`.
+Unlike ``REQUIRES``, ``EXCLUDES`` is optional.  The analysis will not issue a
+warning if the attribute is missing, which can lead to false negatives in some
+cases.  This issue is discussed further in :ref:`negative`.
 
 
 NO_THREAD_SAFETY_ANALYSIS
@@ -307,16 +321,23 @@ thread-safe, but too complicated for the
   class Counter {
     Mutex mu;
     int a GUARDED_BY(mu);
-  
+
     void unsafeIncrement() NO_THREAD_SAFETY_ANALYSIS { a++; }
   };
 
+Unlike the other attributes, NO_THREAD_SAFETY_ANALYSIS is not part of the
+interface of a function, and should thus be placed on the function definition
+(in the ``.cc`` or ``.cpp`` file) rather than on the function delaration
+(in the header).
 
-LOCK_RETURNED(c)
-----------------
 
-``LOCK_RETURNED`` is an attribute on functions or methods, which declares that
-the function returns a reference to the given capability.  It is used to
+RETURN_CAPABILITY(c)
+--------------------
+
+*Previously*: ``LOCK_RETURNED``
+
+``RETURN_CAPABILITY`` is an attribute on functions or methods, which declares
+that the function returns a reference to the given capability.  It is used to
 annotate getter methods that return mutexes.
 
 .. code-block:: c++
@@ -325,12 +346,12 @@ annotate getter methods that return mute
   private:
     Mutex mu;
     int a GUARDED_BY(mu);
-  
+
   public:
-    Mutex* getMu() LOCK_RETURNED(mu) { return μ }
-  
+    Mutex* getMu() RETURN_CAPABILITY(mu) { return μ }
+
     // analysis knows that getMu() == mu
-    void clear() EXCLUSIVE_LOCKS_REQUIRED(getMu()) { a = 0; }
+    void clear() REQUIRES(getMu()) { a = 0; }
   };
 
 
@@ -346,11 +367,11 @@ acquired, in order to prevent deadlock.
 
   Mutex m1;
   Mutex m2 ACQUIRED_AFTER(m1);
-  
+
   // Alternative declaration
   // Mutex m2;
   // Mutex m1 ACQUIRED_BEFORE(m2);
-  
+
   void foo() {
     m2.Lock();
     m1.Lock();  // Warning!  m2 must be acquired after m1.
@@ -359,36 +380,45 @@ acquired, in order to prevent deadlock.
   }
 
 
-LOCKABLE
---------
+CAPABILITY(<string>)
+--------------------
 
-``LOCKABLE`` is an attribute on classes, which specifies that objects of the
-class can be used as a capability.  See the ``Container`` example given above,
-or the ``Mutex`` class in :ref:`mutexheader`.
+*Previously*: ``LOCKABLE``
 
+``CAPABILITY`` is an attribute on classes, which specifies that objects of the
+class can be used as a capability.  The string argument specifies the kind of
+capability in error messages, e.g. ``"mutex"``.  See the ``Container`` example
+given above, or the ``Mutex`` class in :ref:`mutexheader`.
 
-SCOPED_LOCKABLE
----------------
 
-``SCOPED_LOCKABLE`` is an attribute on classes that implement RAII-style
+SCOPED_CAPABILITY
+-----------------
+
+*Previously*: ``SCOPED_LOCKABLE``
+
+``SCOPED_CAPABILITY`` is an attribute on classes that implement RAII-style
 locking, in which a capability is acquired in the constructor, and released in
 the destructor.  Such classes require special handling because the constructor
 and destructor refer to the capability via different names; see the
 ``MutexLocker`` class in :ref:`mutexheader`, below.
 
 
-EXCLUSIVE_TRYLOCK_FUNCTION(<bool>, ...), SHARED_TRYLOCK_FUNCTION(<bool>, ...)
------------------------------------------------------------------------------
+TRY_ACQUIRE(<bool>, ...), TRY_ACQUIRE_SHARED(<bool>, ...)
+---------------------------------------------------------
+
+*Previously:* ``EXCLUSIVE_TRYLOCK_FUNCTION``, ``SHARED_TRYLOCK_FUNCTION``
 
 These are attributes on a function or method that tries to acquire the given
 capability, and returns a boolean value indicating success or failure.
 The first argument must be ``true`` or ``false``, to specify which return value
 indicates success, and the remaining arguments are interpreted in the same way
-as ``(UN)LOCK_FUNCTION``.  See :ref:`mutexheader`, below, for example uses.
+as ``ACQUIRE``.  See :ref:`mutexheader`, below, for example uses.
 
 
-ASSERT_EXCLUSIVE_LOCK(...) and ASSERT_SHARED_LOCK(...)
-------------------------------------------------------
+ASSERT_CAPABILITY(...) and ASSERT_SHARED_CAPABILITY(...)
+--------------------------------------------------------
+
+*Previously:*  ``ASSERT_EXCLUSIVE_LOCK``, ``ASSERT_SHARED_LOCK``
 
 These are attributes on a function or method that does a run-time test to see
 whether the calling thread holds the given capability.  The function is assumed
@@ -410,13 +440,104 @@ Warning flags
   + ``-Wthread-safety-attributes``: Sanity checks on attribute syntax.
   + ``-Wthread-safety-analysis``: The core analysis.
   + ``-Wthread-safety-precise``: Requires that mutex expressions match precisely.
-    This warning can be disabled for code which has a lot of aliases.
+       This warning can be disabled for code which has a lot of aliases.
+  + ``-Wthread-safety-reference``: Checks when guarded members are passed by reference.
+
+
+:ref:`negative` are an experimental feature, which are enabled with:
+
+* ``-Wthread-safety-negative``:  Negative capabilities.  Off by default.
 
 When new features and checks are added to the analysis, they can often introduce
 additional warnings.  Those warnings are initially released as *beta* warnings
-for a period of time, after which they are migrated to the standard analysis.  
+for a period of time, after which they are migrated into the standard analysis.
+
+* ``-Wthread-safety-beta``:  New features.  Off by default.
+
+
+.. _negative:
+
+Negative Capabilities
+=====================
+
+Thread Safety Analysis is designed to prevent both race conditions and
+deadlock.  The GUARDED_BY and REQUIRES attributes prevent race conditions, by
+ensuring that a capability is held before reading or writing to guarded data,
+and the EXCLUDES attribute prevents deadlock, by making sure that a mutex is
+*not* held.
+
+However, EXCLUDES is an optional attribute, and does not provide the same
+safety guarantee as REQUIRES.  In particular:
+
+  * A function which acquires a capability does not have to exclude it.
+  * A function which calls a function that excludes a capability does not
+    have transitively exclude that capability.
+
+As a result, EXCLUDES can easily produce false negatives:
+
+.. code-block:: c++
+
+  class Foo {
+    Mutex mu;
 
-* ``-Wthread-safety-beta``:  New features.  Off by default. 
+    void foo() {
+      mu.Lock();
+      bar();           // No warning.
+      baz();           // No warning.
+      mu.Unlock();
+    }
+
+    void bar() {       // No warning.  (Should have EXCLUDES(mu)).
+      mu.Lock();
+      // ...
+      mu.Unlock();
+    }
+
+    void baz() {
+      bif();           // No warning.  (Should have EXCLUDES(mu)).
+    }
+
+    void bif() EXCLUDES(mu);
+  };
+
+
+Negative requirements are an alternative EXCLUDES that provide
+a stronger safety guarantee.  A negative requirement uses the  REQUIRES
+attribute, in conjection with the ``!`` operator, to indicate that a capability
+should *not* be held.
+
+For example, using ``REQUIRES(!mu)`` instead of ``EXCLUDES(mu)`` will produce
+the appropriate warnings:
+
+.. code-block:: c++
+
+  class FooNeg {
+    Mutex mu;
+
+    void foo() REQUIRES(!mu) {   // foo() now requires !mu.
+      mu.Lock();
+      bar();
+      baz();
+      mu.Unlock();
+    }
+
+    void bar() {
+      mu.Lock();       // WARNING!  Missing REQUIRES(!mu).
+      // ...
+      mu.Unlock();
+    }
+
+    void baz() {
+      bif();           // WARNING!  Missing REQUIRES(!mu).
+    }
+
+    void bif() REQUIRES(!mu);
+  };
+
+
+Negative requirements are an experimental feature which is off by default,
+because it will produce many warnings in existing code.  It can be enabled
+by passing ``-Wthread-safety-negative``.
 
 
 .. _faq:
@@ -426,7 +547,10 @@ Frequently Asked Questions
 
 (Q) Should I put attributes in the header file, or in the .cc/.cpp/.cxx file?
 
-(A) Attributes should always go in the header.
+(A) Attributes are part of the formal interface of a function, and should
+always go in the header, where they are visible to anything that includes
+the header.  Attributes in the .cpp file are not visible outside of the
+immediate translation unit, which leads to false negatives and false positives.
 
 
 (Q) "*Mutex is not locked on every path through here?*"  What does that mean?
@@ -436,7 +560,7 @@ Frequently Asked Questions
 
 .. _limitations:
 
-Known Limitations 
+Known Limitations
 =================
 
 Lexical scope
@@ -448,14 +572,14 @@ capabilities must be declared before the
 Use-before-declaration is okay within a single class, because attributes are
 parsed at the same time as method bodies. (C++ delays parsing of method bodies
 until the end of the class.)  However, use-before-declaration is not allowed
-between classes, as illustrated below.  
+between classes, as illustrated below.
 
 .. code-block:: c++
 
   class Foo;
 
   class Bar {
-    void bar(Foo* f) EXCLUSIVE_LOCKS_REQUIRED(f->mu);  // Error: mu undeclared.
+    void bar(Foo* f) REQUIRES(f->mu);  // Error: mu undeclared.
   };
 
   class Foo {
@@ -474,9 +598,9 @@ Thread safety attributes follow normal C
 is a private member of ``c``, then it is an error to write ``c.mu`` in an
 attribute.
 
-One workround is to (ab)use the ``LOCK_RETURNED`` attribute to provide a public
-*name* for a private mutex, without actually exposing the underlying mutex.
-For example:
+One workround is to (ab)use the ``RETURN_CAPABILITY`` attribute to provide a
+public *name* for a private mutex, without actually exposing the underlying
+mutex.  For example:
 
 .. code-block:: c++
 
@@ -486,12 +610,12 @@ For example:
 
   public:
     // For thread safety analysis only.  Does not actually return mu.
-    Mutex* getMu() LOCK_RETURNED(mu) { return 0; }
+    Mutex* getMu() RETURN_CAPABILITY(mu) { return 0; }
 
-    void doSomething() EXCLUSIVE_LOCKS_REQUIRED(mu); 
+    void doSomething() REQUIRES(mu);
   };
 
-  void doSomethingTwice(MyClass& c) EXCLUSIVE_LOCKS_REQUIRED(c.getMu()) {
+  void doSomethingTwice(MyClass& c) REQUIRES(c.getMu()) {
     // The analysis thinks that c.getMu() == c.mu
     c.doSomething();
     c.doSomething();
@@ -506,43 +630,6 @@ as a fake getter method, which is provid
 safety analysis.
 
 
-False negatives on pass by reference.
--------------------------------------
-
-The current version of the analysis only checks operations which refer to
-guarded data members directly by name.  If the data members are accessed
-indirectly, via a pointer or reference, then no warning is generated.  Thus,
-no warnings will be generated for the following code:
-
-.. code-block:: c++
-
-  Mutex mu;
-  int a GUARDED_BY(mu);
-
-  void clear(int& ra) { ra = 0; }
-
-  void test() {
-    int *p = &a;
-    *p = 0;       // No warning.  *p is an alias to a.  
-       
-    clear(a);     // No warning.  'a' is passed by reference.
-  }
-
-This issue is by far the biggest source of false negatives in the current
-version of the analysis.  At a fundamental level, the
-false negatives are caused by the fact that annotations are attached to data
-members, rather than types.  The type of ``&a`` should really be
-``int GUARDED_BY(mu)*``, rather than ``int*``, and the statement ``p = &a``
-should thus generate a type error.  However, attaching attributes to types
-would be an invasive change to the C++ type system, with potential
-ramifications with respect to template instantation, function overloading,
-and so on.  Thus, a complete solution to this issue is simply not feasible.
-
-Future versions of the analysis will include better support for pointer
-alias analysis, along with limited checking of guarded types, in order to
-reduce the number of false negatives.
-
-
 .. _conditional_locks:
 
 No conditionally held locks.
@@ -557,7 +644,7 @@ generate spurious warnings (false positi
   void foo() {
     bool b = needsToLock();
     if (b) mu.Lock();
-    ...  // Warning!  Mutex 'mu' is not held on every path through here. 
+    ...  // Warning!  Mutex 'mu' is not held on every path through here.
     if (b) mu.Unlock();
   }
 
@@ -567,7 +654,7 @@ No checking inside constructors and dest
 
 The analysis currently does not do any checking inside constructors or
 destructors.  In other words, every constructor and destructor is treated as
-if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``.  
+if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``.
 The reason for this is that during initialization, only one thread typically
 has access to the object which is being initialized, and it is thus safe (and
 common practice) to initialize guarded members without acquiring any locks.
@@ -577,15 +664,15 @@ Ideally, the analysis would allow initia
 object being initialized or destroyed, while still enforcing the usual access
 restrictions on everything else.  However, this is difficult to enforce in
 practice, because in complex pointer-based data structures, it is hard to
-determine what data is "owned by" the enclosing object.
+determine what data is owned by the enclosing object.
 
 No inlining.
 ------------
 
 Thread safety analysis is strictly intra-procedural, just like ordinary type
 checking.  It relies only on the declared attributes of a function, and will
-not attempt to "step inside", or inline any method calls.  As a result, code
-such as the following will not work:
+not attempt to inline any method calls.  As a result, code such as the
+following will not work:
 
 .. code-block:: c++
 
@@ -593,7 +680,7 @@ such as the following will not work:
   class AutoCleanup {
     T* object;
     void (T::*mp)();
-    
+
   public:
     AutoCleanup(T* obj, void (T::*imp)()) : object(obj), mp(imp) { }
     ~AutoCleanup() { (object->*mp)(); }
@@ -602,8 +689,8 @@ such as the following will not work:
   Mutex mu;
   void foo() {
     mu.Lock();
-    AutoCleanup<Mutex>(&mu, &Mutex::Unlock); 
-    ...
+    AutoCleanup<Mutex>(&mu, &Mutex::Unlock);
+    // ...
   }  // Warning, mu is not unlocked.
 
 In this case, the destructor of ``Autocleanup`` calls ``mu.Unlock()``, so
@@ -611,42 +698,14 @@ the warning is bogus.  However,
 thread safety analysis cannot see the unlock, because it does not attempt to
 inline the destructor.  Moreover, there is no way to annotate the destructor,
 because the destructor is calling a function that is not statically known.
-This pattern is simply not supported. 
-
-
-LOCKS_EXCLUDED is not transitive.
----------------------------------
-
-A function which calls a method marked with LOCKS_EXCLUDED is not required to
-put LOCKS_EXCLUDED in its own interface.  LOCKS_EXCLUDED behaves differently
-from LOCKS_REQUIRED in this respect, and it can result in false negatives:
-
-.. code-block:: c++
-
-  class Foo {
-    Mutex mu;
-    
-    void foo() {
-      mu.Lock();
-      bar();                // No warning
-      mu.Unlock();
-    }
-    
-    void bar() { baz(); }   // No warning.  (Should have LOCKS_EXCLUDED(mu).)
-    
-    void baz() LOCKS_EXCLUDED(mu);
-  };
-
-The lack of transitivity is due to the fact that LOCKS_EXCLUDED can easily
-break encapsulation; it would be a bad idea to require functions to list the
-names private locks which happen to be acquired internally.  
+This pattern is simply not supported.
 
 
 No alias analysis.
 ------------------
 
 The analysis currently does not track pointer aliases.  Thus, there can be
-false positives if two pointers both point to the same mutex.  
+false positives if two pointers both point to the same mutex.
 
 
 .. code-block:: c++
@@ -655,13 +714,13 @@ false positives if two pointers both poi
     Mutex* mu;
 
   public:
-    MutexUnlocker(Mutex* m) UNLOCK_FUNCTION(m) : mu(m)  { mu->Unlock(); }
-    ~MutexUnlocker() EXCLUSIVE_LOCK_FUNCTION(mu) { mu->Lock(); }
+    MutexUnlocker(Mutex* m) RELEASE(m) : mu(m)  { mu->Unlock(); }
+    ~MutexUnlocker() ACQUIRE(mu) { mu->Lock(); }
   };
 
   Mutex mutex;
-  void test() EXCLUSIVE_LOCKS_REQUIRED(mutex) {
-    { 
+  void test() REQUIRES(mutex) {
+    {
       MutexUnlocker munl(&mutex);  // unlocks mutex
       doSomeIO();
     }                              // Warning: locks munl.mu
@@ -669,14 +728,14 @@ false positives if two pointers both poi
 
 The MutexUnlocker class is intended to be the dual of the MutexLocker class,
 defined in :ref:`mutexheader`.  However, it doesn't work because the analysis
-doesn't know that munl.mu == mutex.  The SCOPED_LOCKABLE attribute handles
-aliasing 
+doesn't know that munl.mu == mutex.  The SCOPED_CAPABILITY attribute handles
+aliasing for MutexLocker, but does so only for that particular pattern.
 
 
 ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) are currently unimplemented.
 -------------------------------------------------------------------------
 
-To be fixed in a future update. 
+To be fixed in a future update.
 
 
 .. _mutexheader:
@@ -688,14 +747,15 @@ Thread safety analysis can be used with
 require that the threading API be wrapped in classes and methods which have the
 appropriate annotations.  The following code provides ``mutex.h`` as an example;
 these methods should be filled in to call the appropriate underlying
-implementation. 
+implementation.
 
 
 .. code-block:: c++
 
+
   #ifndef THREAD_SAFETY_ANALYSIS_MUTEX_H
   #define THREAD_SAFETY_ANALYSIS_MUTEX_H
-  
+
   // Enable thread safety attributes only with clang.
   // The attributes can be safely erased when compiling with other compilers.
   #if defined(__clang__) && (!defined(SWIG))
@@ -703,116 +763,185 @@ implementation.
   #else
   #define THREAD_ANNOTATION_ATTRIBUTE__(x)   // no-op
   #endif
-  
+
   #define THREAD_ANNOTATION_ATTRIBUTE__(x)   __attribute__((x))
-  
+
+  #define CAPABILITY(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
+
+  #define SCOPED_CAPABILITY \
+    THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
+
   #define GUARDED_BY(x) \
     THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
-  
-  #define GUARDED_VAR \
-    THREAD_ANNOTATION_ATTRIBUTE__(guarded)
-  
+
   #define PT_GUARDED_BY(x) \
     THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
-  
-  #define PT_GUARDED_VAR \
-    THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded)
-  
-  #define ACQUIRED_AFTER(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
-  
+
   #define ACQUIRED_BEFORE(...) \
     THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
-  
-  #define EXCLUSIVE_LOCKS_REQUIRED(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
-  
-  #define SHARED_LOCKS_REQUIRED(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
-  
-  #define LOCKS_EXCLUDED(...) \
+
+  #define ACQUIRED_AFTER(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
+
+  #define REQUIRES(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
+
+  #define REQUIRES_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
+
+  #define ACQUIRE(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
+
+  #define ACQUIRE_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
+
+  #define RELEASE(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
+
+  #define RELEASE_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
+
+  #define TRY_ACQUIRE(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
+
+  #define TRY_ACQUIRE_SHARED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
+
+  #define EXCLUDES(...) \
     THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
-  
-  #define LOCK_RETURNED(x) \
+
+  #define ASSERT_CAPABILITY(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
+
+  #define ASSERT_SHARED_CAPABILITY(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
+
+  #define RETURN_CAPABILITY(x) \
     THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
-  
-  #define LOCKABLE \
-    THREAD_ANNOTATION_ATTRIBUTE__(lockable)
-  
-  #define SCOPED_LOCKABLE \
-    THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
-  
-  #define EXCLUSIVE_LOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
-  
-  #define SHARED_LOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
-  
-  #define ASSERT_EXCLUSIVE_LOCK(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__))
-  
-  #define ASSERT_SHARED_LOCK(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__))
-  
-  #define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
-  
-  #define SHARED_TRYLOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
-  
-  #define UNLOCK_FUNCTION(...) \
-    THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
-  
+
   #define NO_THREAD_SAFETY_ANALYSIS \
     THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
-  
-  
+
+
   // Defines an annotated interface for mutexes.
   // These methods can be implemented to use any internal mutex implementation.
-  class LOCKABLE Mutex {
+  class CAPABILITY("mutex") Mutex {
   public:
     // Acquire/lock this mutex exclusively.  Only one thread can have exclusive
     // access at any one time.  Write operations to guarded data require an
     // exclusive lock.
-    void Lock() EXCLUSIVE_LOCK_FUNCTION();
-  
+    void Lock() ACQUIRE();
+
     // Acquire/lock this mutex for read operations, which require only a shared
     // lock.  This assumes a multiple-reader, single writer semantics.  Multiple
-    // threads may acquire the mutex simultaneously as readers, but a writer must
-    // wait for all of them to release the mutex before it can acquire it
-    // exclusively.  
-    void ReaderLock() SHARED_LOCK_FUNCTION();
-  
-    // Release/unlock the mutex, regardless of whether it is exclusive or shared.
-    void Unlock() UNLOCK_FUNCTION();
-  
+    // threads may acquire the mutex simultaneously as readers, but a writer
+    // must wait for all of them to release the mutex before it can acquire it
+    // exclusively.
+    void ReaderLock() ACQUIRE_SHARED();
+
+    // Release/unlock an exclusive mutex.
+    void Unlock() RELEASE();
+
+    // Release/unlock a shared mutex.
+    void ReaderUnlock() RELEASE_SHARED();
+
     // Try to acquire the mutex.  Returns true on success, and false on failure.
-    bool TryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true);
-  
+    bool TryLock() TRY_ACQUIRE(true);
+
     // Try to acquire the mutex for read operations.
-    bool ReaderTryLock() SHARED_TRYLOCK_FUNCTION(true);
-  
+    bool ReaderTryLock() TRY_ACQUIRE_SHARED(true);
+
     // Assert that this mutex is currently held by the calling thread.
-    void AssertHeld() ASSERT_EXCLUSIVE_LOCK();
-  
-    // Assert that is mutex is currently held for read operations. 
-    void AssertReaderHeld() ASSERT_SHARED_LOCK();
+    void AssertHeld() ASSERT_CAPABILITY(this);
+
+    // Assert that is mutex is currently held for read operations.
+    void AssertReaderHeld() ASSERT_SHARED_CAPABILITY(this);
   };
-  
-  
+
+
   // MutexLocker is an RAII class that acquires a mutex in its constructor, and
-  // releases it in its destructor.  
-  class SCOPED_LOCKABLE MutexLocker {
+  // releases it in its destructor.
+  class SCOPED_CAPABILITY MutexLocker {
   private:
     Mutex* mut;
-  
+
   public:
-    MutexLocker(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mut(mu) {
+    MutexLocker(Mutex *mu) ACQUIRE(mu) : mut(mu) {
       mu->Lock();
-    }  
-    ~MutexLocker() UNLOCK_FUNCTION() {
+    }
+    ~MutexLocker() RELEASE() {
       mut->Unlock();
     }
   };
-  
+
+
+  #ifdef USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
+  // The original version of thread safety analysis the following attribute
+  // definitions.  These use a lock-based terminology.  They are still in use
+  // by existing thread safety code, and will continue to be supported.
+
+  // Deprecated.
+  #define PT_GUARDED_VAR \
+    THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded)
+
+  // Deprecated.
+  #define GUARDED_VAR \
+    THREAD_ANNOTATION_ATTRIBUTE__(guarded)
+
+  // Replaced by REQUIRES
+  #define EXCLUSIVE_LOCKS_REQUIRED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
+
+  // Replaced by REQUIRES_SHARED
+  #define SHARED_LOCKS_REQUIRED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
+
+  // Replaced by CAPABILITY
+  #define LOCKABLE \
+    THREAD_ANNOTATION_ATTRIBUTE__(lockable)
+
+  // Replaced by SCOPED_CAPABILITY
+  #define SCOPED_LOCKABLE \
+    THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
+
+  // Replaced by ACQUIRE
+  #define EXCLUSIVE_LOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
+
+  // Replaced by ACQUIRE_SHARED
+  #define SHARED_LOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
+
+  // Replaced by RELEASE and RELEASE_SHARED
+  #define UNLOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
+
+  // Replaced by TRY_ACQUIRE
+  #define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
+
+  // Replaced by TRY_ACQUIRE_SHARED
+  #define SHARED_TRYLOCK_FUNCTION(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
+
+  // Replaced by ASSERT_CAPABILITY
+  #define ASSERT_EXCLUSIVE_LOCK(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__))
+
+  // Replaced by ASSERT_SHARED_CAPABILITY
+  #define ASSERT_SHARED_LOCK(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__))
+
+  // Replaced by EXCLUDE_CAPABILITY.
+  #define LOCKS_EXCLUDED(...) \
+    THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
+
+  // Replaced by RETURN_CAPABILITY
+  #define LOCK_RETURNED(x) \
+    THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
+
+  #endif  // USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
+
   #endif  // THREAD_SAFETY_ANALYSIS_MUTEX_H
+





More information about the cfe-commits mailing list