StackAddrEscapeChecker.cpp revision 785950e59424dca7ce0081bebf13c0acd2c4fff6
1//=== StackAddrEscapeChecker.cpp ----------------------------------*- C++ -*--//
2//
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
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"
23using namespace clang;
24using namespace ento;
25
26namespace {
27class StackAddrEscapeChecker : public Checker< check::PreStmt<ReturnStmt>,
28                                               check::EndPath > {
29  mutable OwningPtr<BuiltinBug> BT_stackleak;
30  mutable OwningPtr<BuiltinBug> BT_returnstack;
31
32public:
33  void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
34  void checkEndPath(CheckerContext &Ctx) const;
35private:
36  void EmitStackError(CheckerContext &C, const MemRegion *R,
37                      const Expr *RetE) const;
38  static SourceRange GenName(raw_ostream &os, const MemRegion *R,
39                             SourceManager &SM);
40};
41}
42
43SourceRange StackAddrEscapeChecker::GenName(raw_ostream &os,
44                                          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.getExpansionLineNumber(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.getExpansionLineNumber(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.getExpansionLineNumber(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 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  }
84  else {
85    llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
86  }
87
88  return range;
89}
90
91void StackAddrEscapeChecker::EmitStackError(CheckerContext &C, const MemRegion *R,
92                                          const Expr *RetE) const {
93  ExplodedNode *N = C.generateSink();
94
95  if (!N)
96    return;
97
98  if (!BT_returnstack)
99   BT_returnstack.reset(
100                 new BuiltinBug("Return of address to stack-allocated memory"));
101
102  // Generate a report for this bug.
103  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());
109  if (range.isValid())
110    report->addRange(range);
111
112  C.emitReport(report);
113}
114
115void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
116                                          CheckerContext &C) const {
117
118  const Expr *RetE = RS->getRetValue();
119  if (!RetE)
120    return;
121  RetE = RetE->IgnoreParens();
122
123  const LocationContext *LCtx = C.getLocationContext();
124  SVal V = C.getState()->getSVal(RetE, LCtx);
125  const MemRegion *R = V.getAsRegion();
126
127  if (!R)
128    return;
129
130  const StackSpaceRegion *SS =
131    dyn_cast_or_null<StackSpaceRegion>(R->getMemorySpace());
132
133  if (!SS)
134    return;
135
136  // Return stack memory in an ancestor stack frame is fine.
137  const StackFrameContext *CurFrame = LCtx->getCurrentStackFrame();
138  const StackFrameContext *MemFrame = SS->getStackFrame();
139  if (MemFrame != CurFrame)
140    return;
141
142  // Automatic reference counting automatically copies blocks.
143  if (C.getASTContext().getLangOpts().ObjCAutoRefCount &&
144      isa<BlockDataRegion>(R))
145    return;
146
147  // Returning a record by value is fine. (In this case, the returned
148  // expression will be a copy-constructor, possibly wrapped in an
149  // ExprWithCleanups node.)
150  if (const ExprWithCleanups *Cleanup = dyn_cast<ExprWithCleanups>(RetE))
151    RetE = Cleanup->getSubExpr();
152  if (isa<CXXConstructExpr>(RetE) && RetE->getType()->isRecordType())
153    return;
154
155  EmitStackError(C, R, RetE);
156}
157
158void StackAddrEscapeChecker::checkEndPath(CheckerContext &Ctx) const {
159  ProgramStateRef state = Ctx.getState();
160
161  // Iterate over all bindings to global variables and see if it contains
162  // a memory region in the stack space.
163  class CallBack : public StoreManager::BindingsHandler {
164  private:
165    CheckerContext &Ctx;
166    const StackFrameContext *CurSFC;
167  public:
168    SmallVector<std::pair<const MemRegion*, const MemRegion*>, 10> V;
169
170    CallBack(CheckerContext &CC) :
171      Ctx(CC),
172      CurSFC(CC.getLocationContext()->getCurrentStackFrame())
173    {}
174
175    bool HandleBinding(StoreManager &SMgr, Store store,
176                       const MemRegion *region, SVal val) {
177
178      if (!isa<GlobalsSpaceRegion>(region->getMemorySpace()))
179        return true;
180
181      const MemRegion *vR = val.getAsRegion();
182      if (!vR)
183        return true;
184
185      // Under automated retain release, it is okay to assign a block
186      // directly to a global variable.
187      if (Ctx.getASTContext().getLangOpts().ObjCAutoRefCount &&
188          isa<BlockDataRegion>(vR))
189        return true;
190
191      if (const StackSpaceRegion *SSR =
192          dyn_cast<StackSpaceRegion>(vR->getMemorySpace())) {
193        // If the global variable holds a location in the current stack frame,
194        // record the binding to emit a warning.
195        if (SSR->getStackFrame() == CurSFC)
196          V.push_back(std::make_pair(region, vR));
197      }
198
199      return true;
200    }
201  };
202
203  CallBack cb(Ctx);
204  state->getStateManager().getStoreManager().iterBindings(state->getStore(),cb);
205
206  if (cb.V.empty())
207    return;
208
209  // Generate an error node.
210  ExplodedNode *N = Ctx.addTransition(state);
211  if (!N)
212    return;
213
214  if (!BT_stackleak)
215    BT_stackleak.reset(
216      new BuiltinBug("Stack address stored into global variable",
217                     "Stack address was saved into a global variable. "
218                     "This is dangerous because the address will become "
219                     "invalid after returning from the function"));
220
221  for (unsigned i = 0, e = cb.V.size(); i != e; ++i) {
222    // Generate a report for this bug.
223    SmallString<512> buf;
224    llvm::raw_svector_ostream os(buf);
225    SourceRange range = GenName(os, cb.V[i].second,
226                                Ctx.getSourceManager());
227    os << " is still referred to by the global variable '";
228    const VarRegion *VR = cast<VarRegion>(cb.V[i].first->getBaseRegion());
229    os << *VR->getDecl()
230       << "' upon returning to the caller.  This will be a dangling reference";
231    BugReport *report = new BugReport(*BT_stackleak, os.str(), N);
232    if (range.isValid())
233      report->addRange(range);
234
235    Ctx.emitReport(report);
236  }
237}
238
239void ento::registerStackAddrEscapeChecker(CheckerManager &mgr) {
240  mgr.registerChecker<StackAddrEscapeChecker>();
241}
242