CheckObjCDealloc.cpp revision e289d81369914678db386f6aa86faf8f178e245d
1//==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- 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//  This file defines a CheckObjCDealloc, a checker that
11//  analyzes an Objective-C class's implementation to determine if it
12//  correctly implements -dealloc.
13//
14//===----------------------------------------------------------------------===//
15
16#include "ClangSACheckers.h"
17#include "clang/StaticAnalyzer/Core/Checker.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/Basic/LangOptions.h"
25#include "llvm/Support/raw_ostream.h"
26
27using namespace clang;
28using namespace ento;
29
30static bool scan_dealloc(Stmt *S, Selector Dealloc) {
31
32  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S))
33    if (ME->getSelector() == Dealloc) {
34      switch (ME->getReceiverKind()) {
35      case ObjCMessageExpr::Instance: return false;
36      case ObjCMessageExpr::SuperInstance: return true;
37      case ObjCMessageExpr::Class: break;
38      case ObjCMessageExpr::SuperClass: break;
39      }
40    }
41
42  // Recurse to children.
43
44  for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)
45    if (*I && scan_dealloc(*I, Dealloc))
46      return true;
47
48  return false;
49}
50
51static bool scan_ivar_release(Stmt *S, ObjCIvarDecl *ID,
52                              const ObjCPropertyDecl *PD,
53                              Selector Release,
54                              IdentifierInfo* SelfII,
55                              ASTContext &Ctx) {
56
57  // [mMyIvar release]
58  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S))
59    if (ME->getSelector() == Release)
60      if (ME->getInstanceReceiver())
61        if (Expr *Receiver = ME->getInstanceReceiver()->IgnoreParenCasts())
62          if (ObjCIvarRefExpr *E = dyn_cast<ObjCIvarRefExpr>(Receiver))
63            if (E->getDecl() == ID)
64              return true;
65
66  // [self setMyIvar:nil];
67  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S))
68    if (ME->getInstanceReceiver())
69      if (Expr *Receiver = ME->getInstanceReceiver()->IgnoreParenCasts())
70        if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(Receiver))
71          if (E->getDecl()->getIdentifier() == SelfII)
72            if (ME->getMethodDecl() == PD->getSetterMethodDecl() &&
73                ME->getNumArgs() == 1 &&
74                ME->getArg(0)->isNullPointerConstant(Ctx,
75                                              Expr::NPC_ValueDependentIsNull))
76              return true;
77
78  // self.myIvar = nil;
79  if (BinaryOperator* BO = dyn_cast<BinaryOperator>(S))
80    if (BO->isAssignmentOp())
81      if (ObjCPropertyRefExpr *PRE =
82           dyn_cast<ObjCPropertyRefExpr>(BO->getLHS()->IgnoreParenCasts()))
83        if (PRE->isExplicitProperty() && PRE->getExplicitProperty() == PD)
84            if (BO->getRHS()->isNullPointerConstant(Ctx,
85                                            Expr::NPC_ValueDependentIsNull)) {
86              // This is only a 'release' if the property kind is not
87              // 'assign'.
88              return PD->getSetterKind() != ObjCPropertyDecl::Assign;;
89            }
90
91  // Recurse to children.
92  for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)
93    if (*I && scan_ivar_release(*I, ID, PD, Release, SelfII, Ctx))
94      return true;
95
96  return false;
97}
98
99static void checkObjCDealloc(const ObjCImplementationDecl *D,
100                             const LangOptions& LOpts, BugReporter& BR) {
101
102  assert (LOpts.getGC() != LangOptions::GCOnly);
103
104  ASTContext &Ctx = BR.getContext();
105  const ObjCInterfaceDecl *ID = D->getClassInterface();
106
107  // Does the class contain any ivars that are pointers (or id<...>)?
108  // If not, skip the check entirely.
109  // NOTE: This is motivated by PR 2517:
110  //        http://llvm.org/bugs/show_bug.cgi?id=2517
111
112  bool containsPointerIvar = false;
113
114  for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end();
115       I!=E; ++I) {
116
117    ObjCIvarDecl *ID = *I;
118    QualType T = ID->getType();
119
120    if (!T->isObjCObjectPointerType() ||
121        ID->getAttr<IBOutletAttr>() || // Skip IBOutlets.
122        ID->getAttr<IBOutletCollectionAttr>()) // Skip IBOutletCollections.
123      continue;
124
125    containsPointerIvar = true;
126    break;
127  }
128
129  if (!containsPointerIvar)
130    return;
131
132  // Determine if the class subclasses NSObject.
133  IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
134  IdentifierInfo* SenTestCaseII = &Ctx.Idents.get("SenTestCase");
135
136
137  for ( ; ID ; ID = ID->getSuperClass()) {
138    IdentifierInfo *II = ID->getIdentifier();
139
140    if (II == NSObjectII)
141      break;
142
143    // FIXME: For now, ignore classes that subclass SenTestCase, as these don't
144    // need to implement -dealloc.  They implement tear down in another way,
145    // which we should try and catch later.
146    //  http://llvm.org/bugs/show_bug.cgi?id=3187
147    if (II == SenTestCaseII)
148      return;
149  }
150
151  if (!ID)
152    return;
153
154  // Get the "dealloc" selector.
155  IdentifierInfo* II = &Ctx.Idents.get("dealloc");
156  Selector S = Ctx.Selectors.getSelector(0, &II);
157  ObjCMethodDecl *MD = 0;
158
159  // Scan the instance methods for "dealloc".
160  for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
161       E = D->instmeth_end(); I!=E; ++I) {
162
163    if ((*I)->getSelector() == S) {
164      MD = *I;
165      break;
166    }
167  }
168
169  if (!MD) { // No dealloc found.
170
171    const char* name = LOpts.getGC() == LangOptions::NonGC
172                       ? "missing -dealloc"
173                       : "missing -dealloc (Hybrid MM, non-GC)";
174
175    std::string buf;
176    llvm::raw_string_ostream os(buf);
177    os << "Objective-C class '" << D << "' lacks a 'dealloc' instance method";
178
179    BR.EmitBasicReport(name, os.str(), D->getLocStart());
180    return;
181  }
182
183  // dealloc found.  Scan for missing [super dealloc].
184  if (MD->getBody() && !scan_dealloc(MD->getBody(), S)) {
185
186    const char* name = LOpts.getGC() == LangOptions::NonGC
187                       ? "missing [super dealloc]"
188                       : "missing [super dealloc] (Hybrid MM, non-GC)";
189
190    std::string buf;
191    llvm::raw_string_ostream os(buf);
192    os << "The 'dealloc' instance method in Objective-C class '" << D
193       << "' does not send a 'dealloc' message to its super class"
194           " (missing [super dealloc])";
195
196    BR.EmitBasicReport(name, os.str(), D->getLocStart());
197    return;
198  }
199
200  // Get the "release" selector.
201  IdentifierInfo* RII = &Ctx.Idents.get("release");
202  Selector RS = Ctx.Selectors.getSelector(0, &RII);
203
204  // Get the "self" identifier
205  IdentifierInfo* SelfII = &Ctx.Idents.get("self");
206
207  // Scan for missing and extra releases of ivars used by implementations
208  // of synthesized properties
209  for (ObjCImplementationDecl::propimpl_iterator I = D->propimpl_begin(),
210       E = D->propimpl_end(); I!=E; ++I) {
211
212    // We can only check the synthesized properties
213    if ((*I)->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
214      continue;
215
216    ObjCIvarDecl *ID = (*I)->getPropertyIvarDecl();
217    if (!ID)
218      continue;
219
220    QualType T = ID->getType();
221    if (!T->isObjCObjectPointerType()) // Skip non-pointer ivars
222      continue;
223
224    const ObjCPropertyDecl *PD = (*I)->getPropertyDecl();
225    if (!PD)
226      continue;
227
228    // ivars cannot be set via read-only properties, so we'll skip them
229    if (PD->isReadOnly())
230       continue;
231
232    // ivar must be released if and only if the kind of setter was not 'assign'
233    bool requiresRelease = PD->getSetterKind() != ObjCPropertyDecl::Assign;
234    if (scan_ivar_release(MD->getBody(), ID, PD, RS, SelfII, Ctx)
235       != requiresRelease) {
236      const char *name;
237      const char* category = "Memory (Core Foundation/Objective-C)";
238
239      std::string buf;
240      llvm::raw_string_ostream os(buf);
241
242      if (requiresRelease) {
243        name = LOpts.getGC() == LangOptions::NonGC
244               ? "missing ivar release (leak)"
245               : "missing ivar release (Hybrid MM, non-GC)";
246
247        os << "The '" << ID
248           << "' instance variable was retained by a synthesized property but "
249              "wasn't released in 'dealloc'";
250      } else {
251        name = LOpts.getGC() == LangOptions::NonGC
252               ? "extra ivar release (use-after-release)"
253               : "extra ivar release (Hybrid MM, non-GC)";
254
255        os << "The '" << ID
256           << "' instance variable was not retained by a synthesized property "
257              "but was released in 'dealloc'";
258      }
259
260      BR.EmitBasicReport(name, category, os.str(), (*I)->getLocation());
261    }
262  }
263}
264
265//===----------------------------------------------------------------------===//
266// ObjCDeallocChecker
267//===----------------------------------------------------------------------===//
268
269namespace {
270class ObjCDeallocChecker : public Checker<
271                                      check::ASTDecl<ObjCImplementationDecl> > {
272public:
273  void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& mgr,
274                    BugReporter &BR) const {
275    if (mgr.getLangOptions().getGC() == LangOptions::GCOnly)
276      return;
277    checkObjCDealloc(cast<ObjCImplementationDecl>(D), mgr.getLangOptions(), BR);
278  }
279};
280}
281
282void ento::registerObjCDeallocChecker(CheckerManager &mgr) {
283  mgr.registerChecker<ObjCDeallocChecker>();
284}
285