aboutsummaryrefslogtreecommitdiff
path: root/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
blob: b08a2fbcb2f9cdbd1883475ca63eb8a897a37cae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//=- IvarInvalidationChecker.cpp - -*- C++ ----*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This checker implements annotation driven invalidation checking. If a class
//  contains a method annotated with 'objc_instance_variable_invalidator',
//  - (void) foo
//           __attribute__((annotate("objc_instance_variable_invalidator")));
//  all the "ivalidatable" instance variables of this class should be
//  invalidated. We call an instance variable ivalidatable if it is an object of
//  a class which contains an invalidation method.
//
//  Note, this checker currently only checks if an ivar was accessed by the
//  method, we do not currently support any deeper invalidation checking.
//
//===----------------------------------------------------------------------===//

#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallString.h"

using namespace clang;
using namespace ento;

namespace {
class IvarInvalidationChecker :
  public Checker<check::ASTDecl<ObjCMethodDecl> > {

  typedef llvm::DenseMap<const ObjCIvarDecl*, bool> IvarSet;
  typedef llvm::DenseMap<const ObjCMethodDecl*,
                         const ObjCIvarDecl*> MethToIvarMapTy;
  typedef llvm::DenseMap<const ObjCPropertyDecl*,
                         const ObjCIvarDecl*> PropToIvarMapTy;

  /// Statement visitor, which walks the method body and flags the ivars
  /// referenced in it (either directly or via property).
  class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
    const ObjCInterfaceDecl *InterfD;

    /// The set of Ivars which need to be invalidated.
    IvarSet &IVars;

    /// Property setter to ivar mapping.
    MethToIvarMapTy &PropertySetterToIvarMap;

    // Property to ivar mapping.
    PropToIvarMapTy &PropertyToIvarMap;

  public:
    MethodCrawler(const ObjCInterfaceDecl *InID,
                  IvarSet &InIVars, MethToIvarMapTy &InPropertySetterToIvarMap,
                  PropToIvarMapTy &InPropertyToIvarMap)
    : InterfD(InID), IVars(InIVars),
      PropertySetterToIvarMap(InPropertySetterToIvarMap),
      PropertyToIvarMap(InPropertyToIvarMap) {}

    void VisitStmt(const Stmt *S) { VisitChildren(S); }

    void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *IvarRef);

    void VisitObjCMessageExpr(const ObjCMessageExpr *ME);

    void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *PA);

    void VisitChildren(const Stmt *S) {
      for (Stmt::const_child_range I = S->children(); I; ++I)
        if (*I)
          static_cast<MethodCrawler*>(this)->Visit(*I);
    }
  };

  /// Check if the any of the methods inside the interface are annotated with
  /// the invalidation annotation.
  bool containsInvalidationMethod(const ObjCContainerDecl *D) const;

  /// Given the property declaration, and the list of tracked ivars, finds
  /// the ivar backing the property when possible. Returns '0' when no such
  /// ivar could be found.
  static const ObjCIvarDecl *findPropertyBackingIvar(
      const ObjCPropertyDecl *Prop,
      const ObjCInterfaceDecl *InterfaceD,
      IvarSet TrackedIvars);

public:
  void checkASTDecl(const ObjCMethodDecl *D, AnalysisManager& Mgr,
                    BugReporter &BR) const;

};

bool isInvalidationMethod(const ObjCMethodDecl *M) {
  const AnnotateAttr *Ann = M->getAttr<AnnotateAttr>();
  if (!Ann)
    return false;
  if (Ann->getAnnotation() == "objc_instance_variable_invalidator")
    return true;
  return false;
}

bool IvarInvalidationChecker::containsInvalidationMethod (
    const ObjCContainerDecl *D) const {

  // TODO: Cache the results.

  if (!D)
    return false;

  // Check all methods.
  for (ObjCContainerDecl::method_iterator
      I = D->meth_begin(),
      E = D->meth_end(); I != E; ++I) {
      const ObjCMethodDecl *MDI = *I;
      if (isInvalidationMethod(MDI))
        return true;
  }

  // If interface, check all parent protocols and super.
  // TODO: Visit all categories in case the invalidation method is declared in
  // a category.
  if (const ObjCInterfaceDecl *InterfaceD = dyn_cast<ObjCInterfaceDecl>(D)) {
    for (ObjCInterfaceDecl::protocol_iterator
        I = InterfaceD->protocol_begin(),
        E = InterfaceD->protocol_end(); I != E; ++I) {
      if (containsInvalidationMethod(*I))
        return true;
    }
    return containsInvalidationMethod(InterfaceD->getSuperClass());
  }

  // If protocol, check all parent protocols.
  if (const ObjCProtocolDecl *ProtD = dyn_cast<ObjCProtocolDecl>(D)) {
    for (ObjCInterfaceDecl::protocol_iterator
        I = ProtD->protocol_begin(),
        E = ProtD->protocol_end(); I != E; ++I) {
      if (containsInvalidationMethod(*I))
        return true;
    }
    return false;
  }

  llvm_unreachable("One of the casts above should have succeeded.");
}

