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
25#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclObjC.h"
28#include "clang/ASTMatchers/ASTMatchFinder.h"
29#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
30#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
31#include "clang/StaticAnalyzer/Core/Checker.h"
32#include "clang/StaticAnalyzer/Core/CheckerManager.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
35#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.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(Parent: C, A, B);
76 }
77 return false;
78}
79
80static void emitDiagnostics(BoundNodes &Match,
81 const Decl *D,
82 BugReporter &BR,
83 AnalysisManager &AM,
84 const RunLoopAutoreleaseLeakChecker *Checker) {
85 const Stmt *DeclBody = D->getBody();
86 assert(DeclBody);
87
88 AnalysisDeclContext *ADC = AM.getAnalysisDeclContext(D);
89
90 const auto *ME = Match.getNodeAs<ObjCMessageExpr>(ID: OtherMsgBind);
91 assert(ME);
92
93 const auto *AP =
94 Match.getNodeAs<ObjCAutoreleasePoolStmt>(ID: AutoreleasePoolBind);
95 const auto *OAP =
96 Match.getNodeAs<ObjCAutoreleasePoolStmt>(ID: OtherStmtAutoreleasePoolBind);
97 bool HasAutoreleasePool = (AP != nullptr);
98
99 const auto *RL = Match.getNodeAs<ObjCMessageExpr>(ID: RunLoopBind);
100 const auto *RLR = Match.getNodeAs<Stmt>(ID: 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(Parent: DeclBody, A: RLR, B: ME))
106 return;
107
108 if (HasAutoreleasePool && (OAP != AP))
109 return;
110
111 PathDiagnosticLocation Location = PathDiagnosticLocation::createBegin(
112 S: ME, SM: BR.getSourceManager(), SFAC: ADC);
113 SourceRange Range = ME->getSourceRange();
114
115 BR.EmitBasicReport(DeclWithIssue: ADC->getDecl(), Checker,
116 /*Name=*/BugName: "Memory leak inside autorelease pool",
117 /*BugCategory=*/"Memory",
118 /*Name=*/
119 BugStr: (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 Loc: Location, Ranges: Range);
128}
129
130static StatementMatcher getRunLoopRunM(StatementMatcher Extra = anything()) {
131 StatementMatcher MainRunLoopM =
132 objcMessageExpr(hasSelector(BaseName: "mainRunLoop"),
133 hasReceiverType(InnerMatcher: asString(Name: "NSRunLoop")),
134 Extra)
135 .bind(ID: RunLoopBind);
136
137 StatementMatcher MainRunLoopRunM = objcMessageExpr(hasSelector(BaseName: "run"),
138 hasReceiver(InnerMatcher: MainRunLoopM),
139 Extra).bind(ID: RunLoopRunBind);
140
141 StatementMatcher XPCRunM =
142 callExpr(callee(InnerMatcher: functionDecl(hasName(Name: "xpc_main")))).bind(ID: RunLoopRunBind);
143 return anyOf(MainRunLoopRunM, XPCRunM);
144}
145
146static StatementMatcher getOtherMessageSentM(StatementMatcher Extra = anything()) {
147 return objcMessageExpr(unless(anyOf(equalsBoundNode(ID: RunLoopBind),
148 equalsBoundNode(ID: RunLoopRunBind))),
149 Extra)
150 .bind(ID: OtherMsgBind);
151}
152
153static void
154checkTempObjectsInSamePool(const Decl *D, AnalysisManager &AM, BugReporter &BR,
155 const RunLoopAutoreleaseLeakChecker *Chkr) {
156 StatementMatcher RunLoopRunM = getRunLoopRunM();
157 StatementMatcher OtherMessageSentM = getOtherMessageSentM(
158 Extra: hasAncestor(autoreleasePoolStmt().bind(ID: OtherStmtAutoreleasePoolBind)));
159
160 StatementMatcher RunLoopInAutorelease =
161 autoreleasePoolStmt(
162 hasDescendant(RunLoopRunM),
163 hasDescendant(OtherMessageSentM)).bind(ID: AutoreleasePoolBind);
164
165 DeclarationMatcher GroupM = decl(hasDescendant(RunLoopInAutorelease));
166
167 auto Matches = match(Matcher: GroupM, Node: *D, Context&: AM.getASTContext());
168 for (BoundNodes Match : Matches)
169 emitDiagnostics(Match, D, BR, AM, Checker: Chkr);
170}
171
172static void
173checkTempObjectsInNoPool(const Decl *D, AnalysisManager &AM, BugReporter &BR,
174 const RunLoopAutoreleaseLeakChecker *Chkr) {
175
176 auto NoPoolM = unless(hasAncestor(autoreleasePoolStmt()));
177
178 StatementMatcher RunLoopRunM = getRunLoopRunM(Extra: NoPoolM);
179 StatementMatcher OtherMessageSentM = getOtherMessageSentM(Extra: NoPoolM);
180
181 DeclarationMatcher GroupM = functionDecl(
182 isMain(),
183 hasDescendant(RunLoopRunM),
184 hasDescendant(OtherMessageSentM)
185 );
186
187 auto Matches = match(Matcher: GroupM, Node: *D, Context&: AM.getASTContext());
188
189 for (BoundNodes Match : Matches)
190 emitDiagnostics(Match, D, BR, AM, Checker: Chkr);
191
192}
193
194void RunLoopAutoreleaseLeakChecker::checkASTCodeBody(const Decl *D,
195 AnalysisManager &AM,
196 BugReporter &BR) const {
197 checkTempObjectsInSamePool(D, AM, BR, Chkr: this);
198 checkTempObjectsInNoPool(D, AM, BR, Chkr: this);
199}
200
201void ento::registerRunLoopAutoreleaseLeakChecker(CheckerManager &mgr) {
202 mgr.registerChecker<RunLoopAutoreleaseLeakChecker>();
203}
204
205bool ento::shouldRegisterRunLoopAutoreleaseLeakChecker(const CheckerManager &mgr) {
206 return true;
207}
208