Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp
Line
Count
Source (jump to first uncovered line)
1
//=- DirectIvarAssignment.cpp - Check rules on ObjC properties -*- C++ ----*-==//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  Check that Objective C properties are set with the setter, not though a
10
//      direct assignment.
11
//
12
//  Two versions of a checker exist: one that checks all methods and the other
13
//      that only checks the methods annotated with
14
//      __attribute__((annotate("objc_no_direct_instance_variable_assignment")))
15
//
16
//  The checker does not warn about assignments to Ivars, annotated with
17
//       __attribute__((objc_allow_direct_instance_variable_assignment"))). This
18
//      annotation serves as a false positive suppression mechanism for the
19
//      checker. The annotation is allowed on properties and Ivars.
20
//
21
//===----------------------------------------------------------------------===//
22
23
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
24
#include "clang/AST/Attr.h"
25
#include "clang/AST/DeclObjC.h"
26
#include "clang/AST/StmtVisitor.h"
27
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
28
#include "clang/StaticAnalyzer/Core/Checker.h"
29
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
30
#include "llvm/ADT/DenseMap.h"
31
32
using namespace clang;
33
using namespace ento;
34
35
namespace {
36
37
/// The default method filter, which is used to filter out the methods on which
38
/// the check should not be performed.
39
///
40
/// Checks for the init, dealloc, and any other functions that might be allowed
41
/// to perform direct instance variable assignment based on their name.
42
7
static bool DefaultMethodFilter(const ObjCMethodDecl *M) {
43
7
  return M->getMethodFamily() == OMF_init ||
44
7
         
M->getMethodFamily() == OMF_dealloc6
||
45
7
         
M->getMethodFamily() == OMF_copy6
||
46
7
         
M->getMethodFamily() == OMF_mutableCopy5
||
47
7
         
M->getSelector().getNameForSlot(0).find("init") != StringRef::npos5
||
48
7
         
M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos5
;
49
7
}
50
51
class DirectIvarAssignment :
52
  public Checker<check::ASTDecl<ObjCImplementationDecl> > {
53
54
  typedef llvm::DenseMap<const ObjCIvarDecl*,
55
                         const ObjCPropertyDecl*> IvarToPropertyMapTy;
56
57
  /// A helper class, which walks the AST and locates all assignments to ivars
58
  /// in the given function.
59
  class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
60
    const IvarToPropertyMapTy &IvarToPropMap;
61
    const ObjCMethodDecl *MD;
62
    const ObjCInterfaceDecl *InterfD;
63
    BugReporter &BR;
64
    const CheckerBase *Checker;
65
    LocationOrAnalysisDeclContext DCtx;
66
67
  public:
68
    MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
69
                  const ObjCInterfaceDecl *InID, BugReporter &InBR,
70
                  const CheckerBase *Checker, AnalysisDeclContext *InDCtx)
71
        : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR),
72
5
          Checker(Checker), DCtx(InDCtx) {}
73
74
10
    void VisitStmt(const Stmt *S) { VisitChildren(S); }
75
76
    void VisitBinaryOperator(const BinaryOperator *BO);
77
78
10
    void VisitChildren(const Stmt *S) {
79
10
      for (const Stmt *Child : S->children())
80
19
        if (Child)
81
19
          this->Visit(Child);
82
10
    }
83
  };
84
85
public:
86
  bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
87
88
3
  DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
89
90
  void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
91
                    BugReporter &BR) const;
92
};
93
94
static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
95
                                               const ObjCInterfaceDecl *InterD,
96
12
                                               ASTContext &Ctx) {
97
12
  // Check for synthesized ivars.
98
12
  ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
99
12
  if (ID)
100
11
    return ID;
101
1
102
1
  ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
103
1
104
1
  // Check for existing "_PropName".
105
1
  ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
106
1
  if (ID)
107
1
    return ID;
108
0
109
0
  // Check for existing "PropName".
110
0
  IdentifierInfo *PropIdent = PD->getIdentifier();
111
0
  ID = NonConstInterD->lookupInstanceVariable(PropIdent);
112
0
113
0
  return ID;
114
0
}
115
116
void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
117
                                       AnalysisManager& Mgr,
