clang  6.0.0svn
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 "ClangSACheckers.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/StmtVisitor.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 ||
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;
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()) {
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 }
const char *const CoreFoundationObjectiveC
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:192
Stmt - This represents one statement.
Definition: Stmt.h:66
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static bool AttrFilter(const ObjCMethodDecl *M)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3108
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
instprop_range instance_properties() const
Definition: DeclObjC.h:1021
One of these records is kept for each identifier that is lexed.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
AnalysisDeclContext contains the context data for the function or method under analysis.
instmeth_range instance_methods() const
Definition: DeclObjC.h:1072
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:943
child_range children()
Definition: Stmt.cpp:226
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2463
Represents an ObjC class declaration.
Definition: DeclObjC.h:1191
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:910
ASTContext & getASTContext() override
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:543
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
Selector getSetterName() const
Definition: DeclObjC.h:931
IdentifierInfo * getDefaultSynthIvarName(ASTContext &Ctx) const
Get the default name of the synthesized ivar.
Definition: DeclObjC.cpp:218
#define bool
Definition: stdbool.h:31
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:613
Selector getSelector() const
Definition: DeclObjC.h:359
llvm::PointerUnion< const LocationContext *, AnalysisDeclContext * > LocationOrAnalysisDeclContext
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:403
CHECKER * registerChecker()
Used to register checkers.
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges=None)
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition: DeclObjC.cpp:806
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:746
Expr * getLHS() const
Definition: Expr.h:3029
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2459
Dataflow Directional Tag Classes.
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2571
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:517
SourceManager & getSourceManager()
Definition: BugReporter.h:463
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1964
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:962
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1105
Selector getGetterName() const
Definition: DeclObjC.h:923