1 //=- NSAutoreleasePoolChecker.cpp --------------------------------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a NSAutoreleasePoolChecker, a small checker that warns
11 // about subpar uses of NSAutoreleasePool. Note that while the check itself
12 // (in its current form) could be written as a flow-insensitive check, in
13 // can be potentially enhanced in the future with flow-sensitive information.
14 // It is also a good example of the CheckerVisitor interface.
16 //===----------------------------------------------------------------------===//
18 #include "ClangSACheckers.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/Decl.h"
28 using namespace clang;
32 class NSAutoreleasePoolChecker
33 : public Checker<check::PreObjCMessage> {
35 mutable Selector releaseS;
38 void checkPreObjCMessage(ObjCMessage msg, CheckerContext &C) const;
41 } // end anonymous namespace
43 void NSAutoreleasePoolChecker::checkPreObjCMessage(ObjCMessage msg,
44 CheckerContext &C) const {
46 const Expr *receiver = msg.getInstanceReceiver();
50 // FIXME: Enhance with value-tracking information instead of consulting
51 // the type of the expression.
52 const ObjCObjectPointerType* PT =
53 receiver->getType()->getAs<ObjCObjectPointerType>();
57 const ObjCInterfaceDecl *OD = PT->getInterfaceDecl();
60 if (!OD->getIdentifier()->getName().equals("NSAutoreleasePool"))
63 if (releaseS.isNull())
64 releaseS = GetNullarySelector("release", C.getASTContext());
65 // Sending 'release' message?
66 if (msg.getSelector() != releaseS)
69 SourceRange R = msg.getSourceRange();
70 BugReporter &BR = C.getBugReporter();
71 const LocationContext *LC = C.getPredecessor()->getLocationContext();
72 const SourceManager &SM = BR.getSourceManager();
73 const Expr *E = msg.getMsgOrPropExpr();
74 PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(E, SM, LC);
75 C.getBugReporter().EmitBasicReport("Use -drain instead of -release",
76 "API Upgrade (Apple)",
77 "Use -drain instead of -release when using NSAutoreleasePool "
78 "and garbage collection", L, &R, 1);
81 void ento::registerNSAutoreleasePoolChecker(CheckerManager &mgr) {
82 if (mgr.getLangOptions().getGC() != LangOptions::NonGC)
83 mgr.registerChecker<NSAutoreleasePoolChecker>();