clang API Documentation

CheckObjCDealloc.cpp
Go to the documentation of this file.
00001 //==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines a CheckObjCDealloc, a checker that
00011 //  analyzes an Objective-C class's implementation to determine if it
00012 //  correctly implements -dealloc.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "ClangSACheckers.h"
00017 #include "clang/StaticAnalyzer/Core/Checker.h"
00018 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
00019 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
00020 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
00021 #include "clang/AST/ExprObjC.h"
00022 #include "clang/AST/Expr.h"
00023 #include "clang/AST/DeclObjC.h"
00024 #include "clang/Basic/LangOptions.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 
00027 using namespace clang;
00028 using namespace ento;
00029 
00030 static bool scan_dealloc(Stmt *S, Selector Dealloc) {
00031 
00032   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S))
00033     if (ME->getSelector() == Dealloc) {
00034       switch (ME->getReceiverKind()) {
00035       case ObjCMessageExpr::Instance: return false;
00036       case ObjCMessageExpr::SuperInstance: return true;
00037       case ObjCMessageExpr::Class: break;
00038       case ObjCMessageExpr::SuperClass: break;
00039       }
00040     }
00041 
00042   // Recurse to children.
00043 
00044   for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)
00045     if (*I && scan_dealloc(*I, Dealloc))
00046       return true;
00047 
00048   return false;
00049 }
00050 
00051 static bool scan_ivar_release(Stmt *S, ObjCIvarDecl *ID,
00052                               const ObjCPropertyDecl *PD,
00053                               Selector Release,
00054                               IdentifierInfo* SelfII,
00055                               ASTContext &Ctx) {
00056 
00057   // [mMyIvar release]
00058   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S))
00059     if (ME->getSelector() == Release)
00060       if (ME->getInstanceReceiver())
00061         if (Expr *Receiver = ME->getInstanceReceiver()->IgnoreParenCasts())
00062           if (ObjCIvarRefExpr *E = dyn_cast<ObjCIvarRefExpr>(Receiver))
00063             if (E->getDecl() == ID)
00064               return true;
00065 
00066   // [self setMyIvar:nil];
00067   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S))
00068     if (ME->getInstanceReceiver())
00069       if (Expr *Receiver = ME->getInstanceReceiver()->IgnoreParenCasts())
00070         if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(Receiver))
00071           if (E->getDecl()->getIdentifier() == SelfII)
00072             if (ME->getMethodDecl() == PD->getSetterMethodDecl() &&
00073                 ME->getNumArgs() == 1 &&
00074                 ME->getArg(0)->isNullPointerConstant(Ctx, 
00075                                               Expr::NPC_ValueDependentIsNull))
00076               return true;
00077 
00078   // self.myIvar = nil;
00079   if (BinaryOperator* BO = dyn_cast<BinaryOperator>(S))
00080     if (BO->isAssignmentOp())
00081       if (ObjCPropertyRefExpr *PRE =
00082            dyn_cast<ObjCPropertyRefExpr>(BO->getLHS()->IgnoreParenCasts()))
00083         if (PRE->isExplicitProperty() && PRE->getExplicitProperty() == PD)
00084             if (BO->getRHS()->isNullPointerConstant(Ctx, 
00085                                             Expr::NPC_ValueDependentIsNull)) {
00086               // This is only a 'release' if the property kind is not
00087               // 'assign'.
00088               return PD->getSetterKind() != ObjCPropertyDecl::Assign;;
00089             }
00090 
00091   // Recurse to children.
00092   for (Stmt::child_iterator I = S->child_begin(), E= S->child_end(); I!=E; ++I)
00093     if (*I && scan_ivar_release(*I, ID, PD, Release, SelfII, Ctx))
00094       return true;
00095 
00096   return false;
00097 }
00098 
00099 static void checkObjCDealloc(const ObjCImplementationDecl *D,
00100                              const LangOptions& LOpts, BugReporter& BR) {
00101 
00102   assert (LOpts.getGC() != LangOptions::GCOnly);
00103 
00104   ASTContext &Ctx = BR.getContext();
00105   const ObjCInterfaceDecl *ID = D->getClassInterface();
00106 
00107   // Does the class contain any ivars that are pointers (or id<...>)?
00108   // If not, skip the check entirely.
00109   // NOTE: This is motivated by PR 2517:
00110   //        http://llvm.org/bugs/show_bug.cgi?id=2517
00111 
00112   bool containsPointerIvar = false;
00113 
00114   for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end();
00115        I!=E; ++I) {
00116 
00117     ObjCIvarDecl *ID = &*I;
00118     QualType T = ID->getType();
00119 
00120     if (!T->isObjCObjectPointerType() ||
00121         ID->getAttr<IBOutletAttr>() || // Skip IBOutlets.
00122         ID->getAttr<IBOutletCollectionAttr>()) // Skip IBOutletCollections.
00123       continue;
00124 
00125     containsPointerIvar = true;
00126     break;
00127   }
00128 
00129   if (!containsPointerIvar)
00130     return;
00131 
00132   // Determine if the class subclasses NSObject.
00133   IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
00134   IdentifierInfo* SenTestCaseII = &Ctx.Idents.get("SenTestCase");
00135 
00136 
00137   for ( ; ID ; ID = ID->getSuperClass()) {
00138     IdentifierInfo *II = ID->getIdentifier();
00139 
00140     if (II == NSObjectII)
00141       break;
00142 
00143     // FIXME: For now, ignore classes that subclass SenTestCase, as these don't
00144     // need to implement -dealloc.  They implement tear down in another way,
00145     // which we should try and catch later.
00146     //  http://llvm.org/bugs/show_bug.cgi?id=3187
00147     if (II == SenTestCaseII)
00148       return;
00149   }
00150 
00151   if (!ID)
00152     return;
00153 
00154   // Get the "dealloc" selector.
00155   IdentifierInfo* II = &Ctx.Idents.get("dealloc");
00156   Selector S = Ctx.Selectors.getSelector(0, &II);
00157   ObjCMethodDecl *MD = 0;
00158 
00159   // Scan the instance methods for "dealloc".
00160   for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
00161        E = D->instmeth_end(); I!=E; ++I) {
00162 
00163     if ((*I)->getSelector() == S) {
00164       MD = *I;
00165       break;
00166     }
00167   }
00168 
00169   PathDiagnosticLocation DLoc =
00170     PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
00171 
00172   if (!MD) { // No dealloc found.
00173 
00174     const char* name = LOpts.getGC() == LangOptions::NonGC
00175                        ? "missing -dealloc"
00176                        : "missing -dealloc (Hybrid MM, non-GC)";
00177 
00178     std::string buf;
00179     llvm::raw_string_ostream os(buf);
00180     os << "Objective-C class '" << *D << "' lacks a 'dealloc' instance method";
00181 
00182     BR.EmitBasicReport(D, name, categories::CoreFoundationObjectiveC,
00183                        os.str(), DLoc);
00184     return;
00185   }
00186 
00187   // dealloc found.  Scan for missing [super dealloc].
00188   if (MD->getBody() && !scan_dealloc(MD->getBody(), S)) {
00189 
00190     const char* name = LOpts.getGC() == LangOptions::NonGC
00191                        ? "missing [super dealloc]"
00192                        : "missing [super dealloc] (Hybrid MM, non-GC)";
00193 
00194     std::string buf;
00195     llvm::raw_string_ostream os(buf);
00196     os << "The 'dealloc' instance method in Objective-C class '" << *D
00197        << "' does not send a 'dealloc' message to its super class"
00198            " (missing [super dealloc])";
00199 
00200     BR.EmitBasicReport(MD, name, categories::CoreFoundationObjectiveC,
00201                        os.str(), DLoc);
00202     return;
00203   }
00204 
00205   // Get the "release" selector.
00206   IdentifierInfo* RII = &Ctx.Idents.get("release");
00207   Selector RS = Ctx.Selectors.getSelector(0, &RII);
00208 
00209   // Get the "self" identifier
00210   IdentifierInfo* SelfII = &Ctx.Idents.get("self");
00211 
00212   // Scan for missing and extra releases of ivars used by implementations
00213   // of synthesized properties
00214   for (ObjCImplementationDecl::propimpl_iterator I = D->propimpl_begin(),
00215        E = D->propimpl_end(); I!=E; ++I) {
00216 
00217     // We can only check the synthesized properties
00218     if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
00219       continue;
00220 
00221     ObjCIvarDecl *ID = I->getPropertyIvarDecl();
00222     if (!ID)
00223       continue;
00224 
00225     QualType T = ID->getType();
00226     if (!T->isObjCObjectPointerType()) // Skip non-pointer ivars
00227       continue;
00228 
00229     const ObjCPropertyDecl *PD = I->getPropertyDecl();
00230     if (!PD)
00231       continue;
00232 
00233     // ivars cannot be set via read-only properties, so we'll skip them
00234     if (PD->isReadOnly())
00235       continue;
00236 
00237     // ivar must be released if and only if the kind of setter was not 'assign'
00238     bool requiresRelease = PD->getSetterKind() != ObjCPropertyDecl::Assign;
00239     if (scan_ivar_release(MD->getBody(), ID, PD, RS, SelfII, Ctx)
00240        != requiresRelease) {
00241       const char *name = 0;
00242       std::string buf;
00243       llvm::raw_string_ostream os(buf);
00244 
00245       if (requiresRelease) {
00246         name = LOpts.getGC() == LangOptions::NonGC
00247                ? "missing ivar release (leak)"
00248                : "missing ivar release (Hybrid MM, non-GC)";
00249 
00250         os << "The '" << *ID
00251            << "' instance variable was retained by a synthesized property but "
00252               "wasn't released in 'dealloc'";
00253       } else {
00254         name = LOpts.getGC() == LangOptions::NonGC
00255                ? "extra ivar release (use-after-release)"
00256                : "extra ivar release (Hybrid MM, non-GC)";
00257 
00258         os << "The '" << *ID
00259            << "' instance variable was not retained by a synthesized property "
00260               "but was released in 'dealloc'";
00261       }
00262 
00263       PathDiagnosticLocation SDLoc =
00264         PathDiagnosticLocation::createBegin(&*I, BR.getSourceManager());
00265 
00266       BR.EmitBasicReport(MD, name, categories::CoreFoundationObjectiveC,
00267                          os.str(), SDLoc);
00268     }
00269   }
00270 }
00271 
00272 //===----------------------------------------------------------------------===//
00273 // ObjCDeallocChecker
00274 //===----------------------------------------------------------------------===//
00275 
00276 namespace {
00277 class ObjCDeallocChecker : public Checker<
00278                                       check::ASTDecl<ObjCImplementationDecl> > {
00279 public:
00280   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& mgr,
00281                     BugReporter &BR) const {
00282     if (mgr.getLangOpts().getGC() == LangOptions::GCOnly)
00283       return;
00284     checkObjCDealloc(cast<ObjCImplementationDecl>(D), mgr.getLangOpts(), BR);
00285   }
00286 };
00287 }
00288 
00289 void ento::registerObjCDeallocChecker(CheckerManager &mgr) {
00290   mgr.registerChecker<ObjCDeallocChecker>();
00291 }