23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/Support/raw_ostream.h" 25 using namespace clang;
29 class StackAddrEscapeChecker
30 :
public Checker<check::PreCall, check::PreStmt<ReturnStmt>,
33 mutable std::unique_ptr<BuiltinBug> BT_stackleak;
34 mutable std::unique_ptr<BuiltinBug> BT_returnstack;
35 mutable std::unique_ptr<BuiltinBug> BT_capturedstackasync;
36 mutable std::unique_ptr<BuiltinBug> BT_capturedstackret;
40 CK_StackAddrEscapeChecker,
41 CK_StackAddrAsyncEscapeChecker,
45 DefaultBool ChecksEnabled[CK_NumCheckKinds];
47 void checkPreCall(
const CallEvent &Call, CheckerContext &C)
const;
48 void checkPreStmt(
const ReturnStmt *RS, CheckerContext &C)
const;
49 void checkEndFunction(
const ReturnStmt *RS, CheckerContext &Ctx)
const;
52 void checkReturnedBlockCaptures(
const BlockDataRegion &B,
53 CheckerContext &C)
const;
54 void checkAsyncExecutedBlockCaptures(
const BlockDataRegion &B,
55 CheckerContext &C)
const;
56 void EmitStackError(CheckerContext &C,
const MemRegion *R,
57 const Expr *RetE)
const;
58 bool isSemaphoreCaptured(
const BlockDecl &B)
const;
59 static SourceRange genName(raw_ostream &os,
const MemRegion *R,
61 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);
68 SourceRange StackAddrEscapeChecker::genName(raw_ostream &os,
const MemRegion *R,
71 R = R->getBaseRegion();
77 if (
const auto *CR = dyn_cast<CompoundLiteralRegion>(R)) {
79 os <<
"stack memory associated with a compound literal " 83 }
else if (
const auto *AR = dyn_cast<AllocaRegion>(R)) {
84 const Expr *ARE = AR->getExpr();
87 os <<
"stack memory allocated by call to alloca() on line " 89 }
else if (
const auto *BR = dyn_cast<BlockDataRegion>(R)) {
90 const BlockDecl *BD = BR->getCodeRegion()->getDecl();
93 os <<
"stack-allocated block declared on line " 95 }
else if (
const auto *VR = dyn_cast<VarRegion>(R)) {
96 os <<
"stack memory associated with local variable '" << VR->getString()
98 range = VR->getDecl()->getSourceRange();
99 }
else if (
const auto *TOR = dyn_cast<CXXTempObjectRegion>(R)) {
100 QualType Ty = TOR->getValueType().getLocalUnqualifiedType();
101 os <<
"stack memory associated with temporary object of type '";
104 range = TOR->getExpr()->getSourceRange();
106 llvm_unreachable(
"Invalid region in ReturnStackAddressChecker.");
112 bool StackAddrEscapeChecker::isArcManagedBlock(
const MemRegion *R,
114 assert(R &&
"MemRegion should not be null");
115 return C.getASTContext().getLangOpts().ObjCAutoRefCount &&
116 isa<BlockDataRegion>(R);
119 bool StackAddrEscapeChecker::isNotInCurrentFrame(
const MemRegion *R,
121 const StackSpaceRegion *S = cast<StackSpaceRegion>(R->getMemorySpace());
122 return S->getStackFrame() != C.getStackFrame();
125 bool StackAddrEscapeChecker::isSemaphoreCaptured(
const BlockDecl &B)
const {
126 if (!dispatch_semaphore_tII)
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)
136 SmallVector<const MemRegion *, 4>
137 StackAddrEscapeChecker::getCapturedStackRegions(
const BlockDataRegion &B,
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);
151 void StackAddrEscapeChecker::EmitStackError(CheckerContext &C,
153 const Expr *RetE)
const {
154 ExplodedNode *N = C.generateNonFatalErrorNode();
158 BT_returnstack = llvm::make_unique<BuiltinBug>(
159 this,
"Return of address to stack-allocated memory");
162 llvm::raw_svector_ostream os(buf);
163 SourceRange range = genName(os, R, C.getASTContext());
164 os <<
" returned to caller";
165 auto report = llvm::make_unique<BugReport>(*BT_returnstack, os.str(), N);
168 report->addRange(range);
169 C.emitReport(std::move(report));
172 void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures(
173 const BlockDataRegion &B, CheckerContext &C)
const {
181 if (isSemaphoreCaptured(*B.getDecl()))
183 for (
const MemRegion *Region : getCapturedStackRegions(B, C)) {
190 if (isa<BlockDataRegion>(Region))
192 ExplodedNode *N = C.generateNonFatalErrorNode();
195 if (!BT_capturedstackasync)
196 BT_capturedstackasync = llvm::make_unique<BuiltinBug>(
197 this,
"Address of stack-allocated memory is captured");
199 llvm::raw_svector_ostream Out(Buf);
200 SourceRange Range = genName(Out, Region, C.getASTContext());
201 Out <<
" is captured by an asynchronously-executed block";
203 llvm::make_unique<BugReport>(*BT_capturedstackasync, Out.str(), N);
205 Report->addRange(Range);
206 C.emitReport(std::move(Report));
210 void StackAddrEscapeChecker::checkReturnedBlockCaptures(
211 const BlockDataRegion &B, CheckerContext &C)
const {
212 for (
const MemRegion *Region : getCapturedStackRegions(B, C)) {
213 if (isArcManagedBlock(Region, C) || isNotInCurrentFrame(Region, C))
215 ExplodedNode *N = C.generateNonFatalErrorNode();
218 if (!BT_capturedstackret)
219 BT_capturedstackret = llvm::make_unique<BuiltinBug>(
220 this,
"Address of stack-allocated memory is captured");
222 llvm::raw_svector_ostream Out(Buf);
223 SourceRange Range = genName(Out, Region, C.getASTContext());
224 Out <<
" is captured by a returned block";
226 llvm::make_unique<BugReport>(*BT_capturedstackret, Out.str(), N);
228 Report->addRange(Range);
229 C.emitReport(std::move(Report));
233 void StackAddrEscapeChecker::checkPreCall(
const CallEvent &Call,
234 CheckerContext &C)
const {
235 if (!ChecksEnabled[CK_StackAddrAsyncEscapeChecker])
237 if (!Call.isGlobalCFunction(
"dispatch_after") &&
238 !Call.isGlobalCFunction(
"dispatch_async"))
240 for (
unsigned Idx = 0, NumArgs = Call.getNumArgs(); Idx < NumArgs; ++Idx) {
241 if (
const BlockDataRegion *B = dyn_cast_or_null<BlockDataRegion>(
242 Call.getArgSVal(Idx).getAsRegion()))
243 checkAsyncExecutedBlockCaptures(*B, C);
247 void StackAddrEscapeChecker::checkPreStmt(
const ReturnStmt *RS,
248 CheckerContext &C)
const {
249 if (!ChecksEnabled[CK_StackAddrEscapeChecker])
257 SVal
V = C.getSVal(RetE);
258 const MemRegion *R = V.getAsRegion();
262 if (
const BlockDataRegion *B = dyn_cast<BlockDataRegion>(R))
263 checkReturnedBlockCaptures(*B, C);
265 if (!isa<StackSpaceRegion>(R->getMemorySpace()) ||
266 isNotInCurrentFrame(R, C) || isArcManagedBlock(R, C))
273 RetE = Cleanup->getSubExpr();
279 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(RetE)) {
280 if (isa<BlockDataRegion>(R) &&
281 ICE->getCastKind() == CK_CopyAndAutoreleaseBlockObject) {
286 EmitStackError(C, R, RetE);
289 void StackAddrEscapeChecker::checkEndFunction(
const ReturnStmt *RS,
290 CheckerContext &Ctx)
const {
291 if (!ChecksEnabled[CK_StackAddrEscapeChecker])
298 class CallBack :
public StoreManager::BindingsHandler {
304 SmallVector<std::pair<const MemRegion *, const MemRegion *>, 10>
V;
306 CallBack(CheckerContext &CC) : Ctx(CC), CurSFC(CC.getStackFrame()) {}
308 bool HandleBinding(StoreManager &SMgr,
Store S,
const MemRegion *Region,
311 if (!isa<GlobalsSpaceRegion>(Region->getMemorySpace()))
313 const MemRegion *VR = Val.getAsRegion();
314 if (VR && isa<StackSpaceRegion>(VR->getMemorySpace()) &&
315 !isArcManagedBlock(VR, Ctx) && !isNotInCurrentFrame(VR, Ctx))
316 V.emplace_back(Region, VR);
322 State->getStateManager().getStoreManager().iterBindings(State->getStore(),
329 ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
334 BT_stackleak = llvm::make_unique<BuiltinBug>(
335 this,
"Stack address stored into global variable",
336 "Stack address was saved into a global variable. " 337 "This is dangerous because the address will become " 338 "invalid after returning from the function");
340 for (
const auto &
P : Cb.V) {
343 llvm::raw_svector_ostream Out(Buf);
344 SourceRange Range = genName(Out,
P.second, Ctx.getASTContext());
345 Out <<
" is still referred to by the ";
346 if (isa<StaticGlobalSpaceRegion>(
P.first->getMemorySpace()))
350 Out <<
" variable '";
351 const VarRegion *VR = cast<VarRegion>(
P.first->getBaseRegion());
352 Out << *VR->getDecl()
353 <<
"' upon returning to the caller. This will be a dangling reference";
354 auto Report = llvm::make_unique<BugReport>(*BT_stackleak, Out.str(), N);
356 Report->addRange(Range);
358 Ctx.emitReport(std::move(Report));
362 void ento::registerStackAddrEscapeBase(CheckerManager &mgr) {
363 mgr.registerChecker<StackAddrEscapeChecker>();
366 bool ento::shouldRegisterStackAddrEscapeBase(
const LangOptions &LO) {
370 #define REGISTER_CHECKER(name) \ 371 void ento::register##name(CheckerManager &Mgr) { \ 372 StackAddrEscapeChecker *Chk = \ 373 Mgr.getChecker<StackAddrEscapeChecker>(); \ 374 Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true; \ 377 bool ento::shouldRegister##name(const LangOptions &LO) { \
A (possibly-)qualified type.
Defines the SourceManager interface.
bool isRecordType() const
SourceLocation getBeginLoc() const LLVM_READONLY
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
CompoundLiteralExpr - [C99 6.5.2.5].
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Defines the clang::Expr interface and subclasses for C++ expressions.
SourceLocation getBeginLoc() const LLVM_READONLY
One of these records is kept for each identifier that is lexed.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceLocation getBeginLoc() const LLVM_READONLY
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
const clang::PrintingPolicy & getPrintingPolicy() const
Represents a block literal declaration, which is like an unnamed FunctionDecl.
This represents one expression.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ASTContext & getASTContext() const LLVM_READONLY
#define REGISTER_CHECKER(name)
Dataflow Directional Tag Classes.
ArrayRef< Capture > captures() const
SourceManager & getSourceManager()
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
A trivial tuple used to represent a source range.
This class handles loading and caching of source files into memory.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...