const ObjCIvarDecl *IvarInvalidationChecker::findPropertyBackingIvar(
                        const ObjCPropertyDecl *Prop,
                        const ObjCInterfaceDecl *InterfaceD,
                        IvarSet TrackedIvars) {
  const ObjCIvarDecl *IvarD = 0;

  // Lookup for the synthesized case.
  IvarD = Prop->getPropertyIvarDecl();
  if (IvarD)
    return IvarD;

  // Lookup IVars named "_PropName"or "PropName" among the tracked Ivars.
  StringRef PropName = Prop->getIdentifier()->getName();
  for (IvarSet::const_iterator I = TrackedIvars.begin(),
                               E = TrackedIvars.end(); I != E; ++I) {
    const ObjCIvarDecl *Iv = I->first;
    StringRef IvarName = Iv->getName();

    if (IvarName == PropName)
      return Iv;

    SmallString<128> PropNameWithUnderscore;
    {
      llvm::raw_svector_ostream os(PropNameWithUnderscore);
      os << '_' << PropName;
    }
    if (IvarName == PropNameWithUnderscore.str())
      return Iv;
  }

  // Note, this is a possible source of false positives. We could look at the
  // getter implementation to find the ivar when its name is not derived from
  // the property name.
  return 0;
}

void IvarInvalidationChecker::checkASTDecl(const ObjCMethodDecl *D,
                                          AnalysisManager& Mgr,
                                          BugReporter &BR) const {
  // We are only interested in checking the cleanup methods.
  if (!D->hasBody() || !isInvalidationMethod(D))
    return;

  // Collect all ivars that need cleanup.
  IvarSet Ivars;
  const ObjCInterfaceDecl *InterfaceD = D->getClassInterface();
  for (ObjCInterfaceDecl::ivar_iterator
      II = InterfaceD->ivar_begin(),
      IE = InterfaceD->ivar_end(); II != IE; ++II) {
    const ObjCIvarDecl *Iv = *II;
    QualType IvQTy = Iv->getType();
    const ObjCObjectPointerType *IvTy = IvQTy->getAs<ObjCObjectPointerType>();
    if (!IvTy)
      continue;
    const ObjCInterfaceDecl *IvInterf = IvTy->getObjectType()->getInterface();
    if (containsInvalidationMethod(IvInterf))
      Ivars[cast<ObjCIvarDecl>(Iv->getCanonicalDecl())] = false;
  }

  // Construct Property/Property Setter to Ivar maps to assist checking if an
  // ivar which is backing a property has been reset.
  MethToIvarMapTy PropSetterToIvarMap;
  PropToIvarMapTy PropertyToIvarMap;
  for (ObjCInterfaceDecl::prop_iterator
      I = InterfaceD->prop_begin(),
      E = InterfaceD->prop_end(); I != E; ++I) {
    const ObjCPropertyDecl *PD = *I;

    const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterfaceD, Ivars);
    if (!ID) {
      continue;
    }
    // Find the setter.
    const ObjCMethodDecl *SetterD = PD->getSetterMethodDecl();
    // If we don't know the setter, do not track this ivar.
    if (!SetterD) {
      Ivars[cast<ObjCIvarDecl>(ID->getCanonicalDecl())] = true;
      continue;
    }

    // Store the mappings.
    PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl());
    SetterD = cast<ObjCMethodDecl>(SetterD->getCanonicalDecl());
    PropertyToIvarMap[PD] = ID;
    PropSetterToIvarMap[SetterD] = ID;
  }


  // Check which ivars have been accessed by the method.
  // We assume that if ivar was at least accessed, it was not forgotten.
  MethodCrawler(InterfaceD, Ivars,
                PropSetterToIvarMap, PropertyToIvarMap).VisitStmt(D->getBody());

  // Warn on the ivars that were not accessed by the method.
  for (IvarSet::const_iterator I = Ivars.begin(), E = Ivars.end(); I != E; ++I){
    if (I->second == false) {
      const ObjCIvarDecl *IvarDecl = I->first;

      PathDiagnosticLocation IvarDecLocation =
          PathDiagnosticLocation::createBegin(IvarDecl, BR.getSourceManager());

      SmallString<128> sbuf;
      llvm::raw_svector_ostream os(sbuf);
      os << "Ivar needs to be invalidated in the '" <<
            D->getSelector().getAsString()<< "' method";

      BR.EmitBasicReport(IvarDecl