blob: b1f4f623e29b00e2d7f54aeef407accf09a787aa [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 Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.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 Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.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 {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000027class StackAddrEscapeChecker : public Checker< check::PreStmt<ReturnStmt>,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000028 check::EndPath > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000029 mutable OwningPtr<BuiltinBug> BT_stackleak;
30 mutable 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;
Anna Zaksaf498a22011-10-25 19:56:48 +000034 void checkEndPath(CheckerContext &Ctx) 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;
Chris Lattner5f9e2722011-07-23 10:55:15 +000038 static SourceRange GenName(raw_ostream &os, const MemRegion *R,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000039 SourceManager &SM);
Zhongxing Xu1622a542010-06-08 10:00:00 +000040};
41}
42
Chris Lattner5f9e2722011-07-23 10:55:15 +000043SourceRange StackAddrEscapeChecker::GenName(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)) {
Ted Kremenek9c378f72011-08-12 23:37:29 +000053 const CompoundLiteralExpr *CL = CR->getLiteralExpr();
Ted Kremeneka8166152010-06-17 04:21:37 +000054 os << "stack memory associated with a compound literal "
55 "declared on line "
Chandler Carruth64211622011-07-25 21:09:52 +000056 << SM.getExpansionLineNumber(CL->getLocStart())
Ted Kremeneka8166152010-06-17 04:21:37 +000057 << " returned to caller";
58 range = CL->getSourceRange();
59 }
60 else if (const AllocaRegion* AR = dyn_cast<AllocaRegion>(R)) {
Ted Kremenek9c378f72011-08-12 23:37:29 +000061 const Expr *ARE = AR->getExpr();
Ted Kremeneka8166152010-06-17 04:21:37 +000062 SourceLocation L = ARE->getLocStart();
63 range = ARE->getSourceRange();
64 os << "stack memory allocated by call to alloca() on line "
Chandler Carruth64211622011-07-25 21:09:52 +000065 << SM.getExpansionLineNumber(L);
Ted Kremeneka8166152010-06-17 04:21:37 +000066 }
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 "
Chandler Carruth64211622011-07-25 21:09:52 +000072 << SM.getExpansionLineNumber(L);
Ted Kremeneka8166152010-06-17 04:21:37 +000073 }
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 }
Jeffrey Yasskin782f63e2011-08-26 00:41:31 +000079 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();
83 }
Ted Kremeneka8166152010-06-17 04:21:37 +000084 else {
David Blaikieb219cfc2011-09-23 05:06:16 +000085 llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
Ted Kremeneka8166152010-06-17 04:21:37 +000086 }
87
88 return range;
89}
90
Ted Kremenekf5d2ef42011-02-25 22:00:43 +000091void StackAddrEscapeChecker::EmitStackError(CheckerContext &C, const MemRegion *R,
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000092 const Expr *RetE) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +000093 ExplodedNode *N = C.generateSink();
Zhongxing Xu9b146832010-06-09 06:08:24 +000094
95 if (!N)
96 return;
97
98 if (!BT_returnstack)
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +000099 BT_returnstack.reset(
100 new BuiltinBug("Return of address to stack-allocated memory"));
Zhongxing Xu9b146832010-06-09 06:08:24 +0000101
102 // Generate a report for this bug.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000103 SmallString<512> buf;
Zhongxing Xu9b146832010-06-09 06:08:24 +0000104 llvm::raw_svector_ostream os(buf);
Ted Kremeneka8166152010-06-17 04:21:37 +0000105 SourceRange range = GenName(os, R, C.getSourceManager());
106 os << " returned to caller";
Anna Zakse172e8b2011-08-17 23:00:25 +0000107 BugReport *report = new BugReport(*BT_returnstack, os.str(), N);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000108 report->addRange(RetE->getSourceRange());
109 if (range.isValid())
110 report->addRange(range);
111
112 C.EmitReport(report);
Eli Friedmana7e68452010-08-22 01:00:03 +0000113}
Zhongxing Xu9b146832010-06-09 06:08:24 +0000114
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000115void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
Ted Kremenek7e867832012-03-03 01:22:03 +0000116 CheckerContext &C) const {
Zhongxing Xu9b146832010-06-09 06:08:24 +0000117
118 const Expr *RetE = RS->getRetValue();
119 if (!RetE)
120 return;
Jordan Rosec210cb72012-08-27 17:50:07 +0000121
122 const LocationContext *LCtx = C.getLocationContext();
123 SVal V = C.getState()->getSVal(RetE, LCtx);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000124 const MemRegion *R = V.getAsRegion();
125
Ted Kremenek7e867832012-03-03 01:22:03 +0000126 if (!R)
Zhongxing Xu9b146832010-06-09 06:08:24 +0000127 return;
Ted Kremenek7e867832012-03-03 01:22:03 +0000128
129 const StackSpaceRegion *SS =
130 dyn_cast_or_null<StackSpaceRegion>(R->getMemorySpace());
131
132 if (!SS)
133 return;
134
135 // Return stack memory in an ancestor stack frame is fine.
Jordan Rosec210cb72012-08-27 17:50:07 +0000136 const StackFrameContext *CurFrame = LCtx->getCurrentStackFrame();
137 const StackFrameContext *MemFrame = SS->getStackFrame();
138 if (MemFrame != CurFrame)
Ted Kremenek7e867832012-03-03 01:22:03 +0000139 return;
140
141 // Automatic reference counting automatically copies blocks.
David Blaikie4e4d0842012-03-11 07:00:24 +0000142 if (C.getASTContext().getLangOpts().ObjCAutoRefCount &&
Ted Kremenek7e867832012-03-03 01:22:03 +0000143 isa<BlockDataRegion>(R))
144 return;
145
Jordan Rosec210cb72012-08-27 17:50:07 +0000146 // Returning a record by value is fine. (In this case, the returned
147 // expression will be a copy-constructor.)
148 if (isa<CXXConstructExpr>(RetE) && RetE->getType()->isRecordType())
149 return;
150
Ted Kremenek7e867832012-03-03 01:22:03 +0000151 EmitStackError(C, R, RetE);
Zhongxing Xu9b146832010-06-09 06:08:24 +0000152}
Zhongxing Xu1622a542010-06-08 10:00:00 +0000153
Anna Zaksaf498a22011-10-25 19:56:48 +0000154void StackAddrEscapeChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000155 ProgramStateRef state = Ctx.getState();
Zhongxing Xu1622a542010-06-08 10:00:00 +0000156
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000157 // Iterate over all bindings to global variables and see if it contains
158 // a memory region in the stack space.
159 class CallBack : public StoreManager::BindingsHandler {
160 private:
Anna Zaksaf498a22011-10-25 19:56:48 +0000161 CheckerContext &Ctx;
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000162 const StackFrameContext *CurSFC;
163 public:
Chris Lattner5f9e2722011-07-23 10:55:15 +0000164 SmallVector<std::pair<const MemRegion*, const MemRegion*>, 10> V;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000165
Anna Zaksaf498a22011-10-25 19:56:48 +0000166 CallBack(CheckerContext &CC) :
167 Ctx(CC),
Anna Zaks39ac1872011-10-26 21:06:44 +0000168 CurSFC(CC.getLocationContext()->getCurrentStackFrame())
Anna Zaksaf498a22011-10-25 19:56:48 +0000169 {}
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000170
171 bool HandleBinding(StoreManager &SMgr, Store store,
172 const MemRegion *region, SVal val) {
173
174 if (!isa<GlobalsSpaceRegion>(region->getMemorySpace()))
175 return true;
176
177 const MemRegion *vR = val.getAsRegion();
178 if (!vR)
179 return true;
John McCallf85e1932011-06-15 23:02:42 +0000180
181 // Under automated retain release, it is okay to assign a block
182 // directly to a global variable.
David Blaikie4e4d0842012-03-11 07:00:24 +0000183 if (Ctx.getASTContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000184 isa<BlockDataRegion>(vR))
185 return true;
186
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000187 if (const StackSpaceRegion *SSR =
188 dyn_cast<StackSpaceRegion>(vR->getMemorySpace())) {
189 // If the global variable holds a location in the current stack frame,
190 // record the binding to emit a warning.
Ted Kremeneka8166152010-06-17 04:21:37 +0000191 if (SSR->getStackFrame() == CurSFC)
192 V.push_back(std::make_pair(region, vR));
Zhongxing Xu1622a542010-06-08 10:00:00 +0000193 }
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000194
195 return true;
Zhongxing Xu1622a542010-06-08 10:00:00 +0000196 }
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000197 };
198
Anna Zaksaf498a22011-10-25 19:56:48 +0000199 CallBack cb(Ctx);
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000200 state->getStateManager().getStoreManager().iterBindings(state->getStore(),cb);
Ted Kremeneka8166152010-06-17 04:21:37 +0000201
202 if (cb.V.empty())
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000203 return;
204
205 // Generate an error node.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000206 ExplodedNode *N = Ctx.addTransition(state);
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000207 if (!N)
208 return;
Ted Kremenek551bd1f2010-06-17 00:24:44 +0000209
Ted Kremeneka8166152010-06-17 04:21:37 +0000210 if (!BT_stackleak)
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000211 BT_stackleak.reset(
Ted Kremeneka8166152010-06-17 04:21:37 +0000212 new BuiltinBug("Stack address stored into global variable",
213 "Stack address was saved into a global variable. "
214 "This is dangerous because the address will become "
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000215 "invalid after returning from the function"));
Ted Kremeneka8166152010-06-17 04:21:37 +0000216
217 for (unsigned i = 0, e = cb.V.size(); i != e; ++i) {
218 // Generate a report for this bug.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000219 SmallString<512> buf;
Ted Kremeneka8166152010-06-17 04:21:37 +0000220 llvm::raw_svector_ostream os(buf);
221 SourceRange range = GenName(os, cb.V[i].second,
Anna Zaksaf498a22011-10-25 19:56:48 +0000222 Ctx.getSourceManager());
Ted Kremeneka8166152010-06-17 04:21:37 +0000223 os << " is still referred to by the global variable '";
224 const VarRegion *VR = cast<VarRegion>(cb.V[i].first->getBaseRegion());
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000225 os << *VR->getDecl()
Ted Kremeneka8166152010-06-17 04:21:37 +0000226 << "' upon returning to the caller. This will be a dangling reference";
Anna Zakse172e8b2011-08-17 23:00:25 +0000227 BugReport *report = new BugReport(*BT_stackleak, os.str(), N);
Ted Kremeneka8166152010-06-17 04:21:37 +0000228 if (range.isValid())
229 report->addRange(range);
230
Anna Zaksaf498a22011-10-25 19:56:48 +0000231 Ctx.EmitReport(report);
Ted Kremeneka8166152010-06-17 04:21:37 +0000232 }
Zhongxing Xu1622a542010-06-08 10:00:00 +0000233}
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000234
Ted Kremenekf5d2ef42011-02-25 22:00:43 +0000235void ento::registerStackAddrEscapeChecker(CheckerManager &mgr) {
236 mgr.registerChecker<StackAddrEscapeChecker>();
Argyrios Kyrtzidisaf5800a2011-02-23 21:04:54 +0000237}