blob: f7535090bdf239224c8fa13ed0c26fb5e9323530 [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//
10// Check that Objective C properties follow the following rules:
11// - The property should be set with the setter, not though a direct
12// assignment.
13//
14//===----------------------------------------------------------------------===//
15
16#include "ClangSACheckers.h"
Anna Zaks39a62fc2012-12-05 01:14:37 +000017#include "clang/AST/Attr.h"
Anna Zaks88a83e32012-09-27 19:45:15 +000018#include "clang/AST/DeclObjC.h"
19#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
21#include "clang/StaticAnalyzer/Core/Checker.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
Anna Zaks88a83e32012-09-27 19:45:15 +000023#include "llvm/ADT/DenseMap.h"
24
25using namespace clang;
26using namespace ento;
27
28namespace {
29
Anna Zaks39a62fc2012-12-05 01:14:37 +000030/// The default method filter, which is used to filter out the methods on which
31/// the check should not be performed.
32///
33/// Checks for the init, dealloc, and any other functions that might be allowed
34/// to perform direct instance variable assignment based on their name.
35struct MethodFilter {
36 virtual bool operator()(ObjCMethodDecl *M) {
37 if (M->getMethodFamily() == OMF_init ||
38 M->getMethodFamily() == OMF_dealloc ||
39 M->getMethodFamily() == OMF_copy ||
40 M->getMethodFamily() == OMF_mutableCopy ||
41 M->getSelector().getNameForSlot(0).find("init") != StringRef::npos ||
42 M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos)
43 return true;
44 return false;
45 }
46};
47
48static MethodFilter DefaultMethodFilter;
49
Anna Zaks88a83e32012-09-27 19:45:15 +000050class DirectIvarAssignment :
51 public Checker<check::ASTDecl<ObjCImplementationDecl> > {
52
53 typedef llvm::DenseMap<const ObjCIvarDecl*,
54 const ObjCPropertyDecl*> IvarToPropertyMapTy;
55
56 /// A helper class, which walks the AST and locates all assignments to ivars
57 /// in the given function.
58 class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
59 const IvarToPropertyMapTy &IvarToPropMap;
60 const ObjCMethodDecl *MD;
61 const ObjCInterfaceDecl *InterfD;
62 BugReporter &BR;
63 LocationOrAnalysisDeclContext DCtx;
64
65 public:
66 MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
67 const ObjCInterfaceDecl *InID,
68 BugReporter &InBR, AnalysisDeclContext *InDCtx)
69 : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR), DCtx(InDCtx) {}
70
71 void VisitStmt(const Stmt *S) { VisitChildren(S); }
72
73 void VisitBinaryOperator(const BinaryOperator *BO);
74
75 void VisitChildren(const Stmt *S) {
76 for (Stmt::const_child_range I = S->children(); I; ++I)
77 if (*I)
78 this->Visit(*I);
79 }
80 };
81
82public:
Anna Zaks39a62fc2012-12-05 01:14:37 +000083 MethodFilter *ShouldSkipMethod;
84
85 DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
86
Anna Zaks88a83e32012-09-27 19:45:15 +000087 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
88 BugReporter &BR) const;
89};
90
91static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
Anna Zaksbf247922012-09-27 21:57:17 +000092 const ObjCInterfaceDecl *InterD,
93 ASTContext &Ctx) {
Anna Zaks88a83e32012-09-27 19:45:15 +000094 // Check for synthesized ivars.
95 ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
96 if (ID)
97 return ID;
98
Anna Zaksbf247922012-09-27 21:57:17 +000099 ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
100
Anna Zaks88a83e32012-09-27 19:45:15 +0000101 // Check for existing "_PropName".
Anna Zaksbf247922012-09-27 21:57:17 +0000102 ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
Anna Zaks88a83e32012-09-27 19:45:15 +0000103 if (ID)
104 return ID;
105
106 // Check for existing "PropName".
107 IdentifierInfo *PropIdent = PD->getIdentifier();
Anna Zaksbf247922012-09-27 21:57:17 +0000108 ID = NonConstInterD->lookupInstanceVariable(PropIdent);
Anna Zaks88a83e32012-09-27 19:45:15 +0000109
110 return ID;
111}
112
113void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
114 AnalysisManager& Mgr,
115 BugReporter &BR) const {
116 const ObjCInterfaceDecl *InterD = D->getClassInterface();
117
118
119 IvarToPropertyMapTy IvarToPropMap;
120
121 // Find all properties for this class.
122 for (ObjCInterfaceDecl::prop_iterator I = InterD->prop_begin(),
123 E = InterD->prop_end(); I != E; ++I) {
124 ObjCPropertyDecl *PD = *I;
125
126 // Find the corresponding IVar.
Anna Zaksbf247922012-09-27 21:57:17 +0000127 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
128 Mgr.getASTContext());
Anna Zaks88a83e32012-09-27 19:45:15 +0000129
130 if (!ID)
131 continue;
132
133 // Store the IVar to property mapping.
134 IvarToPropMap[ID] = PD;
135 }
136
137 if (IvarToPropMap.empty())
138 return;
139
140 for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
141 E = D->instmeth_end(); I != E; ++I) {
142
143 ObjCMethodDecl *M = *I;
144 AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
145
Anna Zaks39a62fc2012-12-05 01:14:37 +0000146 if ((*ShouldSkipMethod)(M))
Anna Zaks88a83e32012-09-27 19:45:15 +0000147 continue;
148
149 const Stmt *Body = M->getBody();
Anna Zaksbf247922012-09-27 21:57:17 +0000150 assert(Body);
Anna Zaks88a83e32012-09-27 19:45:15 +0000151
152 MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, DCtx);
153 MC.VisitStmt(Body);
154 }
155}
156
157void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
158 const BinaryOperator *BO) {
159 if (!BO->isAssignmentOp())
160 return;
161
Anna Zaksbf247922012-09-27 21:57:17 +0000162 const ObjCIvarRefExpr *IvarRef =
163 dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
Anna Zaks88a83e32012-09-27 19:45:15 +0000164
165 if (!IvarRef)
166 return;
167
168 if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
169 IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
170 if (I != IvarToPropMap.end()) {
171 const ObjCPropertyDecl *PD = I->second;
172
173 ObjCMethodDecl *GetterMethod =
174 InterfD->getInstanceMethod(PD->getGetterName());
175 ObjCMethodDecl *SetterMethod =
176 InterfD->getInstanceMethod(PD->getSetterName());
177
178 if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
179 return;
180
181 if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
182 return;
183
Anna Zaks88a83e32012-09-27 19:45:15 +0000184 BR.EmitBasicReport(MD,
185 "Property access",
186 categories::CoreFoundationObjectiveC,
187 "Direct assignment to an instance variable backing a property; "
Anna Zaksbf247922012-09-27 21:57:17 +0000188 "use the setter instead", PathDiagnosticLocation(IvarRef,
189 BR.getSourceManager(),
190 DCtx));
Anna Zaks88a83e32012-09-27 19:45:15 +0000191 }
192 }
193}
194}
195
Anna Zaks39a62fc2012-12-05 01:14:37 +0000196// Register the checker that checks for direct accesses in all functions,
197// except for the initialization and copy routines.
Anna Zaks88a83e32012-09-27 19:45:15 +0000198void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
199 mgr.registerChecker<DirectIvarAssignment>();
200}
Anna Zaks39a62fc2012-12-05 01:14:37 +0000201
202// Register the checker that checks for direct accesses in functions annotated
203// with __attribute__((annotate("objc_no_direct_instance_variable_assignmemt"))).
204namespace {
205struct InvalidatorMethodFilter : MethodFilter {
206 virtual bool operator()(ObjCMethodDecl *M) {
207 for (specific_attr_iterator<AnnotateAttr>
208 AI = M->specific_attr_begin<AnnotateAttr>(),
209 AE = M->specific_attr_end<AnnotateAttr>(); AI != AE; ++AI) {
210 const AnnotateAttr *Ann = *AI;
211 if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignmemt")
212 return false;
213 }
214 return true;
215 }
216};
217
218InvalidatorMethodFilter AttrFilter;
219}
220
221void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
222 CheckerManager &mgr) {
223 mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
224}