xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp (revision 4aca9b1cd852fcf4e11fa7ff26b73df6fbef8a4c)
1 //=- DirectIvarAssignment.cpp - Check rules on ObjC properties -*- C++ ----*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Check that Objective C properties are set with the setter, not though a
11 //      direct assignment.
12 //
13 //  Two versions of a checker exist: one that checks all methods and the other
14 //      that only checks the methods annotated with
15 //      __attribute__((annotate("objc_no_direct_instance_variable_assignment")))
16 //
17 //  The checker does not warn about assignments to Ivars, annotated with
18 //       __attribute__((objc_allow_direct_instance_variable_assignment"))). This
19 //      annotation serves as a false positive suppression mechanism for the
20 //      checker. The annotation is allowed on properties and Ivars.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "ClangSACheckers.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
29 #include "clang/StaticAnalyzer/Core/Checker.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
31 #include "llvm/ADT/DenseMap.h"
32 
33 using namespace clang;
34 using namespace ento;
35 
36 namespace {
37 
38 /// The default method filter, which is used to filter out the methods on which
39 /// the check should not be performed.
40 ///
41 /// Checks for the init, dealloc, and any other functions that might be allowed
42 /// to perform direct instance variable assignment based on their name.
43 static bool DefaultMethodFilter(const ObjCMethodDecl *M) {
44   if (M->getMethodFamily() == OMF_init || M->getMethodFamily() == OMF_dealloc ||
45       M->getMethodFamily() == OMF_copy ||
46       M->getMethodFamily() == OMF_mutableCopy ||
47       M->getSelector().getNameForSlot(0).find("init") != StringRef::npos ||
48       M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos)
49     return true;
50   return false;
51 }
52 
53 class DirectIvarAssignment :
54   public Checker<check::ASTDecl<ObjCImplementationDecl> > {
55 
56   typedef llvm::DenseMap<const ObjCIvarDecl*,
57                          const ObjCPropertyDecl*> IvarToPropertyMapTy;
58 
59   /// A helper class, which walks the AST and locates all assignments to ivars
60   /// in the given function.
61   class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
62     const IvarToPropertyMapTy &IvarToPropMap;
63     const ObjCMethodDecl *MD;
64     const ObjCInterfaceDecl *InterfD;
65     BugReporter &BR;
66     const CheckerBase *Checker;
67     LocationOrAnalysisDeclContext DCtx;
68 
69   public:
70     MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
71                   const ObjCInterfaceDecl *InID, BugReporter &InBR,
72                   const CheckerBase *Checker, AnalysisDeclContext *InDCtx)
73         : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR),
74           Checker(Checker), DCtx(InDCtx) {}
75 
76     void VisitStmt(const Stmt *S) { VisitChildren(S); }
77 
78     void VisitBinaryOperator(const BinaryOperator *BO);
79 
80     void VisitChildren(const Stmt *S) {
81       for (Stmt::const_child_range I = S->children(); I; ++I)
82         if (*I)
83          this->Visit(*I);
84     }
85   };
86 
87 public:
88   bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
89 
90   DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
91 
92   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
93                     BugReporter &BR) const;
94 };
95 
96 static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
97                                                const ObjCInterfaceDecl *InterD,
98                                                ASTContext &Ctx) {
99   // Check for synthesized ivars.
100   ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
101   if (ID)
102     return ID;
103 
104   ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
105 
106   // Check for existing "_PropName".
107   ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
108   if (ID)
109     return ID;
110 
111   // Check for existing "PropName".
112   IdentifierInfo *PropIdent = PD->getIdentifier();
113   ID = NonConstInterD->lookupInstanceVariable(PropIdent);
114 
115   return ID;
116 }
117 
118 void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
119                                        AnalysisManager& Mgr,
120                                        BugReporter &BR) const {
121   const ObjCInterfaceDecl *InterD = D->getClassInterface();
122 
123 
124   IvarToPropertyMapTy IvarToPropMap;
125 
126   // Find all properties for this class.
127   for (ObjCInterfaceDecl::prop_iterator I = InterD->prop_begin(),
128       E = InterD->prop_end(); I != E; ++I) {
129     ObjCPropertyDecl *PD = *I;
130 
131     // Find the corresponding IVar.
132     const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
133                                                      Mgr.getASTContext());
134 
135     if (!ID)
136       continue;
137 
138     // Store the IVar to property mapping.
139     IvarToPropMap[ID] = PD;
140   }
141 
142   if (IvarToPropMap.empty())
143     return;
144 
145   for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
146       E = D->instmeth_end(); I != E; ++I) {
147 
148     ObjCMethodDecl *M = *I;
149     AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
150 
151     if ((*ShouldSkipMethod)(M))
152       continue;
153 
154     const Stmt *Body = M->getBody();
155     assert(Body);
156 
157     MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
158                      DCtx);
159     MC.VisitStmt(Body);
160   }
161 }
162 
163 static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
164   for (specific_attr_iterator<AnnotateAttr>
165        AI = D->specific_attr_begin<AnnotateAttr>(),
166        AE = D->specific_attr_end<AnnotateAttr>(); AI != AE; ++AI) {
167     const AnnotateAttr *Ann = *AI;
168     if (Ann->getAnnotation() ==
169         "objc_allow_direct_instance_variable_assignment")
170       return true;
171   }
172   return false;
173 }
174 
175 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
176                                                     const BinaryOperator *BO) {
177   if (!BO->isAssignmentOp())
178     return;
179 
180   const ObjCIvarRefExpr *IvarRef =
181           dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
182 
183   if (!IvarRef)
184     return;
185 
186   if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
187     IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
188 
189     if (I != IvarToPropMap.end()) {
190       const ObjCPropertyDecl *PD = I->second;
191       // Skip warnings on Ivars, annotated with
192       // objc_allow_direct_instance_variable_assignment. This annotation serves
193       // as a false positive suppression mechanism for the checker. The
194       // annotation is allowed on properties and ivars.
195       if (isAnnotatedToAllowDirectAssignment(PD) ||
196           isAnnotatedToAllowDirectAssignment(D))
197         return;
198 
199       ObjCMethodDecl *GetterMethod =
200           InterfD->getInstanceMethod(PD->getGetterName());
201       ObjCMethodDecl *SetterMethod =
202           InterfD->getInstanceMethod(PD->getSetterName());
203 
204       if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
205         return;
206 
207       if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
208         return;
209 
210       BR.EmitBasicReport(
211           MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
212           "Direct assignment to an instance variable backing a property; "
213           "use the setter instead",
214           PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
215     }
216   }
217 }
218 }
219 
220 // Register the checker that checks for direct accesses in all functions,
221 // except for the initialization and copy routines.
222 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
223   mgr.registerChecker<DirectIvarAssignment>();
224 }
225 
226 // Register the checker that checks for direct accesses in functions annotated
227 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
228 static bool AttrFilter(const ObjCMethodDecl *M) {
229   for (specific_attr_iterator<AnnotateAttr>
230            AI = M->specific_attr_begin<AnnotateAttr>(),
231            AE = M->specific_attr_end<AnnotateAttr>();
232        AI != AE; ++AI) {
233     const AnnotateAttr *Ann = *AI;
234     if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
235       return false;
236   }
237   return true;
238 }
239 
240 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
241     CheckerManager &mgr) {
242   mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
243 }
244