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"
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
33using namespace clang;
34using namespace ento;
35
36namespace {
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.
43struct MethodFilter {
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)
52      return true;
53    return false;
54  }
55};
56
57static MethodFilter DefaultMethodFilter;
58
59class DirectIvarAssignment :
60  public Checker<check::ASTDecl<ObjCImplementationDecl> > {
61
62  typedef llvm::DenseMap<const ObjCIvarDecl*,
63                         const ObjCPropertyDecl*> IvarToPropertyMapTy;
64
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;
71    BugReporter &BR;
72    LocationOrAnalysisDeclContext DCtx;
73
74  public:
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) {}
79
80    void VisitStmt(const Stmt *S) { VisitChildren(S); }
81
82    void VisitBinaryOperator(const BinaryOperator *BO);
83
84    void VisitChildren(const Stmt *S) {
85      for (Stmt::const_child_range I = S->children(); I; ++I)
86        if (*I)
87         this->Visit(*I);
88    }
89  };
90
91public:
92  MethodFilter *ShouldSkipMethod;
93
94  DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
95
96  void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
97                    BugReporter &BR) const;
98};
99
100static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
101                                               const ObjCInterfaceDecl *InterD,
102                                               ASTContext &Ctx) {
103  // Check for synthesized ivars.
104  ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
105  if (ID)
106    return ID;
107
108  ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
109
110  // Check for existing "_PropName".
111  ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
112  if (ID)
113    return ID;
114
115  // Check for existing "PropName".
116  IdentifierInfo *PropIdent = PD->getIdentifier();
117  ID = NonConstInterD->lookupInstanceVariable(PropIdent);
118
119  return ID;
120}
121
122void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
123                                       AnalysisManager& Mgr,
124                                       BugReporter &BR) const {
125  const ObjCInterfaceDecl *InterD = D->getClassInterface();
126
127
128  IvarToPropertyMapTy IvarToPropMap;
129
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;
134
135    // Find the corresponding IVar.
136    const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
137                                                     Mgr.getASTContext());
138
139    if (!ID)
140      continue;
141
142    // Store the IVar to property mapping.
143    IvarToPropMap[ID] = PD;
144  }
145
146  if (IvarToPropMap.empty())
147    return;
148
149  for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
150      E = D->instmeth_end(); I != E; ++I) {
151
152    ObjCMethodDecl *M = *I;
153    AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
154
155    if ((*ShouldSkipMethod)(M))
156      continue;
157
158    const Stmt *Body = M->getBody();
159    assert(Body);
160
161    MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, DCtx);
162    MC.VisitStmt(Body);
163  }
164}
165
166static 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")
173      return true;
174  }
175  return false;
176}
177
178void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
179                                                    const BinaryOperator *BO) {
180  if (!BO->isAssignmentOp())
181    return;
182
183  const ObjCIvarRefExpr *IvarRef =
184          dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
185
186  if (!IvarRef)
187    return;
188
189  if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
190    IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
191
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))
200        return;
201
202      ObjCMethodDecl *GetterMethod =
203          InterfD->getInstanceMethod(PD->getGetterName());
204      ObjCMethodDecl *SetterMethod =
205          InterfD->getInstanceMethod(PD->getSetterName());
206
207      if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
208        return;
209
210      if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
211        return;
212
213      BR.EmitBasicReport(MD,
214          "Property access",
215          categories::CoreFoundationObjectiveC,
216          "Direct assignment to an instance variable backing a property; "
217          "use the setter instead", PathDiagnosticLocation(IvarRef,
218                                                          BR.getSourceManager(),
219                                                          DCtx));
220    }
221  }
222}
223}
224
225// Register the checker that checks for direct accesses in all functions,
226// except for the initialization and copy routines.
227void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
228  mgr.registerChecker<DirectIvarAssignment>();
229}
230
231// Register the checker that checks for direct accesses in functions annotated
232// with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
233namespace {
234struct 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")
242        return false;
243    }
244    return true;
245  }
246};
247
248InvalidatorMethodFilter AttrFilter;
249}
250
251void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
252    CheckerManager &mgr) {
253  mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
254}
255