118
2
                                       BugReporter &BR) const {
119
2
  const ObjCInterfaceDecl *InterD = D->getClassInterface();
120
2
121
2
122
2
  IvarToPropertyMapTy IvarToPropMap;
123
2
124
2
  // Find all properties for this class.
125
12
  for (const auto *PD : InterD->instance_properties()) {
126
12
    // Find the corresponding IVar.
127
12
    const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
128
12
                                                     Mgr.getASTContext());
129
12
130
12
    if (!ID)
131
0
      continue;
132
12
133
12
    // Store the IVar to property mapping.
134
12
    IvarToPropMap[ID] = PD;
135
12
  }
136
2
137
2
  if (IvarToPropMap.empty())
138
0
    return;
139
2
140
9
  
for (const auto *M : D->instance_methods())2
{
141
9
    AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
142
9
143
9
    if ((*ShouldSkipMethod)(M))
144
4
      continue;
145
5
146
5
    const Stmt *Body = M->getBody();
147
5
    assert(Body);
148
5
149
5
    MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
150
5
                     DCtx);
151
5
    MC.VisitStmt(Body);
152
5
  }
153
2
}
154
155
27
static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
156
27
  for (const auto *Ann : D->specific_attrs<AnnotateAttr>())
157
2
    if (Ann->getAnnotation() ==
158
2
        "objc_allow_direct_instance_variable_assignment")
159
2
      return true;
160
27
  
return false25
;
161
27
}
162
163
void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
164
14
                                                    const BinaryOperator *BO) {
165
14
  if (!BO->isAssignmentOp())
166
0
    return;
167
14
168
14
  const ObjCIvarRefExpr *IvarRef =
169
14
          dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
170
14
171
14
  if (!IvarRef)
172
0
    return;
173
14
174
14
  if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
175
14
    IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
176
14
177
14
    if (I != IvarToPropMap.end()) {
178
14
      const ObjCPropertyDecl *PD = I->second;
179
14
      // Skip warnings on Ivars, annotated with
180
14
      // objc_allow_direct_instance_variable_assignment. This annotation serves
181
14
      // as a false positive suppression mechanism for the checker. The
182
14
      // annotation is allowed on properties and ivars.
183
14
      if (isAnnotatedToAllowDirectAssignment(PD) ||
184
14
          
isAnnotatedToAllowDirectAssignment(D)13
)
185
2
        return;
186
12
187
12
      ObjCMethodDecl *GetterMethod =
188
12
          InterfD->getInstanceMethod(PD->getGetterName());
189
12
      ObjCMethodDecl *SetterMethod =
190
12
          InterfD->getInstanceMethod(PD->getSetterName());
191
12
192
12
      if (SetterMethod && 
SetterMethod->getCanonicalDecl() == MD10
)
193
2
        return;
194
10
195
10
      if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
196
0
        return;
197
10
198
10
      BR.EmitBasicReport(
199
10
          MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
200
10
          "Direct assignment to an instance variable backing a property; "
201
10
          "use the setter instead",
202
10
          PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
203
10
    }
204
14
  }
205
14
}
206
}
207
208
// Register the checker that checks for direct accesses in functions annotated
209
// with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
210
2
static bool AttrFilter(const ObjCMethodDecl *M) {
211
2
  for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
212
1
    if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
213
1
      return false;
214
2
  
return true1
;
215
2
}
216
217
// Register the checker that checks for direct accesses in all functions,
218
// except for the initialization and copy routines.
219
3
void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
220
3
  mgr.registerChecker<DirectIvarAssignment>();
221
3
}
222
223
2
bool ento::shouldRegisterDirectIvarAssignment(const LangOptions &LO) {
224
2
  return true;
225
2
}
226
227
void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
228
2
    CheckerManager &mgr) {
229
2
  mgr.getChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
230
2
}
231
232
bool ento::shouldRegisterDirectIvarAssignmentForAnnotatedFunctions(
233
2
                                                        const LangOptions &LO) {
234
2
  return true;
235
2
}