1 //=- DirectIvarAssignment.cpp - Check rules on ObjC properties -*- C++ ----*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Check that Objective C properties are set with the setter, not though a
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")))
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.
22 //===----------------------------------------------------------------------===//
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"
33 using namespace clang;
38 /// The default method filter, which is used to filter out the methods on which
39 /// the check should not be performed.
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.
44 virtual ~MethodFilter() {}
45 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)
57 static MethodFilter DefaultMethodFilter;
59 class DirectIvarAssignment :
60 public Checker<check::ASTDecl<ObjCImplementationDecl> > {
62 typedef llvm::DenseMap<const ObjCIvarDecl*,
63 const ObjCPropertyDecl*> IvarToPropertyMapTy;
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;
72 LocationOrAnalysisDeclContext DCtx;
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) {}
80 void VisitStmt(const Stmt *S) { VisitChildren(S); }
82 void VisitBinaryOperator(const BinaryOperator *BO);
84 void VisitChildren(const Stmt *S) {
85 for (Stmt::const_child_range I = S->children(); I; ++I)
92 MethodFilter *ShouldSkipMethod;
94 DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
96 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
97 BugReporter &BR) const;
100 static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
101 const ObjCInterfaceDecl *InterD,
103 // Check for synthesized ivars.
104 ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
108 ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
110 // Check for existing "_PropName".
111 ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
115 // Check for existing "PropName".
116 IdentifierInfo *PropIdent = PD->getIdentifier();
117 ID = NonConstInterD->lookupInstanceVariable(PropIdent);
122 void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
123 AnalysisManager& Mgr,
124 BugReporter &BR) const {
125 const ObjCInterfaceDecl *InterD = D->getClassInterface();
128 IvarToPropertyMapTy IvarToPropMap;
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;
135 // Find the corresponding IVar.
136 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
137 Mgr.getASTContext());
142 // Store the IVar to property mapping.
143 IvarToPropMap[ID] = PD;
146 if (IvarToPropMap.empty())
149 for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
150 E = D->instmeth_end(); I != E; ++I) {
152 ObjCMethodDecl *M = *I;
153 AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
155 if ((*ShouldSkipMethod)(M))
158 const Stmt *Body = M->getBody();
161 MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, DCtx);
166 static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
167 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")
178 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
179 const BinaryOperator *BO) {
180 if (!BO->isAssignmentOp())
183 const ObjCIvarRefExpr *IvarRef =
184 dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
189 if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
190 IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
192 if (I != IvarToPropMap.end()) {
193 const ObjCPropertyDecl *PD = I->second;
194 // Skip warnings on Ivars, annotated with
195 // objc_allow_direct_instance_variable_assignment. This annotation serves
196 // 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))
202 ObjCMethodDecl *GetterMethod =
203 InterfD->getInstanceMethod(PD->getGetterName());
204 ObjCMethodDecl *SetterMethod =
205 InterfD->getInstanceMethod(PD->getSetterName());
207 if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
210 if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
213 BR.EmitBasicReport(MD,
215 categories::CoreFoundationObjectiveC,
216 "Direct assignment to an instance variable backing a property; "
217 "use the setter instead", PathDiagnosticLocation(IvarRef,
218 BR.getSourceManager(),
225 // Register the checker that checks for direct accesses in all functions,
226 // except for the initialization and copy routines.
227 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
228 mgr.registerChecker<DirectIvarAssignment>();
231 // Register the checker that checks for direct accesses in functions annotated
232 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
234 struct InvalidatorMethodFilter : MethodFilter {
235 virtual ~InvalidatorMethodFilter() {}
236 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;
241 if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
248 InvalidatorMethodFilter AttrFilter;
251 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
252 CheckerManager &mgr) {
253 mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;