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.
43static 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
52class 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
86public:
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
95static 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
117void 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
156static 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
164void 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.
211void 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"))).
217static 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
224void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
225    CheckerManager &mgr) {
226  mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
227}
228