clang 8.0.0

DirectIvarAssignment.cpp
Go to the documentation of this file.
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 "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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 return M->getMethodFamily() == OMF_init ||
45 M->getMethodFamily() == OMF_dealloc ||
46 M->getMethodFamily() == OMF_copy ||
47 M->getMethodFamily() == OMF_mutableCopy ||
48 M->getSelector().getNameForSlot(0).find("init") != StringRef::npos ||
49 M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos;
50 }
51
52 class DirectIvarAssignment :
53 public Checker<check::ASTDecl<ObjCImplementationDecl> > {
54
55 typedef llvm::DenseMap<const ObjCIvarDecl*,
56 const ObjCPropertyDecl*> IvarToPropertyMapTy;
57
58 /// A helper class, which walks the AST and locates all assignments to ivars
59 /// in the given function.
60 class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
61 const IvarToPropertyMapTy &IvarToPropMap;
62 const ObjCMethodDecl *MD;
63 const ObjCInterfaceDecl *InterfD;
64 BugReporter &BR;
65 const CheckerBase *Checker;
66 LocationOrAnalysisDeclContext DCtx;
67
68 public:
69 MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
70 const ObjCInterfaceDecl *InID, BugReporter &InBR,
71 const CheckerBase *Checker, AnalysisDeclContext *InDCtx)
72 : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR),
73 Checker(Checker), DCtx(InDCtx) {}
74
75 void VisitStmt(const Stmt *S) { VisitChildren(S); }
76
77 void VisitBinaryOperator(const BinaryOperator *BO);
78
79 void VisitChildren(const Stmt *S) {
80 for (const Stmt *Child : S->children())
81 if (Child)
82 this->Visit(Child);
83 }
84 };
85
86 public:
87 bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
88
89 DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
90
91 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
92 BugReporter &BR) const;
93 };
94
95 static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
96 const ObjCInterfaceDecl *InterD,
97 ASTContext &Ctx) {
98 // Check for synthesized ivars.
99 ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
100 if (ID)
101 return ID;
102
103 ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
104
105 // Check for existing "_PropName".
106 ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
107 if (ID)
108 return ID;
109
110 // Check for existing "PropName".
111 IdentifierInfo *PropIdent = PD->getIdentifier();
112 ID = NonConstInterD->lookupInstanceVariable(PropIdent);
113
114 return ID;
115 }
116
117 void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
118 AnalysisManager& Mgr,
119 BugReporter &BR) const {
120 const ObjCInterfaceDecl *InterD = D->getClassInterface();
121
122
123 IvarToPropertyMapTy IvarToPropMap;
124
125 // Find all properties for this class.
126 for (const auto *PD : InterD->instance_properties()) {
127 // Find the corresponding IVar.
128 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
129 Mgr.getASTContext());
130
131 if (!ID)
132 continue;
133
134 // Store the IVar to property mapping.
135 IvarToPropMap[ID] = PD;
136 }
137
138 if (IvarToPropMap.empty())
139 return;
140
141 for (const auto *M : D->instance_methods()) {
142 AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
143
144 if ((*ShouldSkipMethod)(M))
145 continue;
146
147 const Stmt *Body = M->getBody();
148 assert(Body);
149
150 MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
151 DCtx);
152 MC.VisitStmt(Body);
153 }
154 }
155
156 static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
157 for (const auto *Ann : D->specific_attrs<AnnotateAttr>())
158 if (Ann->getAnnotation() ==
159 "objc_allow_direct_instance_variable_assignment")
160 return true;
161 return false;
162 }
163
164 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
165 const BinaryOperator *BO) {
166 if (!BO->isAssignmentOp())
167 return;
168
169 const ObjCIvarRefExpr *IvarRef =
170 dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
171
172 if (!IvarRef)
173 return;
174
175 if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
176 IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
177
178 if (I != IvarToPropMap.end()) {
179 const ObjCPropertyDecl *PD = I->second;
180 // Skip warnings on Ivars, annotated with
181 // objc_allow_direct_instance_variable_assignment. This annotation serves
182 // as a false positive suppression mechanism for the checker. The
183 // annotation is allowed on properties and ivars.
184 if (isAnnotatedToAllowDirectAssignment(PD) ||
185 isAnnotatedToAllowDirectAssignment(D))
186 return;
187
188 ObjCMethodDecl *GetterMethod =
189 InterfD->getInstanceMethod(PD->getGetterName());
190 ObjCMethodDecl *SetterMethod =
191 InterfD->getInstanceMethod(PD->getSetterName());
192
193 if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
194 return;
195
196 if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
197 return;
198
199 BR.EmitBasicReport(
200 MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
201 "Direct assignment to an instance variable backing a property; "
202 "use the setter instead",
203 PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
204 }
205 }
206 }
207 }
208
209 // Register the checker that checks for direct accesses in all functions,
210 // except for the initialization and copy routines.
211 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
212 mgr.registerChecker<DirectIvarAssignment>();
213 }
214
215 // Register the checker that checks for direct accesses in functions annotated
216 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
217 static bool AttrFilter(const ObjCMethodDecl *M) {
218 for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
219 if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
220 return false;
221 return true;
222 }
223
224 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
225 CheckerManager &mgr) {
226 mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
227 }
clang::Builtin::ID
ID
Definition: Builtins.h:49
ento
clang::ento::categories::CoreFoundationObjectiveC
const char *const CoreFoundationObjectiveC
Definition: CommonBugCategories.cpp:15
clang::ConstStmtVisitor
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:193
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:66
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
AttrFilter
static bool AttrFilter(const ObjCMethodDecl *M)
Definition: DirectIvarAssignment.cpp:217
DeclObjC.h
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
clang::BinaryOperator::isAssignmentOp
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3410
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
clang::ObjCContainerDecl::instance_properties
instprop_range instance_properties() const
Definition: DeclObjC.h:1003
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:58
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
clang::AnalysisDeclContext
AnalysisDeclContext contains the context data for the function or method under analysis.
Definition: AnalysisDeclContext.h:70
clang::ObjCContainerDecl::instance_methods
instmeth_range instance_methods() const
Definition: DeclObjC.h:1054
Checker.h
clang::ObjCMethodDecl::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:986
clang::Stmt::children
child_range children()
Definition: Stmt.cpp:237
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3287
clang::Expr::IgnoreParenCasts
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2595
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
clang::ObjCMethodDecl::getCanonicalDecl
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:954
clang::ObjCIvarRefExpr::getDecl
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:543
BugReporter.h
clang::ObjCPropertyDecl::getSetterName
Selector getSetterName() const
Definition: DeclObjC.h:914
clang::ObjCPropertyDecl::getDefaultSynthIvarName
IdentifierInfo * getDefaultSynthIvarName(ASTContext &Ctx) const
Get the default name of the synthesized ivar.
Definition: DeclObjC.cpp:225
clang::OMF_copy
Definition: IdentifierTable.h:620
AnalysisManager.h
clang::OMF_dealloc
Definition: IdentifierTable.h:628
bool
#define bool
Definition: stdbool.h:31
clang::Selector::getNameForSlot
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Definition: IdentifierTable.cpp:436
clang::OMF_mutableCopy
Definition: IdentifierTable.h:622
clang::ObjCInterfaceDecl::lookupInstanceVariable
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:621
StmtVisitor.h
clang::ento::LocationOrAnalysisDeclContext
llvm::PointerUnion< const LocationContext *, AnalysisDeclContext * > LocationOrAnalysisDeclContext
Definition: PathDiagnostic.h:154
clang::ObjCMethodDecl::getSelector
Selector getSelector() const
Definition: DeclObjC.h:321
BuiltinCheckerRegistration.h
Attr.h
clang::Decl::getASTContext
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
clang::ObjCMethodDecl::getBody
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition: DeclObjC.cpp:852
clang::ObjCPropertyDecl
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3327
clang::ObjCImplDecl::getClassInterface
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2440
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:22
clang::ObjCImplementationDecl
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2552
clang::ObjCIvarRefExpr
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
clang::Decl::specific_attrs
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:513
clang::ObjCIvarDecl
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1945
clang::ObjCPropertyDecl::getPropertyIvarDecl
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:945
clang::OMF_init
Definition: IdentifierTable.h:621
clang::ObjCContainerDecl::getInstanceMethod
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1087
clang::ObjCPropertyDecl::getGetterName
Selector getGetterName() const
Definition: DeclObjC.h:906