DirectIvarAssignment.cpp revision 39a62fcd3003785d9cc913ab2820be2f6f27bb40
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 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"
17#include "clang/AST/Attr.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
21#include "clang/StaticAnalyzer/Core/Checker.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
23#include "llvm/ADT/DenseMap.h"
24
25using namespace clang;
26using namespace ento;
27
28namespace {
29
30/// 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
50class 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:
83  MethodFilter *ShouldSkipMethod;
84
85  DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
86
87  void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
88                    BugReporter &BR) const;
89};
90
91static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
92                                               const ObjCInterfaceDecl *InterD,
93                                               ASTContext &Ctx) {
94  // Check for synthesized ivars.
95  ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
96  if (ID)
97    return ID;
98
99  ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
100
101  // Check for existing "_PropName".
102  ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
103  if (ID)
104    return ID;
105
106  // Check for existing "PropName".
107  IdentifierInfo *PropIdent = PD->getIdentifier();
108  ID = NonConstInterD->lookupInstanceVariable(PropIdent);
109
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.
127    const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
128                                                     Mgr.getASTContext());
129
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
146    if ((*ShouldSkipMethod)(M))
147      continue;
148
149    const Stmt *Body = M->getBody();
150    assert(Body);
151
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
162  const ObjCIvarRefExpr *IvarRef =
163          dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
164
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
184      BR.EmitBasicReport(MD,
185          "Property access",
186          categories::CoreFoundationObjectiveC,
187          "Direct assignment to an instance variable backing a property; "
188          "use the setter instead", PathDiagnosticLocation(IvarRef,
189                                                          BR.getSourceManager(),
190                                                          DCtx));
191    }
192  }
193}
194}
195
196// Register the checker that checks for direct accesses in all functions,
197// except for the initialization and copy routines.
198void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
199  mgr.registerChecker<DirectIvarAssignment>();
200}
201
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}
225