clang 24.0.0git
RunLoopAutoreleaseLeakChecker.cpp
Go to the documentation of this file.
1//=- RunLoopAutoreleaseLeakChecker.cpp --------------------------*- C++ -*-==//
2//
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
6//
7//
8//===----------------------------------------------------------------------===//
9//
10// A checker for detecting leaks resulting from allocating temporary
11// autoreleased objects before starting the main run loop.
12//
13// Checks for two antipatterns:
14// 1. ObjCMessageExpr followed by [[NSRunLoop mainRunLoop] run] in the same
15// autorelease pool.
16// 2. ObjCMessageExpr followed by [[NSRunLoop mainRunLoop] run] in no
17// autorelease pool.
18//
19// Any temporary objects autoreleased in code called in those expressions
20// will not be deallocated until the program exits, and are effectively leaks.
21//
22//===----------------------------------------------------------------------===//
23//
24
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclObjC.h"
36
37using namespace clang;
38using namespace ento;
39using namespace ast_matchers;
40
41namespace {
42
43const char * RunLoopBind = "NSRunLoopM";
44const char * RunLoopRunBind = "RunLoopRunM";
45const char * OtherMsgBind = "OtherMessageSentM";
46const char * AutoreleasePoolBind = "AutoreleasePoolM";
47const char * OtherStmtAutoreleasePoolBind = "OtherAutoreleasePoolM";
48
49class RunLoopAutoreleaseLeakChecker : public Checker<check::ASTCodeBody> {
50
51public:
52 void checkASTCodeBody(const Decl *D,
53 AnalysisManager &AM,
54 BugReporter &BR) const;
55
56};
57
58} // end anonymous namespace
59
60/// \return Whether @c A occurs before @c B in traversal of
61/// @c Parent.
62/// Conceptually a very incomplete/unsound approximation of happens-before
63/// relationship (A is likely to be evaluated before B),
64/// but useful enough in this case.
65static bool seenBefore(const Stmt *Parent, const Stmt *A, const Stmt *B) {
66 for (const Stmt *C : Parent->children()) {
67 if (!C) continue;
68
69 if (C == A)
70 return true;
71
72 if (C == B)
73 return false;
74
75 return seenBefore(C, A, B);
76 }
77 return false;
78}
79
81 const Decl *D,
82 BugReporter &BR,
84 const RunLoopAutoreleaseLeakChecker *Checker) {
85 const Stmt *DeclBody = D->getBody();
86 assert(DeclBody);
87
89
90 const auto *ME = Match.getNodeAs<ObjCMessageExpr>(OtherMsgBind);
91 assert(ME);
92
93 const auto *AP =
94 Match.getNodeAs<ObjCAutoreleasePoolStmt>(AutoreleasePoolBind);
95 const auto *OAP =
96 Match.getNodeAs<ObjCAutoreleasePoolStmt>(OtherStmtAutoreleasePoolBind);
97 bool HasAutoreleasePool = (AP != nullptr);
98
99 const auto *RL = Match.getNodeAs<ObjCMessageExpr>(RunLoopBind);
100 const auto *RLR = Match.getNodeAs<Stmt>(RunLoopRunBind);
101 assert(RLR && "Run loop launch not found");
102 assert(ME != RLR);
103
104 // Launch of run loop occurs before the message-sent expression is seen.
105 if (seenBefore(DeclBody, RLR, ME))
106 return;
107
108 if (HasAutoreleasePool && (OAP != AP))
109 return;
110
112 ME, BR.getSourceManager(), ADC);
113 SourceRange Range = ME->getSourceRange();
114
116 /*Name=*/"Memory leak inside autorelease pool",
117 /*BugCategory=*/"Memory",
118 /*Name=*/
119 (Twine("Temporary objects allocated in the") +
120 " autorelease pool " +
121 (HasAutoreleasePool ? "" : "of last resort ") +
122 "followed by the launch of " +
123 (RL ? "main run loop " : "xpc_main ") +
124 "may never get released; consider moving them to a "
125 "separate autorelease pool")
126 .str(),
127 Location, Range);
128}
129
131 StatementMatcher MainRunLoopM =
132 objcMessageExpr(hasSelector("mainRunLoop"),
133 hasReceiverType(asString("NSRunLoop")),
134 Extra)
135 .bind(RunLoopBind);
136
137 StatementMatcher MainRunLoopRunM = objcMessageExpr(hasSelector("run"),
138 hasReceiver(MainRunLoopM),
139 Extra).bind(RunLoopRunBind);
140
141 StatementMatcher XPCRunM =
142 callExpr(callee(functionDecl(hasName("xpc_main")))).bind(RunLoopRunBind);
143 return anyOf(MainRunLoopRunM, XPCRunM);
144}
145
147 return objcMessageExpr(unless(anyOf(equalsBoundNode(RunLoopBind),
148 equalsBoundNode(RunLoopRunBind))),
149 Extra)
150 .bind(OtherMsgBind);
151}
152
153static void
155 const RunLoopAutoreleaseLeakChecker *Chkr) {
156 StatementMatcher RunLoopRunM = getRunLoopRunM();
157 StatementMatcher OtherMessageSentM = getOtherMessageSentM(
158 hasAncestor(autoreleasePoolStmt().bind(OtherStmtAutoreleasePoolBind)));
159
160 StatementMatcher RunLoopInAutorelease =
162 hasDescendant(RunLoopRunM),
163 hasDescendant(OtherMessageSentM)).bind(AutoreleasePoolBind);
164
165 DeclarationMatcher GroupM = decl(hasDescendant(RunLoopInAutorelease));
166
167 auto Matches = match(GroupM, *D, AM.getASTContext());
168 for (BoundNodes Match : Matches)
169 emitDiagnostics(Match, D, BR, AM, Chkr);
170}
171
172static void
174 const RunLoopAutoreleaseLeakChecker *Chkr) {
175
176 auto NoPoolM = unless(hasAncestor(autoreleasePoolStmt()));
177
178 StatementMatcher RunLoopRunM = getRunLoopRunM(NoPoolM);
179 StatementMatcher OtherMessageSentM = getOtherMessageSentM(NoPoolM);
180
182 isMain(),
183 hasDescendant(RunLoopRunM),
184 hasDescendant(OtherMessageSentM)
185 );
186
187 auto Matches = match(GroupM, *D, AM.getASTContext());
188
189 for (BoundNodes Match : Matches)
190 emitDiagnostics(Match, D, BR, AM, Chkr);
191
192}
193
194void RunLoopAutoreleaseLeakChecker::checkASTCodeBody(const Decl *D,
195 AnalysisManager &AM,
196 BugReporter &BR) const {
197 checkTempObjectsInSamePool(D, AM, BR, this);
198 checkTempObjectsInNoPool(D, AM, BR, this);
199}
200
201void ento::registerRunLoopAutoreleaseLeakChecker(CheckerManager &mgr) {
202 mgr.registerChecker<RunLoopAutoreleaseLeakChecker>();
203}
204
205bool ento::shouldRegisterRunLoopAutoreleaseLeakChecker(const CheckerManager &mgr) {
206 return true;
207}
static void emitDiagnostics(BoundNodes &Match, const Decl *D, BugReporter &BR, AnalysisManager &AM, const RunLoopAutoreleaseLeakChecker *Checker)
static bool seenBefore(const Stmt *Parent, const Stmt *A, const Stmt *B)
static void checkTempObjectsInSamePool(const Decl *D, AnalysisManager &AM, BugReporter &BR, const RunLoopAutoreleaseLeakChecker *Chkr)
static StatementMatcher getRunLoopRunM(StatementMatcher Extra=anything())
static StatementMatcher getOtherMessageSentM(StatementMatcher Extra=anything())
static void checkTempObjectsInNoPool(const Decl *D, AnalysisManager &AM, BugReporter &BR, const RunLoopAutoreleaseLeakChecker *Chkr)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1104
Represents Objective-C's @autoreleasepool Statement.
Definition StmtObjC.h:394
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:972
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
Maps string IDs to AST nodes matched by parts of a matcher.
ASTContext & getASTContext() override
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
BugReporter is a utility class for generating PathDiagnostics for analysis.
const SourceManager & getSourceManager()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
A Range represents the closed range [from, to].
const internal::VariadicOperatorMatcherFunc< 1, 1 > unless
Matches if the provided matcher does not match.
internal::Matcher< Decl > DeclarationMatcher
Types of matchers for the top-level classes in the AST class hierarchy.
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, ObjCAutoreleasePoolStmt > autoreleasePoolStmt
Matches an Objective-C autorelease pool statement.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
internal::TrueMatcher anything()
Matches any node.
const internal::VariadicDynCastAllOfMatcher< Stmt, ObjCMessageExpr > objcMessageExpr
Matches ObjectiveC Message invocation expressions.
internal::Matcher< Stmt > StatementMatcher
const internal::VariadicDynCastAllOfMatcher< Decl, FunctionDecl > functionDecl
Matches function declarations.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
const internal::ArgumentAdaptingMatcherFunc< internal::HasAncestorMatcher, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr >, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr > > hasAncestor
Matches AST nodes that have an ancestor that matches the provided matcher.
Top level wrappers for InstallAPI frontend operations.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824