[clang] Thread Safety Analysis: Improved pointer handling (PR #127396)

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Tue Feb 25 08:18:13 PST 2025


================
@@ -6087,9 +6215,37 @@ class Return {
   const Foo &returns_constref_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
     return foo;
   }
+
+  Foo *returns_ptr_exclusive_locks_required() EXCLUSIVE_LOCKS_REQUIRED(mu) {
+    return &foo;
+  }
+
+  Foo *returns_pt_ptr_exclusive_locks_required() EXCLUSIVE_LOCKS_REQUIRED(mu) {
+    return foo_ptr;
+  }
+
+  Foo *returns_ptr_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+    return &foo;              // expected-warning {{returning pointer to variable 'foo' requires holding mutex 'mu' exclusively}}
+  }
+
+  Foo *returns_pt_ptr_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+    return foo_ptr;           // expected-warning {{returning pointer 'foo_ptr' requires holding mutex 'mu' exclusively}}
+  }
+
+  const Foo *returns_constptr_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+    return &foo;
+  }
+
+  const Foo *returns_pt_constptr_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+    return foo_ptr;
+  }
   
   Foo *returns_ptr() {
-    return &foo;              // FIXME -- Do we want to warn on this ?
+    return &foo;              // expected-warning {{returning pointer to variable 'foo' requires holding mutex 'mu' exclusively}}
+  }
+
+  Foo *returns_pt_ptr() {
----------------
ilya-biryukov wrote:

Could we also add the illustrative example that it does not do alias analysis?
```cpp
struct Foo {
  std::mutex mu;
  int *p GUARDED_BY(mu);

  int* do_something() {
    mu.lock();
    int* q = p;
    mu.unlock();
    return q;
  }
};
```

It could be useful for ramping up folks reading the test code on how far the analysis stretches, even if does not really test the bugs we catch.

https://github.com/llvm/llvm-project/pull/127396


More information about the cfe-commits mailing list