https://github.com/geoffreygaren updated 
https://github.com/llvm/llvm-project/pull/244775

>From 20d9f03d82a8abc9cf1d9abedef253372cc579b4 Mon Sep 17 00:00:00 2001
From: Geoff Garen <[email protected]>
Date: Fri, 20 Nov 2026 16:40:13 -0800
Subject: [PATCH] [alpha.webkit.NoUnretainedMemberChecker] Flag direct writes
 to ivars of retaining synthesized properties without ARC

The checker lets the ivar behind a synthesized copy, retain, or strong property 
be a raw pointer,
because @synthesize can't use a RetainPtr ivar. Without ARC, though, only the 
synthesized setter
retains that ivar. A direct write bypasses the retain, and nothing flagged it.

Warn when such an ivar is assigned or has its address taken anywhere other than 
-dealloc. That
includes hand-written accessors, since a class that hand-writes its accessors 
can make the ivar a
RetainPtr. Ivars declared in the class's @interface are still flagged at their 
declarations, since
other translation units can write them.
---
 clang/docs/analyzer/checkers.md               | 16 +++
 .../WebKit/RawPtrRefMemberChecker.cpp         | 84 ++++++++++++++++
 .../unretained-ivar-writes-issue-context.mm   | 30 ++++++
 .../Checkers/WebKit/unretained-members-arc.mm | 20 ++++
 .../Checkers/WebKit/unretained-members.mm     | 97 +++++++++++++++++++
 5 files changed, 247 insertions(+)
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/unretained-ivar-writes-issue-context.mm

