blob: b43dc18c2179f2d0b21d45c3379ed570fa1e4652 [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.
Benjamin Kramera79a20e2013-08-09 17:17:42 +000043static 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}
Anna Zaks39a62fc2012-12-05 01:14:37 +000052
Anna Zaks88a83e32012-09-27 19:45:15 +000053class 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 LocationOrAnalysisDeclContext DCtx;
67
68 public:
69 MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
70 const ObjCInterfaceDecl *InID,
71 BugReporter &InBR, AnalysisDeclContext *InDCtx)
72 : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR), DCtx(InDCtx) {}
73
74 void VisitStmt(const Stmt *S) { VisitChildren(S); }
75
76 void VisitBinaryOperator(const BinaryOperator *BO);
77
78 void VisitChildren(const Stmt *S) {
79 for (Stmt::const_child_range I = S->children(); I; ++I)
80 if (*I)
81 this->Visit(*I);
82 }
83 };
84
85public:
Benjamin Kramera79a20e2013-08-09 17:17:42 +000086 bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
Anna Zaks39a62fc2012-12-05 01:14:37 +000087
88 DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
89
Anna Zaks88a83e32012-09-27 19:45:15 +000090 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
91 BugReporter &BR) const;
92};
93
94static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
Anna Zaksbf247922012-09-27 21:57:17 +000095 const ObjCInterfaceDecl *InterD,
96 ASTContext &Ctx) {
Anna Zaks88a83e32012-09-27 19:45:15 +000097 // Check for synthesized ivars.
98 ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
99 if (ID)
100 return ID;
101
Anna Zaksbf247922012-09-27 21:57:17 +0000102 ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
103
Anna Zaks88a83e32012-09-27 19:45:15 +0000104 // Check for existing "_PropName".
Anna Zaksbf247922012-09-27 21:57:17 +0000105 ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
Anna Zaks88a83e32012-09-27 19:45:15 +0000106 if (ID)
107 return ID;
108
109 // Check for existing "PropName".
110 IdentifierInfo *PropIdent = PD->getIdentifier();
Anna Zaksbf247922012-09-27 21:57:17 +0000111 ID = NonConstInterD->lookupInstanceVariable(PropIdent);
Anna Zaks88a83e32012-09-27 19:45:15 +0000112
113 return ID;
114}
115
116void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
117 AnalysisManager& Mgr,
118 BugReporter &BR) const {
119 const ObjCInterfaceDecl *InterD = D->getClassInterface();
120
121
122 IvarToPropertyMapTy IvarToPropMap;
123
124 // Find all properties for this class.
125 for (ObjCInterfaceDecl::prop_iterator I = InterD->prop_begin(),
126 E = InterD->prop_end(); I != E; ++I) {
127 ObjCPropertyDecl *PD = *I;
128
129 // Find the corresponding IVar.
Anna Zaksbf247922012-09-27 21:57:17 +0000130 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
131 Mgr.getASTContext());
Anna Zaks88a83e32012-09-27 19:45:15 +0000132
133 if (!ID)
134 continue;
135
136 // Store the IVar to property mapping.
137 IvarToPropMap[ID] = PD;
138 }
139
140 if (IvarToPropMap.empty())
141 return;
142
143 for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
144 E = D->instmeth_end(); I != E; ++I) {
145
146 ObjCMethodDecl *M = *I;
147 AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
148
Anna Zaks39a62fc2012-12-05 01:14:37 +0000149 if ((*ShouldSkipMethod)(M))
Anna Zaks88a83e32012-09-27 19:45:15 +0000150 continue;
151
152 const Stmt *Body = M->getBody();
Anna Zaksbf247922012-09-27 21:57:17 +0000153 assert(Body);
Anna Zaks88a83e32012-09-27 19:45:15 +0000154
155 MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, DCtx);
156 MC.VisitStmt(Body);
157 }
158}
159
Anna Zaksfa2b53c2013-01-17 23:24:58 +0000160static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
Anna Zaksd7b1d242013-01-16 01:36:00 +0000161 for (specific_attr_iterator<AnnotateAttr>
162 AI = D->specific_attr_begin<AnnotateAttr>(),
163 AE = D->specific_attr_end<AnnotateAttr>(); AI != AE; ++AI) {
164 const AnnotateAttr *Ann = *AI;
165 if (Ann->getAnnotation() ==
166 "objc_allow_direct_instance_variable_assignment")
167 return true;
168 }
169 return false;
170}
171
Anna Zaks88a83e32012-09-27 19:45:15 +0000172void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
173 const BinaryOperator *BO) {
174 if (!BO->isAssignmentOp())
175 return;
176
Anna Zaksbf247922012-09-27 21:57:17 +0000177 const ObjCIvarRefExpr *IvarRef =
178 dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
Anna Zaks88a83e32012-09-27 19:45:15 +0000179
180 if (!IvarRef)
181 return;
182
183 if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
184 IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
Anna Zaksd7b1d242013-01-16 01:36:00 +0000185
Anna Zaks88a83e32012-09-27 19:45:15 +0000186 if (I != IvarToPropMap.end()) {
187 const ObjCPropertyDecl *PD = I->second;
Anna Zaksfa2b53c2013-01-17 23:24:58 +0000188 // Skip warnings on Ivars, annotated with
Anna Zaksd7b1d242013-01-16 01:36:00 +0000189 // objc_allow_direct_instance_variable_assignment. This annotation serves
Anna Zaksfa2b53c2013-01-17 23:24:58 +0000190 // as a false positive suppression mechanism for the checker. The
191 // annotation is allowed on properties and ivars.
192 if (isAnnotatedToAllowDirectAssignment(PD) ||
193 isAnnotatedToAllowDirectAssignment(D))
Anna Zaksd7b1d242013-01-16 01:36:00 +0000194 return;
Anna Zaks88a83e32012-09-27 19:45:15 +0000195
196 ObjCMethodDecl *GetterMethod =
197 InterfD->getInstanceMethod(PD->getGetterName());
198 ObjCMethodDecl *SetterMethod =
199 InterfD->getInstanceMethod(PD->getSetterName());
200
201 if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
202 return;
203
204 if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
205 return;
206
Anna Zaks88a83e32012-09-27 19:45:15 +0000207 BR.EmitBasicReport(MD,
208 "Property access",
209 categories::CoreFoundationObjectiveC,
210 "Direct assignment to an instance variable backing a property; "
Anna Zaksbf247922012-09-27 21:57:17 +0000211 "use the setter instead", PathDiagnosticLocation(IvarRef,
212 BR.getSourceManager(),
213 DCtx));
Anna Zaks88a83e32012-09-27 19:45:15 +0000214 }
215 }
216}
217}
218
Anna Zaks39a62fc2012-12-05 01:14:37 +0000219// Register the checker that checks for direct accesses in all functions,
220// except for the initialization and copy routines.
Anna Zaks88a83e32012-09-27 19:45:15 +0000221void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
222 mgr.registerChecker<DirectIvarAssignment>();
223}
Anna Zaks39a62fc2012-12-05 01:14:37 +0000224
225// Register the checker that checks for direct accesses in functions annotated
Ted Kremeneka05d2742012-12-22 00:34:48 +0000226// with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
Benjamin Kramera79a20e2013-08-09 17:17:42 +0000227static bool AttrFilter(const ObjCMethodDecl *M) {
228 for (specific_attr_iterator<AnnotateAttr>
229 AI = M->specific_attr_begin<AnnotateAttr>(),
230 AE = M->specific_attr_end<AnnotateAttr>();
231 AI != AE; ++AI) {
232 const AnnotateAttr *Ann = *AI;
233 if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
234 return false;
Anna Zaks39a62fc2012-12-05 01:14:37 +0000235 }
Benjamin Kramera79a20e2013-08-09 17:17:42 +0000236 return true;
Anna Zaks39a62fc2012-12-05 01:14:37 +0000237}
238
239void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
240 CheckerManager &mgr) {
241 mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
242}