24 #include "llvm/ADT/SmallString.h" 25 #include "llvm/Support/raw_ostream.h" 26 using namespace clang;
30 class StackAddrEscapeChecker
31 :
public Checker<check::PreCall, check::PreStmt<ReturnStmt>,
34 mutable std::unique_ptr<BuiltinBug> BT_stackleak;
35 mutable std::unique_ptr<BuiltinBug> BT_returnstack;
36 mutable std::unique_ptr<BuiltinBug> BT_capturedstackasync;
37 mutable std::unique_ptr<BuiltinBug> BT_capturedstackret;
41 CK_StackAddrEscapeChecker,
42 CK_StackAddrAsyncEscapeChecker,
58 const Expr *RetE)
const;
59 bool isSemaphoreCaptured(
const BlockDecl &B)
const;
78 if (
const auto *CR = dyn_cast<CompoundLiteralRegion>(R)) {
80 os <<
"stack memory associated with a compound literal " 84 }
else if (
const auto *AR = dyn_cast<AllocaRegion>(R)) {
85 const Expr *ARE = AR->getExpr();
88 os <<
"stack memory allocated by call to alloca() on line " 90 }
else if (
const auto *BR = dyn_cast<BlockDataRegion>(R)) {
91 const BlockDecl *BD = BR->getCodeRegion()->getDecl();
94 os <<
"stack-allocated block declared on line " 96 }
else if (
const auto *VR = dyn_cast<VarRegion>(R)) {
97 os <<
"stack memory associated with local variable '" << VR->getString()
99 range = VR->getDecl()->getSourceRange();
100 }
else if (
const auto *TOR = dyn_cast<CXXTempObjectRegion>(R)) {
101 QualType Ty = TOR->getValueType().getLocalUnqualifiedType();
102 os <<
"stack memory associated with temporary object of type '";
105 range = TOR->getExpr()->getSourceRange();
107 llvm_unreachable(
"Invalid region in ReturnStackAddressChecker.");
113 bool StackAddrEscapeChecker::isArcManagedBlock(
const MemRegion *R,
115 assert(R &&
"MemRegion should not be null");
117 isa<BlockDataRegion>(R);
120 bool StackAddrEscapeChecker::isNotInCurrentFrame(
const MemRegion *R,
126 bool StackAddrEscapeChecker::isSemaphoreCaptured(
const BlockDecl &B)
const {
127 if (!dispatch_semaphore_tII)
129 for (
const auto &C : B.
captures()) {
130 const auto *T = C.getVariable()->getType()->getAs<
TypedefType>();
131 if (T && T->getDecl()->getIdentifier() == dispatch_semaphore_tII)
138 StackAddrEscapeChecker::getCapturedStackRegions(
const BlockDataRegion &B,
143 for (; I != E; ++I) {
147 Regions.push_back(Region);
154 const Expr *RetE)
const {
159 BT_returnstack = llvm::make_unique<BuiltinBug>(
160 this,
"Return of address to stack-allocated memory");
163 llvm::raw_svector_ostream os(buf);
165 os <<
" returned to caller";
166 auto report = llvm::make_unique<BugReport>(*BT_returnstack, os.str(), N);
169 report->addRange(range);
173 void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures(
182 if (isSemaphoreCaptured(*B.
getDecl()))
184 for (
const MemRegion *Region : getCapturedStackRegions(B, C)) {
191 if (isa<BlockDataRegion>(Region))
196 if (!BT_capturedstackasync)
197 BT_capturedstackasync = llvm::make_unique<BuiltinBug>(
198 this,
"Address of stack-allocated memory is captured");
200 llvm::raw_svector_ostream Out(Buf);
202 Out <<
" is captured by an asynchronously-executed block";
204 llvm::make_unique<BugReport>(*BT_capturedstackasync, Out.str(), N);
206 Report->addRange(Range);
211 void StackAddrEscapeChecker::checkReturnedBlockCaptures(
213 for (
const MemRegion *Region : getCapturedStackRegions(B, C)) {
214 if (isArcManagedBlock(Region, C) || isNotInCurrentFrame(Region, C))
219 if (!BT_capturedstackret)
220 BT_capturedstackret = llvm::make_unique<BuiltinBug>(
221 this,
"Address of stack-allocated memory is captured");
223 llvm::raw_svector_ostream Out(Buf);
225 Out <<
" is captured by a returned block";
227 llvm::make_unique<BugReport>(*BT_capturedstackret, Out.str(), N);
229 Report->addRange(Range);
234 void StackAddrEscapeChecker::checkPreCall(
const CallEvent &Call,
236 if (!ChecksEnabled[CK_StackAddrAsyncEscapeChecker])
241 for (
unsigned Idx = 0, NumArgs = Call.
getNumArgs(); Idx < NumArgs; ++Idx) {
244 checkAsyncExecutedBlockCaptures(*B, C);
248 void StackAddrEscapeChecker::checkPreStmt(
const ReturnStmt *RS,
250 if (!ChecksEnabled[CK_StackAddrEscapeChecker])
264 checkReturnedBlockCaptures(*B, C);
267 isNotInCurrentFrame(R, C) || isArcManagedBlock(R, C))
274 RetE = Cleanup->getSubExpr();
280 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(RetE)) {
281 if (isa<BlockDataRegion>(R) &&
282 ICE->getCastKind() == CK_CopyAndAutoreleaseBlockObject) {
287 EmitStackError(C, R, RetE);
290 void StackAddrEscapeChecker::checkEndFunction(
const ReturnStmt *RS,
292 if (!ChecksEnabled[CK_StackAddrEscapeChecker])
307 CallBack(
CheckerContext &CC) : Ctx(CC), CurSFC(CC.getStackFrame()) {}
316 !isArcManagedBlock(VR, Ctx) && !isNotInCurrentFrame(VR, Ctx))
317 V.emplace_back(Region, VR);
323 State->getStateManager().getStoreManager().iterBindings(State->getStore(),
335 BT_stackleak = llvm::make_unique<BuiltinBug>(
336 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");
341 for (
const auto &
P : Cb.V) {
344 llvm::raw_svector_ostream Out(Buf);
346 Out <<
" is still referred to by the ";
347 if (isa<StaticGlobalSpaceRegion>(
P.first->getMemorySpace()))
351 Out <<
" variable '";
352 const VarRegion *VR = cast<VarRegion>(
P.first->getBaseRegion());
354 <<
"' upon returning to the caller. This will be a dangling reference";
355 auto Report = llvm::make_unique<BugReport>(*BT_stackleak, Out.str(), N);
357 Report->addRange(Range);
363 #define REGISTER_CHECKER(name) \ 364 void ento::register##name(CheckerManager &Mgr) { \ 365 StackAddrEscapeChecker *Chk = \ 366 Mgr.registerChecker<StackAddrEscapeChecker>(); \ 367 Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true; \ A (possibly-)qualified type.
MemRegion - The root abstract class for all memory regions.
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
A helper class which wraps a boolean value set to false by default.
Defines the SourceManager interface.
bool isRecordType() const
A Range represents the closed range [from, to].
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 ...
SVal getSVal(const Stmt *S) const
Get the value of arbitrary expressions at this point in the path.
Defines the clang::Expr interface and subclasses for C++ expressions.
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 ...
const Expr * getRetValue() const
BlockDataRegion - A region that represents a block instance.
const clang::PrintingPolicy & getPrintingPolicy() const
referenced_vars_iterator referenced_vars_end() const
const MemSpaceRegion * getMemorySpace() const
const VarRegion * getCapturedRegion() const
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Expr - This represents one expression.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
ExplodedNode * generateNonFatalErrorNode(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a transition to a node that will be used to report an error.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
const StackFrameContext * getStackFrame() const
const VarDecl * getDecl() const
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
SourceLocation getLocStart() const LLVM_READONLY
SourceLocation getLocStart() const LLVM_READONLY
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
const MemRegion * getAsRegion() const
ASTContext & getASTContext() const LLVM_READONLY
SourceLocation getLocStart() const LLVM_READONLY
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
referenced_vars_iterator referenced_vars_begin() const
#define REGISTER_CHECKER(name)
Dataflow Directional Tag Classes.
ASTContext & getASTContext()
ArrayRef< Capture > captures() const
Represents an abstract call to a function or method along a particular path.
const StackFrameContext * getStackFrame() const
const ProgramStateRef & getState() const
bool isGlobalCFunction(StringRef SpecificName=StringRef()) const
Returns true if the callee is an externally-visible function in the top-level namespace, such as malloc.
SourceManager & getSourceManager()
const BlockDecl * getDecl() const
virtual unsigned getNumArgs() const =0
Returns the number of arguments (explicit and implicit).
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
const MemRegion * getBaseRegion() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
A trivial tuple used to represent a source range.
const LangOptions & getLangOpts() const
This class handles loading and caching of source files into memory.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.