blob: 7285d27495a7c1ab39a4611b30bb238a0d35f780 [file] [log] [blame]
Ted Kremenekf5d2ef42011-02-25 22:00:43 +00001//=== StackAddrEscapeChecker.cpp ----------------------------------*- C++ -*--//
Zhongxing Xu1622a542010-06-08 10:00:00 +00002//
Chandler Carruth324f9182019-01-19 08:50:56 +00003// 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
Zhongxing Xu1622a542010-06-08 10:00:00 +00006//
7//===----------------------------------------------------------------------===//
8//
Ted Kremenek99bb39a2015-09-08 03:50:52 +00009// This file defines stack address leak checker, which checks if an invalid
Zhongxing Xu1622a542010-06-08 10:00:00 +000010// stack address is stored into a global or heap location. See CERT DCL30-C.
11//
12//===----------------------------------------------------------------------===//
13
Kristof Umann308797c2018-12-15 16:23:51 +000014#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ExprCXX.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000018#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000019#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
Zhongxing Xu9b146832010-06-09 06:08:24 +000023#include "llvm/ADT/SmallString.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000024#include "llvm/Support/raw_ostream.h"
Zhongxing Xu1622a542010-06-08 10:00:00 +000025using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000026using namespace ento;
Zhongxing Xu1622a542010-06-08 10:00:00 +000027
28namespace {
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000029class StackAddrEscapeChecker
30 : public Checker<check::PreCall, check::PreStmt<ReturnStmt>,
31 check::EndFunction> {
32 mutable IdentifierInfo *dispatch_semaphore_tII;
Ahmed Charles70639e82014-03-07 20:03:18 +000033 mutable std::unique_ptr<BuiltinBug> BT_stackleak;
34 mutable std::unique_ptr<BuiltinBug> BT_returnstack;
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000035 mutable std::unique_ptr<BuiltinBug> BT_capturedstackasync;
36 mutable std::unique_ptr<BuiltinBug> BT_capturedstackret;
Zhongxing Xu1622a542010-06-08 10:00:00 +000037
38public:
Artem Dergachevbdf9e462017-12-12 02:59:09 +000039 enum CheckKind {
40 CK_StackAddrEscapeChecker,
41 CK_StackAddrAsyncEscapeChecker,
42 CK_NumCheckKinds
43 };
44
45 DefaultBool ChecksEnabled[CK_NumCheckKinds];
46
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000047 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000048 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
Reka Kovacs3ad62f52018-07-16 20:47:45 +000049 void checkEndFunction(const ReturnStmt *RS, CheckerContext &Ctx) const;
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000050
Zhongxing Xu9b146832010-06-09 06:08:24 +000051private:
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000052 void checkReturnedBlockCaptures(const BlockDataRegion &B,
53 CheckerContext &C) const;
54 void checkAsyncExecutedBlockCaptures(const BlockDataRegion &B,
55 CheckerContext &C) const;
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000056 void EmitStackError(CheckerContext &C, const MemRegion *R,
57 const Expr *RetE) const;
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000058 bool isSemaphoreCaptured(const BlockDecl &B) const;
Jordan Rosea0e6e6d2013-02-26 01:21:21 +000059 static SourceRange genName(raw_ostream &os, const MemRegion *R,
60 ASTContext &Ctx);
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000061 static SmallVector<const MemRegion *, 4>
62 getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C);
63 static bool isArcManagedBlock(const MemRegion *R, CheckerContext &C);
64 static bool isNotInCurrentFrame(const MemRegion *R, CheckerContext &C);
Zhongxing Xu1622a542010-06-08 10:00:00 +000065};
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000066} // namespace
Zhongxing Xu1622a542010-06-08 10:00:00 +000067
Jordan Rosea0e6e6d2013-02-26 01:21:21 +000068SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion *R,
69 ASTContext &Ctx) {
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000070 // Get the base region, stripping away fields and elements.
Ted Kremeneka8166152010-06-17 04:21:37 +000071 R = R->getBaseRegion();
Jordan Rosea0e6e6d2013-02-26 01:21:21 +000072 SourceManager &SM = Ctx.getSourceManager();
Ted Kremeneka8166152010-06-17 04:21:37 +000073 SourceRange range;
74 os << "Address of ";
Ted Kremenek99bb39a2015-09-08 03:50:52 +000075
Ted Kremeneka8166152010-06-17 04:21:37 +000076 // Check if the region is a compound literal.
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000077 if (const auto *CR = dyn_cast<CompoundLiteralRegion>(R)) {
Ted Kremenek9c378f72011-08-12 23:37:29 +000078 const CompoundLiteralExpr *CL = CR->getLiteralExpr();
Ted Kremeneka8166152010-06-17 04:21:37 +000079 os << "stack memory associated with a compound literal "
80 "declared on line "
Stephen Kellyd7b659b2018-08-09 21:08:08 +000081 << SM.getExpansionLineNumber(CL->getBeginLoc()) << " returned to caller";
Ted Kremeneka8166152010-06-17 04:21:37 +000082 range = CL->getSourceRange();
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000083 } else if (const auto *AR = dyn_cast<AllocaRegion>(R)) {
Ted Kremenek9c378f72011-08-12 23:37:29 +000084 const Expr *ARE = AR->getExpr();
Stephen Kellyd7b659b2018-08-09 21:08:08 +000085 SourceLocation L = ARE->getBeginLoc();
Ted Kremenek99bb39a2015-09-08 03:50:52 +000086 range = ARE->getSourceRange();
Ted Kremeneka8166152010-06-17 04:21:37 +000087 os << "stack memory allocated by call to alloca() on line "
Chandler Carruth64211622011-07-25 21:09:52 +000088 << SM.getExpansionLineNumber(L);
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000089 } else if (const auto *BR = dyn_cast<BlockDataRegion>(R)) {
Ted Kremeneka8166152010-06-17 04:21:37 +000090 const BlockDecl *BD = BR->getCodeRegion()->getDecl();
Stephen Kellyd7b659b2018-08-09 21:08:08 +000091 SourceLocation L = BD->getBeginLoc();
Ted Kremeneka8166152010-06-17 04:21:37 +000092 range = BD->getSourceRange();
93 os << "stack-allocated block declared on line "
Chandler Carruth64211622011-07-25 21:09:52 +000094 << SM.getExpansionLineNumber(L);
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000095 } else if (const auto *VR = dyn_cast<VarRegion>(R)) {
96 os << "stack memory associated with local variable '" << VR->getString()
97 << '\'';
Ted Kremeneka8166152010-06-17 04:21:37 +000098 range = VR->getDecl()->getSourceRange();
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +000099 } else if (const auto *TOR = dyn_cast<CXXTempObjectRegion>(R)) {
Jordan Rosea0e6e6d2013-02-26 01:21:21 +0000100 QualType Ty = TOR->getValueType().getLocalUnqualifiedType();
101 os << "stack memory associated with temporary object of type '";
102 Ty.print(os, Ctx.getPrintingPolicy());
103 os << "'";
Jeffrey Yasskin782f63e2011-08-26 00:41:31 +0000104 range = TOR->getExpr()->getSourceRange();
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000105 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +0000106 llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
Ted Kremenek99bb39a2015-09-08 03:50:52 +0000107 }
108
Ted Kremeneka8166152010-06-17 04:21:37 +0000109 return range;
110}
111
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000112bool StackAddrEscapeChecker::isArcManagedBlock(const MemRegion *R,
113 CheckerContext &C) {
114 assert(R && "MemRegion should not be null");
115 return C.getASTContext().getLangOpts().ObjCAutoRefCount &&
116 isa<BlockDataRegion>(R);
117}
Zhongxing Xu9b146832010-06-09 06:08:24 +0000118
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000119bool StackAddrEscapeChecker::isNotInCurrentFrame(const MemRegion *R,
120 CheckerContext &C) {
121 const StackSpaceRegion *S = cast<StackSpaceRegion>(R->getMemorySpace());
George Karpenkov33876342018-06-27 01:51:55 +0000122 return S->getStackFrame() != C.getStackFrame();
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000123}
124
125bool StackAddrEscapeChecker::isSemaphoreCaptured(const BlockDecl &B) const {
126 if (!dispatch_semaphore_tII)
127 dispatch_semaphore_tII = &B.getASTContext().Idents.get("dispatch_semaphore_t");
128 for (const auto &C : B.captures()) {
129 const auto *T = C.getVariable()->getType()->getAs<TypedefType>();
130 if (T && T->getDecl()->getIdentifier() == dispatch_semaphore_tII)
Fangrui Songabdbb602018-07-30 19:24:48 +0000131 return true;
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000132 }
133 return false;
134}
135
136SmallVector<const MemRegion *, 4>
137StackAddrEscapeChecker::getCapturedStackRegions(const BlockDataRegion &B,
138 CheckerContext &C) {
139 SmallVector<const MemRegion *, 4> Regions;
140 BlockDataRegion::referenced_vars_iterator I = B.referenced_vars_begin();
141 BlockDataRegion::referenced_vars_iterator E = B.referenced_vars_end();
142 for (; I != E; ++I) {
143 SVal Val = C.getState()->getSVal(I.getCapturedRegion());
144 const MemRegion *Region = Val.getAsRegion();
145 if (Region && isa<StackSpaceRegion>(Region->getMemorySpace()))
146 Regions.push_back(Region);
147 }
148 return Regions;
149}
150
151void StackAddrEscapeChecker::EmitStackError(CheckerContext &C,
152 const MemRegion *R,
153 const Expr *RetE) const {
154 ExplodedNode *N = C.generateNonFatalErrorNode();
Zhongxing Xu9b146832010-06-09 06:08:24 +0000155 if (!N)
156 return;
Zhongxing Xu9b146832010-06-09 06:08:24 +0000157 if (!BT_returnstack)
Jonas Devlieghere49a6b092019-08-14 23:04:18 +0000158 BT_returnstack = std::make_unique<BuiltinBug>(
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000159 this, "Return of address to stack-allocated memory");
Zhongxing Xu9b146832010-06-09 06:08:24 +0000160 // Generate a report for this bug.
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000161 SmallString<128> buf;
Zhongxing Xu9b146832010-06-09 06:08:24 +0000162 llvm::raw_svector_ostream os(buf);
Jordan Rosea0e6e6d2013-02-26 01:21:21 +0000163 SourceRange range = genName(os, R, C.getASTContext());
Ted Kremeneka8166152010-06-17 04:21:37 +0000164 os << " returned to caller";
Artem Dergachev9e6519f2019-09-09 20:34:40 +0000165 auto report =
166 std::make_unique<PathSensitiveBugReport>(*BT_returnstack, os.str(), N);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000167 report->addRange(RetE->getSourceRange());
168 if (range.isValid())
169 report->addRange(range);
Aaron Ballmane1c2ad62015-06-23 13:15:32 +0000170 C.emitReport(std::move(report));
Eli Friedmana7e68452010-08-22 01:00:03 +0000171}
Zhongxing Xu9b146832010-06-09 06:08:24 +0000172
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000173void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures(
174 const BlockDataRegion &B, CheckerContext &C) const {
175 // There is a not-too-uncommon idiom
176 // where a block passed to dispatch_async captures a semaphore
177 // and then the thread (which called dispatch_async) is blocked on waiting
Fangrui Songabdbb602018-07-30 19:24:48 +0000178 // for the completion of the execution of the block
179 // via dispatch_semaphore_wait. To avoid false-positives (for now)
180 // we ignore all the blocks which have captured
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000181 // a variable of the type "dispatch_semaphore_t".
182 if (isSemaphoreCaptured(*B.getDecl()))
183 return;
184 for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
185 // The block passed to dispatch_async may capture another block
186 // created on the stack. However, there is no leak in this situaton,
187 // no matter if ARC or no ARC is enabled:
188 // dispatch_async copies the passed "outer" block (via Block_copy)
189 // and if the block has captured another "inner" block,
190 // the "inner" block will be copied as well.
191 if (isa<BlockDataRegion>(Region))
192 continue;
193 ExplodedNode *N = C.generateNonFatalErrorNode();
194 if (!N)
195 continue;
196 if (!BT_capturedstackasync)
Jonas Devlieghere49a6b092019-08-14 23:04:18 +0000197 BT_capturedstackasync = std::make_unique<BuiltinBug>(
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000198 this, "Address of stack-allocated memory is captured");
199 SmallString<128> Buf;
200 llvm::raw_svector_ostream Out(Buf);
201 SourceRange Range = genName(Out, Region, C.getASTContext());
202 Out << " is captured by an asynchronously-executed block";
Artem Dergachev9e6519f2019-09-09 20:34:40 +0000203 auto Report = std::make_unique<PathSensitiveBugReport>(
204 *BT_capturedstackasync, Out.str(), N);
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000205 if (Range.isValid())
206 Report->addRange(Range);
207 C.emitReport(std::move(Report));
208 }
209}
210
211void StackAddrEscapeChecker::checkReturnedBlockCaptures(
212 const BlockDataRegion &B, CheckerContext &C) const {
213 for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
214 if (isArcManagedBlock(Region, C) || isNotInCurrentFrame(Region, C))
215 continue;
216 ExplodedNode *N = C.generateNonFatalErrorNode();
217 if (!N)
218 continue;
219 if (!BT_capturedstackret)
Jonas Devlieghere49a6b092019-08-14 23:04:18 +0000220 BT_capturedstackret = std::make_unique<BuiltinBug>(
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000221 this, "Address of stack-allocated memory is captured");
222 SmallString<128> Buf;
223 llvm::raw_svector_ostream Out(Buf);
224 SourceRange Range = genName(Out, Region, C.getASTContext());
225 Out << " is captured by a returned block";
Artem Dergachev9e6519f2019-09-09 20:34:40 +0000226 auto Report = std::make_unique<PathSensitiveBugReport>(*BT_capturedstackret,
227 Out.str(), N);
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000228 if (Range.isValid())
229 Report->addRange(Range);
230 C.emitReport(std::move(Report));
231 }
232}
233
234void StackAddrEscapeChecker::checkPreCall(const CallEvent &Call,
235 CheckerContext &C) const {
Artem Dergachevbdf9e462017-12-12 02:59:09 +0000236 if (!ChecksEnabled[CK_StackAddrAsyncEscapeChecker])
237 return;
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000238 if (!Call.isGlobalCFunction("dispatch_after") &&
239 !Call.isGlobalCFunction("dispatch_async"))
240 return;
241 for (unsigned Idx = 0, NumArgs = Call.getNumArgs(); Idx < NumArgs; ++Idx) {
242 if (const BlockDataRegion *B = dyn_cast_or_null<BlockDataRegion>(
243 Call.getArgSVal(Idx).getAsRegion()))
244 checkAsyncExecutedBlockCaptures(*B, C);
245 }
246}
247
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000248void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
Ted Kremenek7e867832012-03-03 01:22:03 +0000249 CheckerContext &C) const {
Artem Dergachevbdf9e462017-12-12 02:59:09 +0000250 if (!ChecksEnabled[CK_StackAddrEscapeChecker])
251 return;
Ted Kremenek99bb39a2015-09-08 03:50:52 +0000252
Zhongxing Xu9b146832010-06-09 06:08:24 +0000253 const Expr *RetE = RS->getRetValue();
254 if (!RetE)
255 return;
Jordan Rose73212df2012-08-29 01:11:59 +0000256 RetE = RetE->IgnoreParens();
Jordan Rosec210cb72012-08-27 17:50:07 +0000257
George Karpenkovb340ee92018-01-17 20:27:29 +0000258 SVal V = C.getSVal(RetE);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000259 const MemRegion *R = V.getAsRegion();
Ted Kremenek7e867832012-03-03 01:22:03 +0000260 if (!R)
Zhongxing Xu9b146832010-06-09 06:08:24 +0000261 return;
Ted Kremenek99bb39a2015-09-08 03:50:52 +0000262
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000263 if (const BlockDataRegion *B = dyn_cast<BlockDataRegion>(R))
264 checkReturnedBlockCaptures(*B, C);
Ted Kremenek99bb39a2015-09-08 03:50:52 +0000265
Fangrui Songabdbb602018-07-30 19:24:48 +0000266 if (!isa<StackSpaceRegion>(R->getMemorySpace()) ||
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000267 isNotInCurrentFrame(R, C) || isArcManagedBlock(R, C))
Ted Kremenek7e867832012-03-03 01:22:03 +0000268 return;
269
Jordan Rosec210cb72012-08-27 17:50:07 +0000270 // Returning a record by value is fine. (In this case, the returned
Jordan Rose73212df2012-08-29 01:11:59 +0000271 // expression will be a copy-constructor, possibly wrapped in an
272 // ExprWithCleanups node.)
273 if (const ExprWithCleanups *Cleanup = dyn_cast<ExprWithCleanups>(RetE))
274 RetE = Cleanup->getSubExpr();
Jordan Rosec210cb72012-08-27 17:50:07 +0000275 if (isa<CXXConstructExpr>(RetE) && RetE->getType()->isRecordType())
276 return;
277
Devin Coughlina2892f02015-12-03 19:41:24 +0000278 // The CK_CopyAndAutoreleaseBlockObject cast causes the block to be copied
279 // so the stack address is not escaping here.
280 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetE)) {
281 if (isa<BlockDataRegion>(R) &&
282 ICE->getCastKind() == CK_CopyAndAutoreleaseBlockObject) {
283 return;
284 }
285 }
286
Ted Kremenek7e867832012-03-03 01:22:03 +0000287 EmitStackError(C, R, RetE);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000288}
Zhongxing Xu1622a542010-06-08 10:00:00 +0000289
Reka Kovacs3ad62f52018-07-16 20:47:45 +0000290void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
291 CheckerContext &Ctx) const {
Artem Dergachevbdf9e462017-12-12 02:59:09 +0000292 if (!ChecksEnabled[CK_StackAddrEscapeChecker])
293 return;
294
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000295 ProgramStateRef State = Ctx.getState();
Zhongxing Xu1622a542010-06-08 10:00:00 +0000296
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000297 // Iterate over all bindings to global variables and see if it contains
298 // a memory region in the stack space.
299 class CallBack : public StoreManager::BindingsHandler {
300 private:
Anna Zaksaf498a22011-10-25 19:56:48 +0000301 CheckerContext &Ctx;
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000302 const StackFrameContext *CurSFC;
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000303
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000304 public:
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000305 SmallVector<std::pair<const MemRegion *, const MemRegion *>, 10> V;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000306
George Karpenkov33876342018-06-27 01:51:55 +0000307 CallBack(CheckerContext &CC) : Ctx(CC), CurSFC(CC.getStackFrame()) {}
Ted Kremenek99bb39a2015-09-08 03:50:52 +0000308
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000309 bool HandleBinding(StoreManager &SMgr, Store S, const MemRegion *Region,
310 SVal Val) override {
Craig Topper83daac82014-03-15 04:29:04 +0000311
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000312 if (!isa<GlobalsSpaceRegion>(Region->getMemorySpace()))
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000313 return true;
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000314 const MemRegion *VR = Val.getAsRegion();
315 if (VR && isa<StackSpaceRegion>(VR->getMemorySpace()) &&
316 !isArcManagedBlock(VR, Ctx) && !isNotInCurrentFrame(VR, Ctx))
317 V.emplace_back(Region, VR);
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000318 return true;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000319 }
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000320 };
Ted Kremenek99bb39a2015-09-08 03:50:52 +0000321
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000322 CallBack Cb(Ctx);
323 State->getStateManager().getStoreManager().iterBindings(State->getStore(),
324 Cb);
Ted Kremeneka8166152010-06-17 04:21:37 +0000325
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000326 if (Cb.V.empty())
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000327 return;
328
329 // Generate an error node.
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000330 ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000331 if (!N)
332 return;
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000333
Ted Kremeneka8166152010-06-17 04:21:37 +0000334 if (!BT_stackleak)
Jonas Devlieghere49a6b092019-08-14 23:04:18 +0000335 BT_stackleak = std::make_unique<BuiltinBug>(
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000336 this, "Stack address stored into global variable",
337 "Stack address was saved into a global variable. "
338 "This is dangerous because the address will become "
339 "invalid after returning from the function");
Alexander Kornienko15c01b22014-02-11 21:49:21 +0000340
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000341 for (const auto &P : Cb.V) {
Ted Kremeneka8166152010-06-17 04:21:37 +0000342 // Generate a report for this bug.
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000343 SmallString<128> Buf;
344 llvm::raw_svector_ostream Out(Buf);
345 SourceRange Range = genName(Out, P.second, Ctx.getASTContext());
346 Out << " is still referred to by the ";
347 if (isa<StaticGlobalSpaceRegion>(P.first->getMemorySpace()))
348 Out << "static";
Sean Eveson2283ffc2016-05-26 14:02:17 +0000349 else
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000350 Out << "global";
351 Out << " variable '";
352 const VarRegion *VR = cast<VarRegion>(P.first->getBaseRegion());
353 Out << *VR->getDecl()
354 << "' upon returning to the caller. This will be a dangling reference";
Artem Dergachev9e6519f2019-09-09 20:34:40 +0000355 auto Report =
356 std::make_unique<PathSensitiveBugReport>(*BT_stackleak, Out.str(), N);
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000357 if (Range.isValid())
358 Report->addRange(Range);
Ted Kremeneka8166152010-06-17 04:21:37 +0000359
Alexander Shaposhnikov94ab6722017-11-20 22:53:30 +0000360 Ctx.emitReport(std::move(Report));
Ted Kremeneka8166152010-06-17 04:21:37 +0000361 }
Zhongxing Xu1622a542010-06-08 10:00:00 +0000362}
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000363
Kristof Umann0492ebd2019-01-26 20:06:54 +0000364void ento::registerStackAddrEscapeBase(CheckerManager &mgr) {
365 mgr.registerChecker<StackAddrEscapeChecker>();
366}
367
368bool ento::shouldRegisterStackAddrEscapeBase(const LangOptions &LO) {
369 return true;
370}
371
Kristof Umann8abad3c2019-01-26 21:41:50 +0000372#define REGISTER_CHECKER(name) \
373 void ento::register##name(CheckerManager &Mgr) { \
374 StackAddrEscapeChecker *Chk = \
375 Mgr.getChecker<StackAddrEscapeChecker>(); \
376 Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true; \
Kristof Umann9b220eb2019-01-26 14:23:08 +0000377 } \
378 \
379 bool ento::shouldRegister##name(const LangOptions &LO) { \
380 return true; \
Artem Dergachevbdf9e462017-12-12 02:59:09 +0000381 }
382
383REGISTER_CHECKER(StackAddrEscapeChecker)
384REGISTER_CHECKER(StackAddrAsyncEscapeChecker)