https://github.com/vtjnash updated https://github.com/llvm/llvm-project/pull/242937
>From 3f399189bb512d21738d9fbc8ec4d226397770d1 Mon Sep 17 00:00:00 2001 From: Jameson Nash <[email protected]> Date: Sun, 15 Nov 2026 16:00:27 -0500 Subject: [PATCH 1/2] [clang][Sema][ThreadSafety] Accept attributes without arguments meaning 'this' An attribute such as ACQUIRE or RELEASE without capability arguments is documented to refer to 'this': the analysis translates it to the self argument of the call (ThreadSafetyAnalyzer::getMutexIDs). But Sema accepts one only on a non-static method of a capability class, and elsewhere warns, even though it keeps the attribute. On a function pointer field, the meaning of such an attribute has slowly changed without being explicitly proposed. d1e84bb9ad3b (#191187) allowed these attributes on function pointer fields. A call through a field had no self argument then, so such an attribute on a field translated to no capability and was dropped. dfeadc6b0836 (#231602) made the base of the member access the self argument of a call through a field, so that the attribute could name a sibling member. As a side effect, an attribute without arguments on a field came to name that object, as it does on a method. For struct CAPABILITY("mutex") Node { void (*lock)(void) ACQUIRE(); }; `n->lock()` acquires 'n', while Sema still warns that the attribute applies only to methods. The two should agree. This change proposes keeping the analysis's meaning: on a field, an attribute without arguments refers to the object the field is called through. That is the documented rule for methods read with "the object called through" for 'this', so the documentation needs no change. It is also the only way to name that object from C, which has no 'this'. The analysis is unchanged: with the previous Sema check the new analysis tests pass, and only the -Wthread-safety-attributes warnings differ. Previously, it wasn't clear why this would be useful: https://github.com/llvm/llvm-project/issues/20777#issuecomment-1013343709 I've encountered a possible use: enforcing a constraint that isn't a real lock, so there's nothing to put in a member, but which would be useful to verify in this framework. What is new to permit that now is just in Sema: on a field, it accepts an attribute without arguments, and checks that the record the field is a member of is a capability, as it checks the class of a method. For a field of an anonymous struct or union, that is the anonymous record, which is also what 'this' names inside one in C++. The two diagnostics change so that the first names function pointer members and the second does not say 'this' for a field. The alternative is to restore the earlier behavior: add an exception to the analysis to ignore an attribute without arguments on a field, while keeping the Sema warning. The documentation would then need to say that an empty list means 'this' on a method but nothing on a function pointer field, and C code would still have no way to name the object. Assisted-by: Claude (Fable 5.1, Opus 5.5) --- .../clang/Basic/DiagnosticSemaKinds.td | 7 +-- clang/lib/Sema/SemaDeclAttr.cpp | 17 +++++-- clang/test/Sema/attr-capabilities.c | 36 +++++++++---- clang/test/Sema/warn-thread-safety-analysis.c | 13 +++++ .../SemaCXX/warn-thread-safety-analysis.cpp | 39 +++++++++++++++ .../SemaCXX/warn-thread-safety-parsing.cpp | 50 +++++++++++++------ 6 files changed, 130 insertions(+), 32 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index dff45a081f2e8c..d69b01a070c2e5 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -4375,11 +4375,12 @@ def warn_thread_attribute_ignored : Warning< InGroup<ThreadSafetyAttributes>, DefaultIgnore; def warn_thread_attribute_not_on_non_static_member : Warning< "%0 attribute without capability arguments can only be applied to non-static " - "methods of a class">, + "methods and function pointer members of a class">, InGroup<ThreadSafetyAttributes>, DefaultIgnore; def warn_thread_attribute_not_on_capability_member : Warning< - "%0 attribute without capability arguments refers to 'this', but %1 isn't " - "annotated with 'capability' or 'scoped_lockable' attribute">, + "%0 attribute without capability arguments refers to " + "%select{'this'|the object it is called through}2, but %1 isn't annotated " + "with 'capability' or 'scoped_lockable' attribute">, InGroup<ThreadSafetyAttributes>, DefaultIgnore; def warn_thread_attribute_argument_not_lockable : Warning< "%0 attribute requires arguments whose type is annotated " diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 0392c5067a1184..3aede092250dad 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -352,16 +352,23 @@ static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, if (Sidx == AL.getNumArgs()) { // If we don't have any capability arguments, the attribute implicitly // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're - // a non-static method, and that the class is a (scoped) capability. - const auto *MD = dyn_cast<const CXXMethodDecl>(D); - if (MD && !MD->isStatic()) { - const CXXRecordDecl *RD = MD->getParent(); + // a non-static method, and that the class is a (scoped) capability. A + // function pointer field is likewise called through an object, which the + // attribute then refers to. + const RecordDecl *RD = nullptr; + if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { + if (!MD->isStatic()) + RD = MD->getParent(); + } else if (const auto *FD = dyn_cast<FieldDecl>(D)) { + RD = FD->getParent(); + } + if (RD) { // FIXME -- need to check this again on template instantiation if (!checkRecordDeclForAttr<CapabilityAttr>(RD) && !checkRecordDeclForAttr<ScopedLockableAttr>(RD)) S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_capability_member) - << AL << MD->getParent(); + << AL << RD << isa<FieldDecl>(D); } else { S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member) << AL; diff --git a/clang/test/Sema/attr-capabilities.c b/clang/test/Sema/attr-capabilities.c index 6d594bca075350..9967a8c053042e 100644 --- a/clang/test/Sema/attr-capabilities.c +++ b/clang/test/Sema/attr-capabilities.c @@ -37,25 +37,25 @@ void Func6(void) __attribute__((requires_shared_capability(BadCapability))) {} void Func7(void) __attribute__((assert_capability(GUI))) {} void Func8(void) __attribute__((assert_shared_capability(GUI))) {} -void Func9(void) __attribute__((assert_capability())) {} // expected-warning {{'assert_capability' attribute without capability arguments can only be applied to non-static methods of a class}} -void Func10(void) __attribute__((assert_shared_capability())) {} // expected-warning {{'assert_shared_capability' attribute without capability arguments can only be applied to non-static methods of a class}} +void Func9(void) __attribute__((assert_capability())) {} // expected-warning {{'assert_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} +void Func10(void) __attribute__((assert_shared_capability())) {} // expected-warning {{'assert_shared_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} void Func11(void) __attribute__((acquire_capability(GUI))) {} void Func12(void) __attribute__((acquire_shared_capability(GUI))) {} -void Func13(void) __attribute__((acquire_capability())) {} // expected-warning {{'acquire_capability' attribute without capability arguments can only be applied to non-static methods of a class}} -void Func14(void) __attribute__((acquire_shared_capability())) {} // expected-warning {{'acquire_shared_capability' attribute without capability arguments can only be applied to non-static methods of a class}} +void Func13(void) __attribute__((acquire_capability())) {} // expected-warning {{'acquire_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} +void Func14(void) __attribute__((acquire_shared_capability())) {} // expected-warning {{'acquire_shared_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} void Func15(void) __attribute__((release_capability(GUI))) {} void Func16(void) __attribute__((release_shared_capability(GUI))) {} void Func17(void) __attribute__((release_generic_capability(GUI))) {} -void Func18(void) __attribute__((release_capability())) {} // expected-warning {{'release_capability' attribute without capability arguments can only be applied to non-static methods of a class}} -void Func19(void) __attribute__((release_shared_capability())) {} // expected-warning {{'release_shared_capability' attribute without capability arguments can only be applied to non-static methods of a class}} -void Func20(void) __attribute__((release_generic_capability())) {} // expected-warning {{'release_generic_capability' attribute without capability arguments can only be applied to non-static methods of a class}} +void Func18(void) __attribute__((release_capability())) {} // expected-warning {{'release_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} +void Func19(void) __attribute__((release_shared_capability())) {} // expected-warning {{'release_shared_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} +void Func20(void) __attribute__((release_generic_capability())) {} // expected-warning {{'release_generic_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} -void Func21(void) __attribute__((try_acquire_capability(1))) {} // expected-warning {{'try_acquire_capability' attribute without capability arguments can only be applied to non-static methods of a class}} -void Func22(void) __attribute__((try_acquire_shared_capability(1))) {} // expected-warning {{'try_acquire_shared_capability' attribute without capability arguments can only be applied to non-static methods of a class}} +void Func21(void) __attribute__((try_acquire_capability(1))) {} // expected-warning {{'try_acquire_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} +void Func22(void) __attribute__((try_acquire_shared_capability(1))) {} // expected-warning {{'try_acquire_shared_capability' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} void Func23(void) __attribute__((try_acquire_capability(1, GUI))) {} void Func24(void) __attribute__((try_acquire_shared_capability(1, GUI))) {} @@ -71,3 +71,21 @@ void Func30(void) __attribute__((requires_capability((Worker || Worker) && !GUI) int AlsoNotACapability; void Func31(void) __attribute__((requires_capability(GUI && AlsoNotACapability))); // expected-warning {{'requires_capability' attribute requires arguments whose type is annotated with 'capability' attribute; type here is 'int'}} + +// Without arguments, an attribute on a function pointer field refers to the +// object the field is called through, which must be a capability. +struct __attribute__((capability("mutex"))) FPCap { + void (*lock)(void) __attribute__((acquire_capability())); + void (*unlock)(void) __attribute__((release_capability())); +}; +struct FPNotCap { + void (*lock)(void) __attribute__((acquire_capability())); // expected-warning {{'acquire_capability' attribute without capability arguments refers to the object it is called through, but 'FPNotCap' isn't annotated with 'capability' or 'scoped_lockable' attribute}} +}; + +// A field of an anonymous struct or union is called through the anonymous +// object, which must be the capability, not the record it is in. +struct __attribute__((capability("mutex"))) FPAnonInCap { + struct { + void (*lock)(void) __attribute__((acquire_capability())); // expected-warning {{'acquire_capability' attribute without capability arguments refers to the object it is called through, but 'struct (unnamed at}} + }; +}; diff --git a/clang/test/Sema/warn-thread-safety-analysis.c b/clang/test/Sema/warn-thread-safety-analysis.c index 37dd29a659e977..7f482e1873d779 100644 --- a/clang/test/Sema/warn-thread-safety-analysis.c +++ b/clang/test/Sema/warn-thread-safety-analysis.c @@ -703,6 +703,19 @@ void late_param_other(void (*release)(struct Mutex *) UNLOCK_FUNCTION(mu), } // expected-warning {{expecting mutex 'mu' to be held at the end of function}} #endif +// Without arguments, an attribute on a function pointer field refers to the +// object the field is called through, as it refers to 'this' on a method. +struct LOCKABLE Node { + void (*lock)(void) EXCLUSIVE_LOCK_FUNCTION(); + void (*unlock)(void) UNLOCK_FUNCTION(); +}; + +void test_node(struct Node *n, struct Node *other) { + n->lock(); + other->unlock(); // expected-warning {{releasing mutex 'other' that was not held}} + n->unlock(); +} + // Test unusual trylock patterns void do_some_work(void); int work_data GUARDED_BY(mu1); diff --git a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp index afde78942be560..e7208d5ef10442 100644 --- a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp +++ b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp @@ -8518,6 +8518,45 @@ struct GuardedOpsSelf { } }; +// Without arguments, an attribute on a function pointer field refers to the +// object the field is called through, the object 'this' names in it. +struct LOCKABLE SelfOps { + void (*lock)() EXCLUSIVE_LOCK_FUNCTION(); + void (*unlock)() UNLOCK_FUNCTION(); + int data GUARDED_BY(this); + void self() { lock(); data = 1; unlock(); } + struct LOCKABLE { + void (*anonLock)() EXCLUSIVE_LOCK_FUNCTION(); + void (*anonUnlock)() UNLOCK_FUNCTION(); + int anonData GUARDED_BY(this); // the anonymous object, as for anonLock + }; +}; + +void requiresSelfOps(SelfOps *s) EXCLUSIVE_LOCKS_REQUIRED(s); + +void testSelfOps(SelfOps *s, SelfOps *o) { + s->lock(); + s->data = 1; + requiresSelfOps(s); + o->data = 1; // expected-warning {{writing variable 'data' requires holding mutex 'o' exclusively}} + s->unlock(); + s->anonLock(); + s->anonData = 1; + s->anonUnlock(); +} + +template <class F> struct LOCKABLE SelfOpsTemplate { + F lock EXCLUSIVE_LOCK_FUNCTION(); + F unlock UNLOCK_FUNCTION(); + int data GUARDED_BY(this); +}; + +void testSelfOpsTemplate(SelfOpsTemplate<void (*)()> *t) { + t->lock(); + t->data = 1; + t->unlock(); +} + } // namespace FunctionPointers namespace AnonymousMembers { diff --git a/clang/test/SemaCXX/warn-thread-safety-parsing.cpp b/clang/test/SemaCXX/warn-thread-safety-parsing.cpp index 70b3edf97e12f5..3d28a662814f81 100644 --- a/clang/test/SemaCXX/warn-thread-safety-parsing.cpp +++ b/clang/test/SemaCXX/warn-thread-safety-parsing.cpp @@ -588,11 +588,11 @@ UnlockableMu ab_var_arg_bad_5 ACQUIRED_BEFORE(mu_ab); // \ // takes zero or more arguments, all locks (vars/fields) -void elf_function() EXCLUSIVE_LOCK_FUNCTION(); // expected-warning {{'exclusive_lock_function' attribute without capability arguments can only be applied to non-static methods of a class}} +void elf_function() EXCLUSIVE_LOCK_FUNCTION(); // expected-warning {{'exclusive_lock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} void elf_function_args() EXCLUSIVE_LOCK_FUNCTION(mu1, mu2); -int elf_testfn(int y) EXCLUSIVE_LOCK_FUNCTION(); // expected-warning {{'exclusive_lock_function' attribute without capability arguments can only be applied to non-static methods of a class}} +int elf_testfn(int y) EXCLUSIVE_LOCK_FUNCTION(); // expected-warning {{'exclusive_lock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} int elf_testfn(int y) { int x EXCLUSIVE_LOCK_FUNCTION() = y; // \ @@ -619,7 +619,7 @@ void elf_fun_params1(MutexLock& scope EXCLUSIVE_LOCK_FUNCTION(mu1)); void elf_fun_params2(int lvar EXCLUSIVE_LOCK_FUNCTION(mu1)); // \ // expected-warning{{'exclusive_lock_function' attribute applies to function parameters only if their type is a function pointer or a reference to a 'scoped_lockable'-annotated type}} void elf_fun_params3(MutexLock& scope EXCLUSIVE_LOCK_FUNCTION()); // \ - // expected-warning{{'exclusive_lock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning{{'exclusive_lock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} // Check argument parsing. @@ -682,11 +682,11 @@ template int elf_variadic_template<Mutex, UnlockableMu>(Mutex&, UnlockableMu&); // takes zero or more arguments, all locks (vars/fields) -void slf_function() SHARED_LOCK_FUNCTION(); // expected-warning {{'shared_lock_function' attribute without capability arguments can only be applied to non-static methods of a class}} +void slf_function() SHARED_LOCK_FUNCTION(); // expected-warning {{'shared_lock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} void slf_function_args() SHARED_LOCK_FUNCTION(mu1, mu2); -int slf_testfn(int y) SHARED_LOCK_FUNCTION(); // expected-warning {{'shared_lock_function' attribute without capability arguments can only be applied to non-static methods of a class}} +int slf_testfn(int y) SHARED_LOCK_FUNCTION(); // expected-warning {{'shared_lock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} int slf_testfn(int y) { int x SHARED_LOCK_FUNCTION() = y; // \ @@ -701,7 +701,7 @@ void slf_fun_params1(MutexLock& scope SHARED_LOCK_FUNCTION(mu1)); void slf_fun_params2(int lvar SHARED_LOCK_FUNCTION(mu1)); // \ // expected-warning {{'shared_lock_function' attribute applies to function parameters only if their type is a function pointer or a reference to a 'scoped_lockable'-annotated type}} void slf_fun_params3(MutexLock& scope SHARED_LOCK_FUNCTION()); // \ - // expected-warning {{'shared_lock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'shared_lock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} class SlfFoo { private: @@ -783,10 +783,10 @@ void etf_function() __attribute__((exclusive_trylock_function)); // \ void etf_function_args() EXCLUSIVE_TRYLOCK_FUNCTION(1, mu2); void etf_function_arg() EXCLUSIVE_TRYLOCK_FUNCTION(1); // \ - // expected-warning {{'exclusive_trylock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'exclusive_trylock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} int etf_testfn(int y) EXCLUSIVE_TRYLOCK_FUNCTION(1); // \ - // expected-warning {{'exclusive_trylock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'exclusive_trylock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} int etf_testfn(int y) { int x EXCLUSIVE_TRYLOCK_FUNCTION(1) = y; // \ @@ -824,7 +824,7 @@ int etf_function_6() EXCLUSIVE_TRYLOCK_FUNCTION(1, muRef); int etf_function_7() EXCLUSIVE_TRYLOCK_FUNCTION(1, muDoubleWrapper.getWrapper()->getMu()); int etf_functetfn_8() EXCLUSIVE_TRYLOCK_FUNCTION(1, muPointer); int etf_function_9() EXCLUSIVE_TRYLOCK_FUNCTION(true); // \ - // expected-warning {{'exclusive_trylock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'exclusive_trylock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} // illegal attribute arguments @@ -878,10 +878,10 @@ void stf_function() __attribute__((shared_trylock_function)); // \ void stf_function_args() SHARED_TRYLOCK_FUNCTION(1, mu2); void stf_function_arg() SHARED_TRYLOCK_FUNCTION(1); // \ - // expected-warning {{'shared_trylock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'shared_trylock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} int stf_testfn(int y) SHARED_TRYLOCK_FUNCTION(1); // \ - // expected-warning {{'shared_trylock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'shared_trylock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} int stf_testfn(int y) { int x SHARED_TRYLOCK_FUNCTION(1) = y; // \ @@ -920,7 +920,7 @@ int stf_function_6() SHARED_TRYLOCK_FUNCTION(1, muRef); int stf_function_7() SHARED_TRYLOCK_FUNCTION(1, muDoubleWrapper.getWrapper()->getMu()); int stf_function_8() SHARED_TRYLOCK_FUNCTION(1, muPointer); int stf_function_9() SHARED_TRYLOCK_FUNCTION(true); // \ - // expected-warning {{'shared_trylock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'shared_trylock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} // illegal attribute arguments @@ -968,13 +968,13 @@ template int stf_variadic_template<Mutex, UnlockableMu>(Mutex&, UnlockableMu&); // takes zero or more arguments, all locks (vars/fields) void uf_function() UNLOCK_FUNCTION(); // \ - // expected-warning {{'unlock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'unlock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} void uf_function_args() UNLOCK_FUNCTION(mu1, mu2); int uf_testfn(int y) UNLOCK_FUNCTION(); //\ - // expected-warning {{'unlock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'unlock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} int uf_testfn(int y) { int x UNLOCK_FUNCTION() = y; // \ @@ -1001,7 +1001,7 @@ void uf_fun_params1(MutexLock& scope UNLOCK_FUNCTION(mu1)); void uf_fun_params2(int lvar UNLOCK_FUNCTION(mu1)); // \ // expected-warning {{'unlock_function' attribute applies to function parameters only if their type is a function pointer or a reference to a 'scoped_lockable'-annotated type}} void uf_fun_params3(MutexLock& scope UNLOCK_FUNCTION()); // \ - // expected-warning {{'unlock_function' attribute without capability arguments can only be applied to non-static methods of a class}} + // expected-warning {{'unlock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} // Check argument parsing. @@ -1800,6 +1800,26 @@ void fn_ref_param_requires(void (&rf)(void) EXCLUSIVE_LOCKS_REQUIRED(mu1)); Mutex &mu1_impl(void); Mutex &(&fn_ref_returned)(void) LOCK_RETURNED(mu1) = mu1_impl; +// Without arguments, an attribute on a field refers to the object the field is +// called through, as it refers to 'this' on a method. +struct LOCKABLE FPSelf { + void (*lock)(void) EXCLUSIVE_LOCK_FUNCTION(); + void (*unlock)(void) UNLOCK_FUNCTION(); +}; +struct FPNotLockable { + void (*lock)(void) EXCLUSIVE_LOCK_FUNCTION(); // \ + // expected-warning {{'exclusive_lock_function' attribute without capability arguments refers to the object it is called through, but 'FPNotLockable' isn't annotated with 'capability' or 'scoped_lockable' attribute}} +}; +// The record may be a capability through a base, as the class of a method may. +struct FPDerived : FPSelf { + void (*relock)(void) EXCLUSIVE_LOCK_FUNCTION(); +}; +// A static member is not called through an object. +struct LOCKABLE FPStatic { + static void (*lock)(void) EXCLUSIVE_LOCK_FUNCTION(); // \ + // expected-warning {{'exclusive_lock_function' attribute without capability arguments can only be applied to non-static methods and function pointer members of a class}} +}; + // lock_returned may name the pointee's parameters. struct MutexHolder { Mutex mu; >From 5de30dadb20cc0b58fcc0577b332ba1d6946bd7e Mon Sep 17 00:00:00 2001 From: Jameson Nash <[email protected]> Date: Sun, 15 Nov 2026 16:00:27 -0500 Subject: [PATCH 2/2] [clang][Sema][ThreadSafety] Accept attributes without arguments meaning 'this' An attribute such as ACQUIRE or RELEASE without capability arguments is documented to refer to 'this': the analysis translates it to the self argument of the call (ThreadSafetyAnalyzer::getMutexIDs). But Sema accepts one only on a non-static method of a capability class, and elsewhere warns, even though it keeps the attribute. On a function pointer field, the meaning of such an attribute has slowly changed without being explicitly proposed. d1e84bb9ad3b (#191187) allowed these attributes on function pointer fields. A call through a field had no self argument then, so such an attribute on a field translated to no capability and was dropped. dfeadc6b0836 (#231602) made the base of the member access the self argument of a call through a field, so that the attribute could name a sibling member. As a side effect, an attribute without arguments on a field came to name that object, as it does on a method. For struct CAPABILITY("mutex") Node { void (*lock)(void) ACQUIRE(); }; `n->lock()` acquires 'n', while Sema still warns that the attribute applies only to methods. The two should agree. This change proposes keeping the analysis's meaning: on a field, an attribute without arguments refers to the object the field is called through. That is the documented rule for methods read with "the object called through" for 'this', so the documentation needs no change. It is also the only way to name that object from C, which has no 'this'. The analysis is unchanged: with the previous Sema check the new analysis tests pass, and only the -Wthread-safety-attributes warnings differ. Previously, it wasn't clear why this would be useful: https://github.com/llvm/llvm-project/issues/20777#issuecomment-1013343709 I've encountered a possible use: enforcing a constraint that isn't a real lock, so there's nothing to put in a member, but which would be useful to verify in this framework. What is new to permit that now is just in Sema: on a field, it accepts an attribute without arguments, and checks that the record the field is a member of is a capability, as it checks the class of a method. For a field of an anonymous struct or union, that is the anonymous record, which is also what 'this' names inside one in C++. The two diagnostics change so that the first names function pointer members and the second does not say 'this' for a field. A field's attributes can be applied before the record's own attributes after its closing brace: always in C without late parsing, and for a C++11 attribute spelling in C++. So while the record is still being defined, a field isn't checked when its attribute is. Instead, ActOnFields checks the attributes already on the record's fields once it has applied the record's own. Late-parsed attributes come after that, on a complete record, and are checked as before. The alternative is to restore the earlier behavior: add an exception to the analysis to ignore an attribute without arguments on a field, while keeping the Sema warning. The documentation would then need to say that an empty list means 'this' on a method but nothing on a function pointer field, and C code would still have no way to name the object. Assisted-by: Claude (Fable 5.1, Opus 5.5) --- clang/include/clang/Sema/Sema.h | 6 ++++ clang/lib/Sema/SemaDecl.cpp | 1 + clang/lib/Sema/SemaDeclAttr.cpp | 30 +++++++++++++++++++ clang/test/Sema/attr-capabilities.c | 11 +++++-- .../SemaCXX/warn-thread-safety-parsing.cpp | 15 ++++++++-- 5 files changed, 57 insertions(+), 6 deletions(-) diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 0e5548e56f678a..3ef93647e64aaa 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -5331,6 +5331,12 @@ class Sema final : public SemaBase { bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); + /// Check that \p Record is a capability if a thread safety attribute without + /// capability arguments on one of its fields refers to it. Called once the + /// record's own attributes are applied; the attributes checked are those + /// already on its fields, which were applied before the record's. + void CheckFieldCapabilityAttrs(const RecordDecl *Record); + /// checkUnusedDeclAttributes - Given a declarator which is not being /// used to build a declaration, complain about any decl attributes /// which might be lying around on it. diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 5a70ab0162f14c..845950ae9e59d5 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -20591,6 +20591,7 @@ void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, // Handle attributes before checking the layout. ProcessDeclAttributeList(S, Record, Attrs); + CheckFieldCapabilityAttrs(Record); // Maybe randomize the record's decls. We automatically randomize a record // of function pointers, unless it has the "no_randomize_layout" attribute. diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 3aede092250dad..cd15d941eeecb7 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -361,6 +361,10 @@ static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, RD = MD->getParent(); } else if (const auto *FD = dyn_cast<FieldDecl>(D)) { RD = FD->getParent(); + // Attributes after the record's closing brace aren't applied yet. + // ActOnFields checks the field then (CheckFieldCapabilityAttrs). + if (RD && !RD->isCompleteDefinition()) + return; } if (RD) { // FIXME -- need to check this again on template instantiation @@ -523,6 +527,32 @@ bool Sema::checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A) { return checkThreadSafetyValueDeclIsFunPtr(*this, VD, *A); } +template <typename... AttrTypes> static bool isAttrWithoutArgs(const Attr *A) { + return (... || [A] { + const auto *TA = dyn_cast<AttrTypes>(A); + return TA && TA->args_size() == 0; + }()); +} + +void Sema::CheckFieldCapabilityAttrs(const RecordDecl *Record) { + std::optional<bool> IsCapability; + for (const FieldDecl *FD : Record->fields()) { + for (const Attr *A : FD->attrs()) { + // The attributes that may have no capability arguments. + if (!isAttrWithoutArgs<AcquireCapabilityAttr, ReleaseCapabilityAttr, + TryAcquireCapabilityAttr, AssertCapabilityAttr>(A)) + continue; + if (!IsCapability) + IsCapability = checkRecordDeclForAttr<CapabilityAttr>(Record) || + checkRecordDeclForAttr<ScopedLockableAttr>(Record); + if (!*IsCapability) + Diag(A->getLocation(), + diag::warn_thread_attribute_not_on_capability_member) + << A << Record << /*IsField=*/true; + } + } +} + //===----------------------------------------------------------------------===// // Attribute Implementations //===----------------------------------------------------------------------===// diff --git a/clang/test/Sema/attr-capabilities.c b/clang/test/Sema/attr-capabilities.c index 9967a8c053042e..a3b2d2db9271d9 100644 --- a/clang/test/Sema/attr-capabilities.c +++ b/clang/test/Sema/attr-capabilities.c @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -fsyntax-only -Wthread-safety -verify %s +// RUN: %clang_cc1 -fsyntax-only -Wthread-safety -verify -fexperimental-late-parse-attributes %s typedef int __attribute__((capability("role"))) ThreadRole; struct __attribute__((shared_capability("mutex"))) Mutex {}; @@ -73,13 +74,17 @@ int AlsoNotACapability; void Func31(void) __attribute__((requires_capability(GUI && AlsoNotACapability))); // expected-warning {{'requires_capability' attribute requires arguments whose type is annotated with 'capability' attribute; type here is 'int'}} // Without arguments, an attribute on a function pointer field refers to the -// object the field is called through, which must be a capability. -struct __attribute__((capability("mutex"))) FPCap { +// object the field is called through, which must be a capability. The record's +// own attributes may follow its closing brace, after the field's. +struct FPCap { void (*lock)(void) __attribute__((acquire_capability())); void (*unlock)(void) __attribute__((release_capability())); -}; +} __attribute__((capability("mutex"))); struct FPNotCap { void (*lock)(void) __attribute__((acquire_capability())); // expected-warning {{'acquire_capability' attribute without capability arguments refers to the object it is called through, but 'FPNotCap' isn't annotated with 'capability' or 'scoped_lockable' attribute}} + struct FPInnerCap { + void (*lock)(void) __attribute__((acquire_capability())); + } __attribute__((capability("mutex"))) inner; }; // A field of an anonymous struct or union is called through the anonymous diff --git a/clang/test/SemaCXX/warn-thread-safety-parsing.cpp b/clang/test/SemaCXX/warn-thread-safety-parsing.cpp index 3d28a662814f81..ea6c5931a12c1e 100644 --- a/clang/test/SemaCXX/warn-thread-safety-parsing.cpp +++ b/clang/test/SemaCXX/warn-thread-safety-parsing.cpp @@ -1801,14 +1801,23 @@ Mutex &mu1_impl(void); Mutex &(&fn_ref_returned)(void) LOCK_RETURNED(mu1) = mu1_impl; // Without arguments, an attribute on a field refers to the object the field is -// called through, as it refers to 'this' on a method. -struct LOCKABLE FPSelf { +// called through, as it refers to 'this' on a method. The class's own +// attributes may follow its closing brace: a field's GNU attributes are parsed +// after them, but C++11 ones are applied before. +struct FPSelf { void (*lock)(void) EXCLUSIVE_LOCK_FUNCTION(); void (*unlock)(void) UNLOCK_FUNCTION(); -}; +#if __cplusplus >= 201103 + [[clang::acquire_capability]] void (*lock11)(void); +#endif +} LOCKABLE; struct FPNotLockable { void (*lock)(void) EXCLUSIVE_LOCK_FUNCTION(); // \ // expected-warning {{'exclusive_lock_function' attribute without capability arguments refers to the object it is called through, but 'FPNotLockable' isn't annotated with 'capability' or 'scoped_lockable' attribute}} +#if __cplusplus >= 201103 + [[clang::acquire_capability]] void (*lock11)(void); // \ + // expected-warning {{'clang::acquire_capability' attribute without capability arguments refers to the object it is called through, but 'FPNotLockable' isn't annotated with 'capability' or 'scoped_lockable' attribute}} +#endif }; // The record may be a capability through a base, as the class of a method may. struct FPDerived : FPSelf { _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
