blob: 6a9a37d955bfba38aa7c3d7fa45b521fabcc09f2 [file] [log] [blame]
Ted Kremenekf5d2ef42011-02-25 22:00:43 +00001//=== StackAddrEscapeChecker.cpp ----------------------------------*- C++ -*--//
Zhongxing Xu1622a542010-06-08 10:00:00 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis027a6ab2011-02-15 07:42:33 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000016#include "clang/StaticAnalyzer/Core/CheckerV2.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000018#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h"
Zhongxing Xu9b146832010-06-09 06:08:24 +000021#include "clang/Basic/SourceManager.h"
22#include "llvm/ADT/SmallString.h"
Zhongxing Xu1622a542010-06-08 10:00:00 +000023using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000024using namespace ento;
Zhongxing Xu1622a542010-06-08 10:00:00 +000025
26namespace {
Ted Kremenekf5d2ef42011-02-25 22:00:43 +000027class StackAddrEscapeChecker : public CheckerV2< check::PreStmt<ReturnStmt>,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000028 check::EndPath > {
29 mutable llvm::OwningPtr<BuiltinBug> BT_stackleak;
30 mutable llvm::OwningPtr<BuiltinBug> BT_returnstack;
Zhongxing Xu1622a542010-06-08 10:00:00 +000031
32public:
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000033 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
34 void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
Zhongxing Xu9b146832010-06-09 06:08:24 +000035private:
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000036 void EmitStackError(CheckerContext &C, const MemRegion *R,
37 const Expr *RetE) const;
38 static SourceRange GenName(llvm::raw_ostream &os, const MemRegion *R,
39 SourceManager &SM);
Zhongxing Xu1622a542010-06-08 10:00:00 +000040};
41}
42
Ted Kremenekf5d2ef42011-02-25 22:00:43 +000043SourceRange StackAddrEscapeChecker::GenName(llvm::raw_ostream &os,
Ted Kremeneka8166152010-06-17 04:21:37 +000044 const MemRegion *R,
45 SourceManager &SM) {
46 // Get the base region, stripping away fields and elements.
47 R = R->getBaseRegion();
48 SourceRange range;
49 os << "Address of ";
50
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 "
55 "declared on line "
56 << SM.getInstantiationLineNumber(CL->getLocStart())
57 << " returned to caller";
58 range = CL->getSourceRange();
59 }
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.getInstantiationLineNumber(L);
66 }
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.getInstantiationLineNumber(L);
73 }
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();
78 }
79 else {
80 assert(false && "Invalid region in ReturnStackAddressChecker.");
81 }
82
83 return range;
84}
85
Ted Kremenekf5d2ef42011-02-25 22:00:43 +000086void StackAddrEscapeChecker::EmitStackError(CheckerContext &C, const MemRegion *R,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000087 const Expr *RetE) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +000088 ExplodedNode *N = C.generateSink();
Zhongxing Xu9b146832010-06-09 06:08:24 +000089
90 if (!N)
91 return;
92
93 if (!BT_returnstack)
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000094 BT_returnstack.reset(
95 new BuiltinBug("Return of address to stack-allocated memory"));
Zhongxing Xu9b146832010-06-09 06:08:24 +000096
97 // Generate a report for this bug.
98 llvm::SmallString<512> buf;
99 llvm::raw_svector_ostream os(buf);
Ted Kremeneka8166152010-06-17 04:21:37 +0000100 SourceRange range = GenName(os, R, C.getSourceManager());
101 os << " returned to caller";
Zhongxing Xu9b146832010-06-09 06:08:24 +0000102 RangedBugReport *report = new RangedBugReport(*BT_returnstack, os.str(), N);
103 report->addRange(RetE->getSourceRange());
104 if (range.isValid())
105 report->addRange(range);
106
107 C.EmitReport(report);
Eli Friedmana7e68452010-08-22 01:00:03 +0000108}
Zhongxing Xu9b146832010-06-09 06:08:24 +0000109
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000110void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000111 CheckerContext &C) const {
Zhongxing Xu9b146832010-06-09 06:08:24 +0000112
113 const Expr *RetE = RS->getRetValue();
114 if (!RetE)
115 return;
116
117 SVal V = C.getState()->getSVal(RetE);
118 const MemRegion *R = V.getAsRegion();
119
120 if (!R || !R->hasStackStorage())
121 return;
122
123 if (R->hasStackStorage()) {
124 EmitStackError(C, R, RetE);
125 return;
126 }
127}
Zhongxing Xu1622a542010-06-08 10:00:00 +0000128
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000129void StackAddrEscapeChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000130 ExprEngine &Eng) const {
Ted Kremenekba37d3b2011-01-13 04:36:40 +0000131
Zhongxing Xu1622a542010-06-08 10:00:00 +0000132 const GRState *state = B.getState();
Zhongxing Xu1622a542010-06-08 10:00:00 +0000133
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000134 // Iterate over all bindings to global variables and see if it contains
135 // a memory region in the stack space.
136 class CallBack : public StoreManager::BindingsHandler {
137 private:
138 const StackFrameContext *CurSFC;
139 public:
Ted Kremeneka8166152010-06-17 04:21:37 +0000140 llvm::SmallVector<std::pair<const MemRegion*, const MemRegion*>, 10> V;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000141
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000142 CallBack(const LocationContext *LCtx)
Ted Kremeneka8166152010-06-17 04:21:37 +0000143 : CurSFC(LCtx->getCurrentStackFrame()) {}
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000144
145 bool HandleBinding(StoreManager &SMgr, Store store,
146 const MemRegion *region, SVal val) {
147
148 if (!isa<GlobalsSpaceRegion>(region->getMemorySpace()))
149 return true;
150
151 const MemRegion *vR = val.getAsRegion();
152 if (!vR)
153 return true;
154
155 if (const StackSpaceRegion *SSR =
156 dyn_cast<StackSpaceRegion>(vR->getMemorySpace())) {
157 // If the global variable holds a location in the current stack frame,
158 // record the binding to emit a warning.
Ted Kremeneka8166152010-06-17 04:21:37 +0000159 if (SSR->getStackFrame() == CurSFC)
160 V.push_back(std::make_pair(region, vR));
Zhongxing Xu1622a542010-06-08 10:00:00 +0000161 }
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000162
163 return true;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000164 }
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000165 };
166
167 CallBack cb(B.getPredecessor()->getLocationContext());
168 state->getStateManager().getStoreManager().iterBindings(state->getStore(),cb);
Ted Kremeneka8166152010-06-17 04:21:37 +0000169
170 if (cb.V.empty())
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000171 return;
172
173 // Generate an error node.
Argyrios Kyrtzidisf178ac82011-02-23 21:04:49 +0000174 ExplodedNode *N = B.generateNode(state);
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000175 if (!N)
176 return;
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000177
Ted Kremeneka8166152010-06-17 04:21:37 +0000178 if (!BT_stackleak)
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000179 BT_stackleak.reset(
Ted Kremeneka8166152010-06-17 04:21:37 +0000180 new BuiltinBug("Stack address stored into global variable",
181 "Stack address was saved into a global variable. "
182 "This is dangerous because the address will become "
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000183 "invalid after returning from the function"));
Ted Kremeneka8166152010-06-17 04:21:37 +0000184
185 for (unsigned i = 0, e = cb.V.size(); i != e; ++i) {
186 // Generate a report for this bug.
187 llvm::SmallString<512> buf;
188 llvm::raw_svector_ostream os(buf);
189 SourceRange range = GenName(os, cb.V[i].second,
190 Eng.getContext().getSourceManager());
191 os << " is still referred to by the global variable '";
192 const VarRegion *VR = cast<VarRegion>(cb.V[i].first->getBaseRegion());
193 os << VR->getDecl()->getNameAsString()
194 << "' upon returning to the caller. This will be a dangling reference";
195 RangedBugReport *report = new RangedBugReport(*BT_stackleak, os.str(), N);
196 if (range.isValid())
197 report->addRange(range);
198
199 Eng.getBugReporter().EmitReport(report);
200 }
Zhongxing Xu1622a542010-06-08 10:00:00 +0000201}
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000202
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000203void ento::registerStackAddrEscapeChecker(CheckerManager &mgr) {
204 mgr.registerChecker<StackAddrEscapeChecker>();
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000205}