blob: 6d3dd1e42f02b87e13a63cd2bb02ab7138e14d69 [file] [log] [blame]
Anna Zaks88a83e32012-09-27 19:45:15 +00001//=- 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//
Anna Zaksfa2b53c2013-01-17 23:24:58 +000010// 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.
Anna Zaks88a83e32012-09-27 19:45:15 +000021//
22//===----------------------------------------------------------------------===//
23
24#include "ClangSACheckers.h"
Anna Zaks39a62fc2012-12-05 01:14:37 +000025#include "clang/AST/Attr.h"
Anna Zaks88a83e32012-09-27 19:45:15 +000026#include "clang/AST/DeclObjC.h"
27#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000028#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
29#include "clang/StaticAnalyzer/Core/Checker.h"
30#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
Anna Zaks88a83e32012-09-27 19:45:15 +000031#include "llvm/ADT/DenseMap.h"
32
33using namespace clang;
34using namespace ento;
35
36namespace {
37
Anna Zaks39a62fc2012-12-05 01:14:37 +000038/// 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.
43struct MethodFilter {
Daniel Jasperaacadfe2012-12-05 09:23:48 +000044 virtual ~MethodFilter() {}
Anna Zaks39a62fc2012-12-05 01:14:37 +000045 virtual bool operator()(ObjCMethodDecl *M) {
46 if (M->getMethodFamily() == OMF_init ||
47 M->getMethodFamily() == OMF_dealloc ||
48 M->getMethodFamily() == OMF_copy ||
49 M->getMethodFamily() == OMF_mutableCopy ||
50 M->getSelector().getNameForSlot(0).find("init") != StringRef::npos ||
51 M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos)
52 return true;
53 return false;
54 }
55};
56
57static MethodFilter DefaultMethodFilter;
58
Anna Zaks88a83e32012-09-27 19:45:15 +000059class DirectIvarAssignment :
60 public Checker<check::ASTDecl<ObjCImplementationDecl> > {
61
62 typedef llvm::DenseMap<const ObjCIvarDecl*,
63 const ObjCPropertyDecl*> IvarToPropertyMapTy;
64
65 /// A helper class, which walks the AST and locates all assignments to ivars
66 /// in the given function.
67 class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
68 const IvarToPropertyMapTy &IvarToPropMap;
69 const ObjCMethodDecl *MD;
70 const ObjCInterfaceDecl *InterfD;
71 BugReporter &BR;
72 LocationOrAnalysisDeclContext DCtx;
73
74 public:
75 MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
76 const ObjCInterfaceDecl *InID,
77 BugReporter &InBR, AnalysisDeclContext *InDCtx)
78 : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR), DCtx(InDCtx) {}
79
80 void VisitStmt(const Stmt *S) { VisitChildren(S); }
81
82 void VisitBinaryOperator(const BinaryOperator *BO);
83
84 void VisitChildren(const Stmt *S) {
85 for (Stmt::const_child_range I = S->children(); I; ++I)
86 if (*I)
87 this->Visit(*I);
88 }
89 };
90
91public:
Anna Zaks39a62fc2012-12-05 01:14:37 +000092 MethodFilter *ShouldSkipMethod;
93
94 DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
95
Anna Zaks88a83e32012-09-27 19:45:15 +000096 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
97 BugReporter &BR) const;
98};
99
100static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
Anna Zaksbf247922012-09-27 21:57:17 +0000101 const ObjCInterfaceDecl *InterD,
102 ASTContext &Ctx) {
Anna Zaks88a83e32012-09-27 19:45:15 +0000103 // Check for synthesized ivars.
104 ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
105 if (ID)
106 return ID;
107
Anna Zaksbf247922012-09-27 21:57:17 +0000108 ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
109
Anna Zaks88a83e32012-09-27 19:45:15 +0000110 // Check for existing "_PropName".
Anna Zaksbf247922012-09-27 21:57:17 +0000111 ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
Anna Zaks88a83e32012-09-27 19:45:15 +0000112 if (ID)
113 return ID;
114
115 // Check for existing "PropName".
116 IdentifierInfo *PropIdent = PD->getIdentifier();
Anna Zaksbf247922012-09-27 21:57:17 +0000117 ID = NonConstInterD->lookupInstanceVariable(PropIdent);
Anna Zaks88a83e32012-09-27 19:45:15 +0000118
119 return ID;
120}
121
122void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
123 AnalysisManager& Mgr,
124 BugReporter &BR) const {
125 const ObjCInterfaceDecl *InterD = D->getClassInterface();
126
127
128 IvarToPropertyMapTy IvarToPropMap;
129
130 // Find all properties for this class.
131 for (ObjCInterfaceDecl::prop_iterator I = InterD->prop_begin(),
132 E = InterD->prop_end(); I != E; ++I) {
133 ObjCPropertyDecl *PD = *I;
134
135 // Find the corresponding IVar.
Anna Zaksbf247922012-09-27 21:57:17 +0000136 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
137 Mgr.getASTContext());
Anna Zaks88a83e32012-09-27 19:45:15 +0000138
139 if (!ID)
140 continue;
141
142 // Store the IVar to property mapping.
143 IvarToPropMap[ID] = PD;
144 }
145
146 if (IvarToPropMap.empty())
147 return;
148
149 for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
150 E = D->instmeth_end(); I != E; ++I) {
151
152 ObjCMethodDecl *M = *I;
153 AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
154
Anna Zaks39a62fc2012-12-05 01:14:37 +0000155 if ((*ShouldSkipMethod)(M))
Anna Zaks88a83e32012-09-27 19:45:15 +0000156 continue;
157
158 const Stmt *Body = M->getBody();
Anna Zaksbf247922012-09-27 21:57:17 +0000159 assert(Body);
Anna Zaks88a83e32012-09-27 19:45:15 +0000160
161 MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, DCtx);
162 MC.VisitStmt(Body);
163 }
164}
165
Anna Zaksfa2b53c2013-01-17 23:24:58 +0000166static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
Anna Zaksd7b1d242013-01-16 01:36:00 +0000167 for (specific_attr_iterator<AnnotateAttr>
168 AI = D->specific_attr_begin<AnnotateAttr>(),
169 AE = D->specific_attr_end<AnnotateAttr>(); AI != AE; ++AI) {
170 const AnnotateAttr *Ann = *AI;
171 if (Ann->getAnnotation() ==
172 "objc_allow_direct_instance_variable_assignment")
173 return true;
174 }
175 return false;
176}
177
Anna Zaks88a83e32012-09-27 19:45:15 +0000178void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
179 const BinaryOperator *BO) {
180 if (!BO->isAssignmentOp())
181 return;
182
Anna Zaksbf247922012-09-27 21:57:17 +0000183 const ObjCIvarRefExpr *IvarRef =
184 dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
Anna Zaks88a83e32012-09-27 19:45:15 +0000185
186 if (!IvarRef)
187 return;
188
189 if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
190 IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
Anna Zaksd7b1d242013-01-16 01:36:00 +0000191
Anna Zaks88a83e32012-09-27 19:45:15 +0000192 if (I != IvarToPropMap.end()) {
193 const ObjCPropertyDecl *PD = I->second;
Anna Zaksfa2b53c2013-01-17 23:24:58 +0000194 // Skip warnings on Ivars, annotated with
Anna Zaksd7b1d242013-01-16 01:36:00 +0000195 // objc_allow_direct_instance_variable_assignment. This annotation serves
Anna Zaksfa2b53c2013-01-17 23:24:58 +0000196 // as a false positive suppression mechanism for the checker. The
197 // annotation is allowed on properties and ivars.
198 if (isAnnotatedToAllowDirectAssignment(PD) ||
199 isAnnotatedToAllowDirectAssignment(D))
Anna Zaksd7b1d242013-01-16 01:36:00 +0000200 return;
Anna Zaks88a83e32012-09-27 19:45:15 +0000201
202 ObjCMethodDecl *GetterMethod =
203 InterfD->getInstanceMethod(PD->getGetterName());
204 ObjCMethodDecl *SetterMethod =
205 InterfD->getInstanceMethod(PD->getSetterName());
206
207 if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
208 return;
209
210 if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
211 return;
212
Anna Zaks88a83e32012-09-27 19:45:15 +0000213 BR.EmitBasicReport(MD,
214 "Property access",
215 categories::CoreFoundationObjectiveC,
216 "Direct assignment to an instance variable backing a property; "
Anna Zaksbf247922012-09-27 21:57:17 +0000217 "use the setter instead", PathDiagnosticLocation(IvarRef,
218 BR.getSourceManager(),
219 DCtx));
Anna Zaks88a83e32012-09-27 19:45:15 +0000220 }
221 }
222}
223}
224
Anna Zaks39a62fc2012-12-05 01:14:37 +0000225// Register the checker that checks for direct accesses in all functions,
226// except for the initialization and copy routines.
Anna Zaks88a83e32012-09-27 19:45:15 +0000227void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
228 mgr.registerChecker<DirectIvarAssignment>();
229}
Anna Zaks39a62fc2012-12-05 01:14:37 +0000230
231// Register the checker that checks for direct accesses in functions annotated
Ted Kremeneka05d2742012-12-22 00:34:48 +0000232// with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
Anna Zaks39a62fc2012-12-05 01:14:37 +0000233namespace {
234struct InvalidatorMethodFilter : MethodFilter {
Daniel Jasperaacadfe2012-12-05 09:23:48 +0000235 virtual ~InvalidatorMethodFilter() {}
Anna Zaks39a62fc2012-12-05 01:14:37 +0000236 virtual bool operator()(ObjCMethodDecl *M) {
237 for (specific_attr_iterator<AnnotateAttr>
238 AI = M->specific_attr_begin<AnnotateAttr>(),
239 AE = M->specific_attr_end<AnnotateAttr>(); AI != AE; ++AI) {
240 const AnnotateAttr *Ann = *AI;
Ted Kremeneka05d2742012-12-22 00:34:48 +0000241 if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
Anna Zaks39a62fc2012-12-05 01:14:37 +0000242 return false;
243 }
244 return true;
245 }
246};
247
248InvalidatorMethodFilter AttrFilter;
249}
250
251void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
252 CheckerManager &mgr) {
253 mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
254}