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