1 //=- NSAutoreleasePoolChecker.cpp --------------------------------*- C++ -*-==//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines a NSAutoreleasePoolChecker, a small checker that warns
10 // about subpar uses of NSAutoreleasePool. Note that while the check itself
11 // (in its current form) could be written as a flow-insensitive check, in
12 // can be potentially enhanced in the future with flow-sensitive information.
13 // It is also a good example of the CheckerVisitor interface.
15 //===----------------------------------------------------------------------===//
17 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
28 using namespace clang
;
32 class NSAutoreleasePoolChecker
33 : public Checker
<check::PreObjCMessage
> {
34 mutable std::unique_ptr
<BugType
> BT
;
35 mutable Selector releaseS
;
38 void checkPreObjCMessage(const ObjCMethodCall
&msg
, CheckerContext
&C
) const;
41 } // end anonymous namespace
43 void NSAutoreleasePoolChecker::checkPreObjCMessage(const ObjCMethodCall
&msg
,
44 CheckerContext
&C
) const {
45 if (!msg
.isInstanceMessage())
48 const ObjCInterfaceDecl
*OD
= msg
.getReceiverInterface();
51 if (!OD
->getIdentifier()->isStr("NSAutoreleasePool"))
54 if (releaseS
.isNull())
55 releaseS
= GetNullarySelector("release", C
.getASTContext());
56 // Sending 'release' message?
57 if (msg
.getSelector() != releaseS
)
61 BT
.reset(new BugType(this, "Use -drain instead of -release",
62 "API Upgrade (Apple)"));
64 ExplodedNode
*N
= C
.generateNonFatalErrorNode();
70 auto Report
= std::make_unique
<PathSensitiveBugReport
>(
72 "Use -drain instead of -release when using NSAutoreleasePool and "
75 Report
->addRange(msg
.getSourceRange());
76 C
.emitReport(std::move(Report
));
79 void ento::registerNSAutoreleasePoolChecker(CheckerManager
&mgr
) {
80 mgr
.registerChecker
<NSAutoreleasePoolChecker
>();
83 bool ento::shouldRegisterNSAutoreleasePoolChecker(const CheckerManager
&mgr
) {
84 const LangOptions
&LO
= mgr
.getLangOpts();
85 return LO
.getGC() != LangOptions::NonGC
;