blob: 4fd778ef58ca941612d3a46af1432d66d6f5534a [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000019#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000020#include "clang/StaticAnalyzer/Core/CheckerManager.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 {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000029class StackAddrEscapeChecker : public Checker< check::PreStmt<ReturnStmt>,
Anna Zaks344c77a2013-01-03 00:25:29 +000030 check::EndFunction > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000031 mutable OwningPtr<BuiltinBug> BT_stackleak;
32 mutable OwningPtr<BuiltinBug> BT_returnstack;
Zhongxing Xu1622a542010-06-08 10:00:00 +000033
34public:
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000035 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +000036 void checkEndFunction(CheckerContext &Ctx) const;
Zhongxing Xu9b146832010-06-09 06:08:24 +000037private:
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000038 void EmitStackError(CheckerContext &C, const MemRegion *R,
39 const Expr *RetE) const;
Jordan Rosea0e6e6d2013-02-26 01:21:21 +000040 static SourceRange genName(raw_ostream &os, const MemRegion *R,
41 ASTContext &Ctx);
Zhongxing Xu1622a542010-06-08 10:00:00 +000042};
43}
44
Jordan Rosea0e6e6d2013-02-26 01:21:21 +000045SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion *R,
46 ASTContext &Ctx) {
Ted Kremeneka8166152010-06-17 04:21:37 +000047 // Get the base region, stripping away fields and elements.
48 R = R->getBaseRegion();
Jordan Rosea0e6e6d2013-02-26 01:21:21 +000049 SourceManager &SM = Ctx.getSourceManager();
Ted Kremeneka8166152010-06-17 04:21:37 +000050 SourceRange range;
51 os << "Address of ";
52
53 // Check if the region is a compound literal.
54 if (const CompoundLiteralRegion* CR = dyn_cast<CompoundLiteralRegion>(R)) {
Ted Kremenek9c378f72011-08-12 23:37:29 +000055 const CompoundLiteralExpr *CL = CR->getLiteralExpr();
Ted Kremeneka8166152010-06-17 04:21:37 +000056 os << "stack memory associated with a compound literal "
57 "declared on line "
Chandler Carruth64211622011-07-25 21:09:52 +000058 << SM.getExpansionLineNumber(CL->getLocStart())
Ted Kremeneka8166152010-06-17 04:21:37 +000059 << " returned to caller";
60 range = CL->getSourceRange();
61 }
62 else if (const AllocaRegion* AR = dyn_cast<AllocaRegion>(R)) {
Ted Kremenek9c378f72011-08-12 23:37:29 +000063 const Expr *ARE = AR->getExpr();
Ted Kremeneka8166152010-06-17 04:21:37 +000064 SourceLocation L = ARE->getLocStart();
65 range = ARE->getSourceRange();
66 os << "stack memory allocated by call to alloca() on line "
Chandler Carruth64211622011-07-25 21:09:52 +000067 << SM.getExpansionLineNumber(L);
Ted Kremeneka8166152010-06-17 04:21:37 +000068 }
69 else if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
70 const BlockDecl *BD = BR->getCodeRegion()->getDecl();
71 SourceLocation L = BD->getLocStart();
72 range = BD->getSourceRange();
73 os << "stack-allocated block declared on line "
Chandler Carruth64211622011-07-25 21:09:52 +000074 << SM.getExpansionLineNumber(L);
Ted Kremeneka8166152010-06-17 04:21:37 +000075 }
76 else if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
77 os << "stack memory associated with local variable '"
78 << VR->getString() << '\'';
79 range = VR->getDecl()->getSourceRange();
80 }
Jeffrey Yasskin782f63e2011-08-26 00:41:31 +000081 else if (const CXXTempObjectRegion *TOR = dyn_cast<CXXTempObjectRegion>(R)) {
Jordan Rosea0e6e6d2013-02-26 01:21:21 +000082 QualType Ty = TOR->getValueType().getLocalUnqualifiedType();
83 os << "stack memory associated with temporary object of type '";
84 Ty.print(os, Ctx.getPrintingPolicy());
85 os << "'";
Jeffrey Yasskin782f63e2011-08-26 00:41:31 +000086 range = TOR->getExpr()->getSourceRange();
87 }
Ted Kremeneka8166152010-06-17 04:21:37 +000088 else {
David Blaikieb219cfc2011-09-23 05:06:16 +000089 llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
Ted Kremeneka8166152010-06-17 04:21:37 +000090 }
91
92 return range;
93}
94
Ted Kremenekf5d2ef42011-02-25 22:00:43 +000095void StackAddrEscapeChecker::EmitStackError(CheckerContext &C, const MemRegion *R,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000096 const Expr *RetE) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +000097 ExplodedNode *N = C.generateSink();
Zhongxing Xu9b146832010-06-09 06:08:24 +000098
99 if (!N)
100 return;
101
102 if (!BT_returnstack)
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000103 BT_returnstack.reset(
104 new BuiltinBug("Return of address to stack-allocated memory"));
Zhongxing Xu9b146832010-06-09 06:08:24 +0000105
106 // Generate a report for this bug.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000107 SmallString<512> buf;
Zhongxing Xu9b146832010-06-09 06:08:24 +0000108 llvm::raw_svector_ostream os(buf);
Jordan Rosea0e6e6d2013-02-26 01:21:21 +0000109 SourceRange range = genName(os, R, C.getASTContext());
Ted Kremeneka8166152010-06-17 04:21:37 +0000110 os << " returned to caller";
Anna Zakse172e8b2011-08-17 23:00:25 +0000111 BugReport *report = new BugReport(*BT_returnstack, os.str(), N);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000112 report->addRange(RetE->getSourceRange());
113 if (range.isValid())
114 report->addRange(range);
115
Jordan Rose785950e2012-11-02 01:53:40 +0000116 C.emitReport(report);
Eli Friedmana7e68452010-08-22 01:00:03 +0000117}
Zhongxing Xu9b146832010-06-09 06:08:24 +0000118
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000119void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
Ted Kremenek7e867832012-03-03 01:22:03 +0000120 CheckerContext &C) const {
Zhongxing Xu9b146832010-06-09 06:08:24 +0000121
122 const Expr *RetE = RS->getRetValue();
123 if (!RetE)
124 return;
Jordan Rose73212df2012-08-29 01:11:59 +0000125 RetE = RetE->IgnoreParens();
Jordan Rosec210cb72012-08-27 17:50:07 +0000126
127 const LocationContext *LCtx = C.getLocationContext();
128 SVal V = C.getState()->getSVal(RetE, LCtx);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000129 const MemRegion *R = V.getAsRegion();
130
Ted Kremenek7e867832012-03-03 01:22:03 +0000131 if (!R)
Zhongxing Xu9b146832010-06-09 06:08:24 +0000132 return;
Ted Kremenek7e867832012-03-03 01:22:03 +0000133
134 const StackSpaceRegion *SS =
135 dyn_cast_or_null<StackSpaceRegion>(R->getMemorySpace());
136
137 if (!SS)
138 return;
139
140 // Return stack memory in an ancestor stack frame is fine.
Jordan Rosec210cb72012-08-27 17:50:07 +0000141 const StackFrameContext *CurFrame = LCtx->getCurrentStackFrame();
142 const StackFrameContext *MemFrame = SS->getStackFrame();
143 if (MemFrame != CurFrame)
Ted Kremenek7e867832012-03-03 01:22:03 +0000144 return;
145
146 // Automatic reference counting automatically copies blocks.
David Blaikie4e4d0842012-03-11 07:00:24 +0000147 if (C.getASTContext().getLangOpts().ObjCAutoRefCount &&
Ted Kremenek7e867832012-03-03 01:22:03 +0000148 isa<BlockDataRegion>(R))
149 return;
150
Jordan Rosec210cb72012-08-27 17:50:07 +0000151 // Returning a record by value is fine. (In this case, the returned
Jordan Rose73212df2012-08-29 01:11:59 +0000152 // expression will be a copy-constructor, possibly wrapped in an
153 // ExprWithCleanups node.)
154 if (const ExprWithCleanups *Cleanup = dyn_cast<ExprWithCleanups>(RetE))
155 RetE = Cleanup->getSubExpr();
Jordan Rosec210cb72012-08-27 17:50:07 +0000156 if (isa<CXXConstructExpr>(RetE) && RetE->getType()->isRecordType())
157 return;
158
Ted Kremenek7e867832012-03-03 01:22:03 +0000159 EmitStackError(C, R, RetE);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000160}
Zhongxing Xu1622a542010-06-08 10:00:00 +0000161
Anna Zaks344c77a2013-01-03 00:25:29 +0000162void StackAddrEscapeChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000163 ProgramStateRef state = Ctx.getState();
Zhongxing Xu1622a542010-06-08 10:00:00 +0000164
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000165 // Iterate over all bindings to global variables and see if it contains
166 // a memory region in the stack space.
167 class CallBack : public StoreManager::BindingsHandler {
168 private:
Anna Zaksaf498a22011-10-25 19:56:48 +0000169 CheckerContext &Ctx;
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000170 const StackFrameContext *CurSFC;
171 public:
Chris Lattner5f9e2722011-07-23 10:55:15 +0000172 SmallVector<std::pair<const MemRegion*, const MemRegion*>, 10> V;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000173
Anna Zaksaf498a22011-10-25 19:56:48 +0000174 CallBack(CheckerContext &CC) :
175 Ctx(CC),
Anna Zaks39ac1872011-10-26 21:06:44 +0000176 CurSFC(CC.getLocationContext()->getCurrentStackFrame())
Anna Zaksaf498a22011-10-25 19:56:48 +0000177 {}
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000178
179 bool HandleBinding(StoreManager &SMgr, Store store,
180 const MemRegion *region, SVal val) {
181
182 if (!isa<GlobalsSpaceRegion>(region->getMemorySpace()))
183 return true;
184
185 const MemRegion *vR = val.getAsRegion();
186 if (!vR)
187 return true;
John McCallf85e1932011-06-15 23:02:42 +0000188
189 // Under automated retain release, it is okay to assign a block
190 // directly to a global variable.
David Blaikie4e4d0842012-03-11 07:00:24 +0000191 if (Ctx.getASTContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000192 isa<BlockDataRegion>(vR))
193 return true;
194
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000195 if (const StackSpaceRegion *SSR =
196 dyn_cast<StackSpaceRegion>(vR->getMemorySpace())) {
197 // If the global variable holds a location in the current stack frame,
198 // record the binding to emit a warning.
Ted Kremeneka8166152010-06-17 04:21:37 +0000199 if (SSR->getStackFrame() == CurSFC)
200 V.push_back(std::make_pair(region, vR));
Zhongxing Xu1622a542010-06-08 10:00:00 +0000201 }
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000202
203 return true;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000204 }
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000205 };
206
Anna Zaksaf498a22011-10-25 19:56:48 +0000207 CallBack cb(Ctx);
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000208 state->getStateManager().getStoreManager().iterBindings(state->getStore(),cb);
Ted Kremeneka8166152010-06-17 04:21:37 +0000209
210 if (cb.V.empty())
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000211 return;
212
213 // Generate an error node.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000214 ExplodedNode *N = Ctx.addTransition(state);
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000215 if (!N)
216 return;
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000217
Ted Kremeneka8166152010-06-17 04:21:37 +0000218 if (!BT_stackleak)
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000219 BT_stackleak.reset(
Ted Kremeneka8166152010-06-17 04:21:37 +0000220 new BuiltinBug("Stack address stored into global variable",
221 "Stack address was saved into a global variable. "
222 "This is dangerous because the address will become "
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000223 "invalid after returning from the function"));
Ted Kremeneka8166152010-06-17 04:21:37 +0000224
225 for (unsigned i = 0, e = cb.V.size(); i != e; ++i) {
226 // Generate a report for this bug.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000227 SmallString<512> buf;
Ted Kremeneka8166152010-06-17 04:21:37 +0000228 llvm::raw_svector_ostream os(buf);
Jordan Rosea0e6e6d2013-02-26 01:21:21 +0000229 SourceRange range = genName(os, cb.V[i].second, Ctx.getASTContext());
Ted Kremeneka8166152010-06-17 04:21:37 +0000230 os << " is still referred to by the global variable '";
231 const VarRegion *VR = cast<VarRegion>(cb.V[i].first->getBaseRegion());
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000232 os << *VR->getDecl()
Ted Kremeneka8166152010-06-17 04:21:37 +0000233 << "' upon returning to the caller. This will be a dangling reference";
Anna Zakse172e8b2011-08-17 23:00:25 +0000234 BugReport *report = new BugReport(*BT_stackleak, os.str(), N);
Ted Kremeneka8166152010-06-17 04:21:37 +0000235 if (range.isValid())
236 report->addRange(range);
237
Jordan Rose785950e2012-11-02 01:53:40 +0000238 Ctx.emitReport(report);
Ted Kremeneka8166152010-06-17 04:21:37 +0000239 }
Zhongxing Xu1622a542010-06-08 10:00:00 +0000240}
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000241
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000242void ento::registerStackAddrEscapeChecker(CheckerManager &mgr) {
243 mgr.registerChecker<StackAddrEscapeChecker>();
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000244}