xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp (revision be22bcb180714600926d5247ad9439f75cfc49db)
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 (const auto *Ann : D->specific_attrs<AnnotateAttr>())
165     if (Ann->getAnnotation() ==
166         "objc_allow_direct_instance_variable_assignment")
167       return true;
168   return false;
169 }
170 
171 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
172                                                     const BinaryOperator *BO) {
173   if (!BO->isAssignmentOp())
174     return;
175 
176   const ObjCIvarRefExpr *IvarRef =
177           dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
178 
179   if (!IvarRef)
180     return;
181 
182   if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
183     IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
184 
185     if (I != IvarToPropMap.end()) {
186       const ObjCPropertyDecl *PD = I->second;
187       // Skip warnings on Ivars, annotated with
188       // objc_allow_direct_instance_variable_assignment. This annotation serves
189       // as a false positive suppression mechanism for the checker. The
190       // annotation is allowed on properties and ivars.
191       if (isAnnotatedToAllowDirectAssignment(PD) ||
192           isAnnotatedToAllowDirectAssignment(D))
193         return;
194 
195       ObjCMethodDecl *GetterMethod =
196           InterfD->getInstanceMethod(PD->getGetterName());
197       ObjCMethodDecl *SetterMethod =
198           InterfD->getInstanceMethod(PD->getSetterName());
199 
200       if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
201         return;
202 
203       if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
204         return;
205 
206       BR.EmitBasicReport(
207           MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
208           "Direct assignment to an instance variable backing a property; "
209           "use the setter instead",
210           PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
211     }
212   }
213 }
214 }
215 
216 // Register the checker that checks for direct accesses in all functions,
217 // except for the initialization and copy routines.
218 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
219   mgr.registerChecker<DirectIvarAssignment>();
220 }
221 
222 // Register the checker that checks for direct accesses in functions annotated
223 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
224 static bool AttrFilter(const ObjCMethodDecl *M) {
225   for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
226     if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
227       return false;
228   return true;
229 }
230 
231 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
232     CheckerManager &mgr) {
233   mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
234 }
235