1 //=- NSAutoreleasePoolChecker.cpp --------------------------------*- 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 NSAutoreleasePoolChecker, a small checker that warns
11 // about subpar uses of NSAutoreleasePool. Note that while the check itself
12 // (in it's 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.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "ClangSACheckers.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/Decl.h"
26
27 using namespace clang;
28 using namespace ento;
29
30 namespace {
31 class NSAutoreleasePoolChecker
32 : public Checker<check::PreObjCMessage> {
33
34 mutable Selector releaseS;
35
36 public:
37 void checkPreObjCMessage(ObjCMessage msg, CheckerContext &C) const;
38 };
39
40 } // end anonymous namespace
41
checkPreObjCMessage(ObjCMessage msg,CheckerContext & C) const42 void NSAutoreleasePoolChecker::checkPreObjCMessage(ObjCMessage msg,
43 CheckerContext &C) const {
44
45 const Expr *receiver = msg.getInstanceReceiver();
46 if (!receiver)
47 return;
48
49 // FIXME: Enhance with value-tracking information instead of consulting
50 // the type of the expression.
51 const ObjCObjectPointerType* PT =
52 receiver->getType()->getAs<ObjCObjectPointerType>();
53
54 if (!PT)
55 return;
56 const ObjCInterfaceDecl* OD = PT->getInterfaceDecl();
57 if (!OD)
58 return;
59 if (!OD->getIdentifier()->getName().equals("NSAutoreleasePool"))
60 return;
61
62 if (releaseS.isNull())
63 releaseS = GetNullarySelector("release", C.getASTContext());
64 // Sending 'release' message?
65 if (msg.getSelector() != releaseS)
66 return;
67
68 SourceRange R = msg.getSourceRange();
69
70 C.getBugReporter().EmitBasicReport("Use -drain instead of -release",
71 "API Upgrade (Apple)",
72 "Use -drain instead of -release when using NSAutoreleasePool "
73 "and garbage collection", R.getBegin(), &R, 1);
74 }
75
registerNSAutoreleasePoolChecker(CheckerManager & mgr)76 void ento::registerNSAutoreleasePoolChecker(CheckerManager &mgr) {
77 if (mgr.getLangOptions().getGCMode() != LangOptions::NonGC)
78 mgr.registerChecker<NSAutoreleasePoolChecker>();
79 }
80