1 //=== StackAddrEscapeChecker.cpp ----------------------------------*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines stack address leak checker, which checks if an invalid
11 // stack address is stored into a global or heap location. See CERT DCL30-C.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "llvm/ADT/SmallString.h"
23 using namespace clang;
27 class StackAddrEscapeChecker : public Checker< check::PreStmt<ReturnStmt>,
29 mutable llvm::OwningPtr<BuiltinBug> BT_stackleak;
30 mutable llvm::OwningPtr<BuiltinBug> BT_returnstack;
33 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
34 void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
36 void EmitStackError(CheckerContext &C, const MemRegion *R,
37 const Expr *RetE) const;
38 static SourceRange GenName(raw_ostream &os, const MemRegion *R,
43 SourceRange StackAddrEscapeChecker::GenName(raw_ostream &os,
46 // Get the base region, stripping away fields and elements.
47 R = R->getBaseRegion();
51 // Check if the region is a compound literal.
52 if (const CompoundLiteralRegion* CR = dyn_cast<CompoundLiteralRegion>(R)) {
53 const CompoundLiteralExpr *CL = CR->getLiteralExpr();
54 os << "stack memory associated with a compound literal "
56 << SM.getExpansionLineNumber(CL->getLocStart())
57 << " returned to caller";
58 range = CL->getSourceRange();
60 else if (const AllocaRegion* AR = dyn_cast<AllocaRegion>(R)) {
61 const Expr *ARE = AR->getExpr();
62 SourceLocation L = ARE->getLocStart();
63 range = ARE->getSourceRange();
64 os << "stack memory allocated by call to alloca() on line "
65 << SM.getExpansionLineNumber(L);
67 else if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
68 const BlockDecl *BD = BR->getCodeRegion()->getDecl();
69 SourceLocation L = BD->getLocStart();
70 range = BD->getSourceRange();
71 os << "stack-allocated block declared on line "
72 << SM.getExpansionLineNumber(L);
74 else if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
75 os << "stack memory associated with local variable '"
76 << VR->getString() << '\'';
77 range = VR->getDecl()->getSourceRange();
79 else if (const CXXTempObjectRegion *TOR = dyn_cast<CXXTempObjectRegion>(R)) {
80 os << "stack memory associated with temporary object of type '"
81 << TOR->getValueType().getAsString() << '\'';
82 range = TOR->getExpr()->getSourceRange();
85 llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
91 void StackAddrEscapeChecker::EmitStackError(CheckerContext &C, const MemRegion *R,
92 const Expr *RetE) const {
93 ExplodedNode *N = C.generateSink();
100 new BuiltinBug("Return of address to stack-allocated memory"));
102 // Generate a report for this bug.
103 llvm::SmallString<512> buf;
104 llvm::raw_svector_ostream os(buf);
105 SourceRange range = GenName(os, R, C.getSourceManager());
106 os << " returned to caller";
107 BugReport *report = new BugReport(*BT_returnstack, os.str(), N);
108 report->addRange(RetE->getSourceRange());
110 report->addRange(range);
112 C.EmitReport(report);
115 void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
116 CheckerContext &C) const {
118 const Expr *RetE = RS->getRetValue();
122 SVal V = C.getState()->getSVal(RetE);
123 const MemRegion *R = V.getAsRegion();
125 if (!R || !R->hasStackStorage())
128 if (R->hasStackStorage()) {
129 // Automatic reference counting automatically copies blocks.
130 if (C.getASTContext().getLangOptions().ObjCAutoRefCount &&
131 isa<BlockDataRegion>(R))
134 EmitStackError(C, R, RetE);
139 void StackAddrEscapeChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
140 ExprEngine &Eng) const {
142 const ProgramState *state = B.getState();
144 // Iterate over all bindings to global variables and see if it contains
145 // a memory region in the stack space.
146 class CallBack : public StoreManager::BindingsHandler {
149 const StackFrameContext *CurSFC;
151 SmallVector<std::pair<const MemRegion*, const MemRegion*>, 10> V;
153 CallBack(ExprEngine &Eng, const LocationContext *LCtx)
154 : Eng(Eng), CurSFC(LCtx->getCurrentStackFrame()) {}
156 bool HandleBinding(StoreManager &SMgr, Store store,
157 const MemRegion *region, SVal val) {
159 if (!isa<GlobalsSpaceRegion>(region->getMemorySpace()))
162 const MemRegion *vR = val.getAsRegion();
166 // Under automated retain release, it is okay to assign a block
167 // directly to a global variable.
168 if (Eng.getContext().getLangOptions().ObjCAutoRefCount &&
169 isa<BlockDataRegion>(vR))
172 if (const StackSpaceRegion *SSR =
173 dyn_cast<StackSpaceRegion>(vR->getMemorySpace())) {
174 // If the global variable holds a location in the current stack frame,
175 // record the binding to emit a warning.
176 if (SSR->getStackFrame() == CurSFC)
177 V.push_back(std::make_pair(region, vR));
184 CallBack cb(Eng, B.getPredecessor()->getLocationContext());
185 state->getStateManager().getStoreManager().iterBindings(state->getStore(),cb);
190 // Generate an error node.
191 ExplodedNode *N = B.generateNode(state);
197 new BuiltinBug("Stack address stored into global variable",
198 "Stack address was saved into a global variable. "
199 "This is dangerous because the address will become "
200 "invalid after returning from the function"));
202 for (unsigned i = 0, e = cb.V.size(); i != e; ++i) {
203 // Generate a report for this bug.
204 llvm::SmallString<512> buf;
205 llvm::raw_svector_ostream os(buf);
206 SourceRange range = GenName(os, cb.V[i].second,
207 Eng.getContext().getSourceManager());
208 os << " is still referred to by the global variable '";
209 const VarRegion *VR = cast<VarRegion>(cb.V[i].first->getBaseRegion());
211 << "' upon returning to the caller. This will be a dangling reference";
212 BugReport *report = new BugReport(*BT_stackleak, os.str(), N);
214 report->addRange(range);
216 Eng.getBugReporter().EmitReport(report);
220 void ento::registerStackAddrEscapeChecker(CheckerManager &mgr) {
221 mgr.registerChecker<StackAddrEscapeChecker>();