diff --git a/clang/docs/analyzer/checkers.md b/clang/docs/analyzer/checkers.md
index 0ea0b31c51927d..943c471038c38b 100644
--- a/clang/docs/analyzer/checkers.md
+++ b/clang/docs/analyzer/checkers.md
@@ -3906,6 +3906,22 @@ struct Foo {
 };
 ```
 
+Without ARC, the ivar of a synthesized `copy`, `retain`, or `strong` property 
may be a raw pointer, because `@synthesize` can't use a RetainPtr ivar. Only 
the synthesized setter retains it, so the checker warns about direct writes to 
that ivar anywhere other than `-dealloc`.
+
+```objc
+@interface Bar : NSObject
+@property (nonatomic, copy) NSString *name;
+@end
+
+@implementation Bar
+- (instancetype)initWithName:(NSString *)name {
+  self = [super init];
+  _name = [name copy]; // warn
+  return self;
+}
+@end
+```
+
 See [WebKit Guidelines for Safer C++ 
Programming](https://github.com/WebKit/WebKit/wiki/Safer-CPP-Guidelines) for 
details.
 
 #### alpha.webkit.UnretainedLambdaCapturesChecker
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp
index 8b0ac3e4f2177e..70285c0162d31d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefMemberChecker.cpp
@@ -12,13 +12,16 @@
 #include "RawPtrRefSafetyModel.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclObjC.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "llvm/Support/Casting.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include <optional>
 
 using namespace clang;
@@ -77,6 +80,27 @@ class RawPtrRefMemberChecker
         Checker->visitObjCDecl(CD);
         return true;
       }
+
+      const Decl *DeclWithIssue = nullptr;
+
+      bool TraverseDecl(const Decl *D) override {
+        llvm::SaveAndRestore SavedDecl(DeclWithIssue);
+        if (D && (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)))
+          DeclWithIssue = D;
+        return ConstDynamicRecursiveASTVisitor::TraverseDecl(D);
+      }
+
+      bool VisitBinaryOperator(const BinaryOperator *BO) override {
+        if (BO->isAssignmentOp())
+          Checker->visitIvarWrite(BO->getLHS(), BO, DeclWithIssue);
+        return true;
+      }
+
+      bool VisitUnaryOperator(const UnaryOperator *UO) override {
+        if (UO->getOpcode() == UO_AddrOf)
+          Checker->visitIvarWrite(UO->getSubExpr(), UO, DeclWithIssue);
+        return true;
+      }
     };
 
     LocalVisitor visitor(this);
@@ -229,6 +253,66 @@ class RawPtrRefMemberChecker
     return {IsUnsafePtr && *IsUnsafePtr && !HasSafeAttr, PropType};
   }
 
+  void visitIvarWrite(const Expr *Target, const Expr *Write,
+                      const Decl *DeclWithIssue) const {
+    if (!Model->retainTypeChecker())
+      return;
+    auto *Method = dyn_cast_or_null<ObjCMethodDecl>(DeclWithIssue);
+    if (Method && Method->isInstanceMethod() &&
+        Method->getMethodFamily() == OMF_dealloc)
+      return;
+    auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(Target->IgnoreParenImpCasts());
+    if (!IvarRef)
+      return;
+    if (BR->getSourceManager().isInSystemHeader(Write->getBeginLoc()))
+      return;
+    auto *Ivar = IvarRef->getDecl();
+    if (auto *PD = setterOwnedProperty(Ivar))
+      reportIvarWrite(Write, Ivar, PD, DeclWithIssue);
+  }
+
+  // Ivars declared in the primary @interface are flagged at their declaration
+  // instead, because other translation units can write them.
+  const ObjCPropertyDecl *setterOwnedProperty(const ObjCIvarDecl *Ivar) const {
+    auto *Interface = Ivar->getContainingInterface();
+    if (!Interface || Ivar->getDeclContext() == Interface)
+      return nullptr;
+    auto *Impl = Interface->getImplementation();
+    if (!Impl)
+      return nullptr;
+    auto *PID = Impl->FindPropertyImplIvarDecl(Ivar->getIdentifier());
+    if (!PID ||
+        PID->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
+      return nullptr;
+    auto *PD = PID->getPropertyDecl();
+    if (!PD || !PD->isRetaining() ||
+        (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak))
+      return nullptr;
+    auto IsUnsafePtr = isUnsafePtr(Ivar->getType());
+    if (!IsUnsafePtr || !*IsUnsafePtr)
+      return nullptr;
+    return PD;
+  }
+
+  void reportIvarWrite(const Expr *Write, const ObjCIvarDecl *Ivar,
+                       const ObjCPropertyDecl *PD,
+                       const Decl *DeclWithIssue) const {
+    SmallString<100> Buf;
+    llvm::raw_svector_ostream Os(Buf);
+    Os << "Instance variable ";
+    printQuotedName(Os, Ivar);
+    Os << " of retaining property ";
+    printQuotedName(Os, PD);
+    Os << " is written directly; assign through the property, or hand-write "
+          "the accessors and make the instance variable a RetainPtr";
+
+    PathDiagnosticLocation BSLoc(Write->getBeginLoc(), BR->getSourceManager());
+    auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
+    Report->addRange(Write->getSourceRange());
+    Report->setDeclWithIssue(DeclWithIssue);
+    BR->emitReport(std::move(Report));
+  }
+
   bool shouldSkipDecl(const RecordDecl *RD) const {
     if (!RD->isThisDeclarationADefinition())
       return true;
diff --git 
a/clang/test/Analysis/Checkers/WebKit/unretained-ivar-writes-issue-context.mm 
b/clang/test/Analysis/Checkers/WebKit/unretained-ivar-writes-issue-context.mm
new file mode 100644
index 00000000000000..a11c9e506044bc
--- /dev/null
+++ 
b/clang/test/Analysis/Checkers/WebKit/unretained-ivar-writes-issue-context.mm
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.NoUnretainedMemberChecker \
+// RUN:   -analyzer-output=plist -o %t.plist %s
+// RUN: FileCheck --input-file=%t.plist %s
+
+#include "objc-mock-types.h"
+
+@interface Writer : NSObject
+@property (nonatomic, copy) NSString *name;
+@end
+
+@implementation Writer
+- (void)first {
+  _name = nil;
+}
+
+- (void)second {
+  _name = nil;
+}
+
+static void writeFromFunction(Writer *other) {
+  other->_name = nil;
+}
+@end
+
+// CHECK:      <key>issue_context_kind</key><string>Objective-C method</string>
+// CHECK-NEXT: <key>issue_context</key><string>first</string>
+// CHECK:      <key>issue_context_kind</key><string>Objective-C method</string>
+// CHECK-NEXT: <key>issue_context</key><string>second</string>
+// CHECK:      <key>issue_context_kind</key><string>function</string>
+// CHECK-NEXT: <key>issue_context</key><string>writeFromFunction</string>
diff --git a/clang/test/Analysis/Checkers/WebKit/unretained-members-arc.mm 
b/clang/test/Analysis/Checkers/WebKit/unretained-members-arc.mm
index ca70b75fc75573..0646520c352ed2 100644
--- a/clang/test/Analysis/Checkers/WebKit/unretained-members-arc.mm
+++ b/clang/test/Analysis/Checkers/WebKit/unretained-members-arc.mm
@@ -127,3 +127,23 @@ - (NSString *)prop_string1 {
 @synthesize prop_string4;
 @synthesize prop_string5;
 @end
+
+
+void writeStrongStringOut(NSString * __strong *out);
+
+@interface IvarWritesARC : NSObject
+@property (nonatomic, copy) NSString *name;
+@property (nonatomic, readonly, strong) NSString *readonlyName;
+@property (nonatomic, strong) dispatch_queue_t queue;
+@end
+
+@implementation IvarWritesARC
+- (instancetype)initWithName:(NSString *)name {
+  self = [super init];
+  _name = name;
+  _readonlyName = name;
+  writeStrongStringOut(&_name);
+  _queue = dispatch_queue_create("q", nullptr);
+  return self;
+}
+@end
diff --git a/clang/test/Analysis/Checkers/WebKit/unretained-members.mm 
b/clang/test/Analysis/Checkers/WebKit/unretained-members.mm
index 51c9b7851d96d3..44212307daa7cf 100644
--- a/clang/test/Analysis/Checkers/WebKit/unretained-members.mm
+++ b/clang/test/Analysis/Checkers/WebKit/unretained-members.mm
@@ -196,3 +196,100 @@ - (dispatch_queue_t)dispatch {
   return nil;
 }
 @end
+
+
+@interface NSObject (IvarWritesDealloc)
+- (void)dealloc;
+@end
+
+void writeStringOut(NSString **out);
+
+@interface IvarWrites : NSObject {
+  NSString *_declaredInInterface;
+  // expected-warning@-1{{Instance variable '_declaredInInterface' (of 
'IvarWrites') is a raw pointer to RetainPtr-capable type 'NSString'}}
+}
+@property (nonatomic, copy) NSString *name;
+@property (nonatomic, readonly, retain) NSString *readonlyName;
+@property (nonatomic, copy) NSString *customSetter;
+@property (nonatomic, retain) NSString *lazy;
+@property (nonatomic, retain) dispatch_queue_t queue;
+@property (nonatomic, copy) NSString *declaredInImplementation;
+@property (nonatomic, copy) NSString *declaredInInterface;
+@property (nonatomic, assign) NSString *assigned;
+// expected-warning@-1{{Property 'assigned' (of 'IvarWrites') is a raw pointer 
to RetainPtr-capable type 'NSString'}}
+@end
+
+@interface IvarWrites () {
+  NSString *_declaredInExtension;
+}
+@property (nonatomic, copy) NSString *declaredInExtension;
+@end
+
+@implementation IvarWrites {
+  NSString *_declaredInImplementation;
+}
+@synthesize declaredInImplementation = _declaredInImplementation;
+@synthesize declaredInInterface = _declaredInInterface;
+@synthesize declaredInExtension = _declaredInExtension;
+@synthesize assigned = _assigned;
+
+- (instancetype)initWithName:(NSString *)name {
+  self = [super init];
+  _name = [name retain];
+  // expected-warning@-1{{Instance variable '_name' of retaining property 
'name' is written directly; assign through the property, or hand-write the 
accessors and make the instance variable a RetainPtr}}
+  _readonlyName = [name retain];
+  // expected-warning@-1{{Instance variable '_readonlyName' of retaining 
property 'readonlyName' is written directly}}
+  return self;
+}
+
+- (void)clear {
+  _name = nil;
+  // expected-warning@-1{{Instance variable '_name' of retaining property 
'name' is written directly}}
+  self->_name = nil;
+  // expected-warning@-1{{Instance variable '_name' of retaining property 
'name' is written directly}}
+  _queue = nil;
+  // expected-warning@-1{{Instance variable '_queue' of retaining property 
'queue' is written directly}}
+}
+
+- (void)fill {
+  writeStringOut(&_name);
+  // expected-warning@-1{{Instance variable '_name' of retaining property 
'name' is written directly}}
+}
+
+- (void)setCustomSetter:(NSString *)value {
+  [_customSetter release];
+  _customSetter = [value retain];
+  // expected-warning@-1{{Instance variable '_customSetter' of retaining 
property 'customSetter' is written directly}}
+}
+
+- (NSString *)lazy {
+  if (!_lazy)
+    _lazy = [[NSString alloc] init];
+    // expected-warning@-1{{Instance variable '_lazy' of retaining property 
'lazy' is written directly}}
+  return _lazy;
+}
+
+- (void)writeExplicitIvars {
+  _declaredInImplementation = nil;
+  // expected-warning@-1{{Instance variable '_declaredInImplementation' of 
retaining property 'declaredInImplementation' is written directly}}
+  _declaredInExtension = nil;
+  // expected-warning@-1{{Instance variable '_declaredInExtension' of 
retaining property 'declaredInExtension' is written directly}}
+  _declaredInInterface = nil;
+  _assigned = nil;
+}
+
+- (NSString *)read {
+  return _name;
+}
+
+- (void)dealloc {
+  [_name release];
+  _name = nil;
+  [super dealloc];
+}
+
+static void writeFromFunction(IvarWrites *other) {
+  other->_name = nil;
+  // expected-warning@-1{{Instance variable '_name' of retaining property 
'name' is written directly}}
+}
+@end

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to