clang  3.7.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 "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  if (M->getMethodFamily() == OMF_init || M->getMethodFamily() == OMF_dealloc ||
45  M->getMethodFamily() == OMF_copy ||
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 }
52 
53 class 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  const CheckerBase *Checker;
68 
69  public:
70  MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
71  const ObjCInterfaceDecl *InID, BugReporter &InBR,
72  const CheckerBase *Checker, AnalysisDeclContext *InDCtx)
73  : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR),
74  Checker(Checker), DCtx(InDCtx) {}
75 
76  void VisitStmt(const Stmt *S) { VisitChildren(S); }
77 
78  void VisitBinaryOperator(const BinaryOperator *BO);
79 
80  void VisitChildren(const Stmt *S) {
81  for (const Stmt *Child : S->children())
82  if (Child)
83  this->Visit(Child);
84  }
85  };
86 
87 public:
88  bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
89 
90  DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
91 
92  void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
93  BugReporter &BR) const;
94 };
95 
96 static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
97  const ObjCInterfaceDecl *InterD,
98  ASTContext &Ctx) {
99  // Check for synthesized ivars.
101  if (ID)
102  return ID;
103 
104  ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
105 
106  // Check for existing "_PropName".
107  ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
108  if (ID)
109  return ID;
110 
111  // Check for existing "PropName".
112  IdentifierInfo *PropIdent = PD->getIdentifier();
113  ID = NonConstInterD->lookupInstanceVariable(PropIdent);
114 
115  return ID;
116 }
117 
118 void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
119  AnalysisManager& Mgr,
120  BugReporter &BR) const {
121  const ObjCInterfaceDecl *InterD = D->getClassInterface();
122 
123 
124  IvarToPropertyMapTy IvarToPropMap;
125 
126  // Find all properties for this class.
127  for (const auto *PD : InterD->properties()) {
128  // Find the corresponding IVar.
129  const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
130  Mgr.getASTContext());
131 
132  if (!ID)
133  continue;
134 
135  // Store the IVar to property mapping.
136  IvarToPropMap[ID] = PD;
137  }
138 
139  if (IvarToPropMap.empty())
140  return;
141 
142  for (const auto *M : D->instance_methods()) {
144 
145  if ((*ShouldSkipMethod)(M))
146  continue;
147 
148  const Stmt *Body = M->getBody();
149  assert(Body);
150 
151  MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
152  DCtx);
153  MC.VisitStmt(Body);
154  }
155 }
156 
157 static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
158  for (const auto *Ann : D->specific_attrs<AnnotateAttr>())
159  if (Ann->getAnnotation() ==
160  "objc_allow_direct_instance_variable_assignment")
161  return true;
162  return false;
163 }
164 
165 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
166  const BinaryOperator *BO) {
167  if (!BO->isAssignmentOp())
168  return;
169 
170  const ObjCIvarRefExpr *IvarRef =
171  dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
172 
173  if (!IvarRef)
174  return;
175 
176  if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
177  IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
178 
179  if (I != IvarToPropMap.end()) {
180  const ObjCPropertyDecl *PD = I->second;
181  // Skip warnings on Ivars, annotated with
182  // objc_allow_direct_instance_variable_assignment. This annotation serves
183  // as a false positive suppression mechanism for the checker. The
184  // annotation is allowed on properties and ivars.
185  if (isAnnotatedToAllowDirectAssignment(PD) ||
186  isAnnotatedToAllowDirectAssignment(D))
187  return;
188 
189  ObjCMethodDecl *GetterMethod =
190  InterfD->getInstanceMethod(PD->getGetterName());
191  ObjCMethodDecl *SetterMethod =
192  InterfD->getInstanceMethod(PD->getSetterName());
193 
194  if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
195  return;
196 
197  if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
198  return;
199 
200  BR.EmitBasicReport(
201  MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
202  "Direct assignment to an instance variable backing a property; "
203  "use the setter instead",
204  PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
205  }
206  }
207 }
208 }
209 
210 // Register the checker that checks for direct accesses in all functions,
211 // except for the initialization and copy routines.
212 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
213  mgr.registerChecker<DirectIvarAssignment>();
214 }
215 
216 // Register the checker that checks for direct accesses in functions annotated
217 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
218 static bool AttrFilter(const ObjCMethodDecl *M) {
219  for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
220  if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
221  return false;
222  return true;
223 }
224 
225 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
226  CheckerManager &mgr) {
227  mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
228 }
const char *const CoreFoundationObjectiveC
IdentifierInfo * getIdentifier() const
Definition: Decl.h:163
static bool AttrFilter(const ObjCMethodDecl *M)
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3040
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
Expr * getLHS() const
Definition: Expr.h:2964
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:856
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2918
Selector getSetterName() const
Definition: DeclObjC.h:2578
Expr * IgnoreParenCasts() LLVM_READONLY
Definition: Expr.cpp:2439
Represents an ObjC class declaration.
Definition: DeclObjC.h:851
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:826
ASTContext & getASTContext() override
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:500
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
ID
Defines the set of possible language-specific address spaces.
Definition: AddressSpaces.h:27
#define bool
Definition: stdbool.h:31
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:538
llvm::PointerUnion< const LocationContext *, AnalysisDeclContext * > LocationOrAnalysisDeclContext
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)
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition: DeclObjC.cpp:731
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2093
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:2424
instmeth_range instance_methods() const
Definition: DeclObjC.h:742
prop_range properties() const
Definition: DeclObjC.h:714
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2598
Selector getGetterName() const
Definition: DeclObjC.h:2575
Selector getSelector() const
Definition: DeclObjC.h:328
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:474
SourceManager & getSourceManager()
Definition: BugReporter.h:448
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:470
IdentifierInfo * getDefaultSynthIvarName(ASTContext &Ctx) const
Get the default name of the synthesized ivar.
Definition: DeclObjC.cpp:174