Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//=== StackAddrEscapeChecker.cpp ----------------------------------*- C++ -*--//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file defines stack address leak checker, which checks if an invalid
10
// stack address is stored into a global or heap location. See CERT DCL30-C.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "clang/AST/ExprCXX.h"
16
#include "clang/Basic/SourceManager.h"
17
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18
#include "clang/StaticAnalyzer/Core/Checker.h"
19
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23
#include "llvm/ADT/SmallString.h"
24
#include "llvm/Support/raw_ostream.h"
25
using namespace clang;
26
using namespace ento;
27
28
namespace {
29
class StackAddrEscapeChecker
30
    : public Checker<check::PreCall, check::PreStmt<ReturnStmt>,
31
                     check::EndFunction> {
32
  mutable IdentifierInfo *dispatch_semaphore_tII;
33
  mutable std::unique_ptr<BuiltinBug> BT_stackleak;
34
  mutable std::unique_ptr<BuiltinBug> BT_returnstack;
35
  mutable std::unique_ptr<BuiltinBug> BT_capturedstackasync;
36
  mutable std::unique_ptr<BuiltinBug> BT_capturedstackret;
37
38
public:
39
  enum CheckKind {
40
    CK_StackAddrEscapeChecker,
41
    CK_StackAddrAsyncEscapeChecker,
42
    CK_NumCheckKinds
43
  };
44
45
  DefaultBool ChecksEnabled[CK_NumCheckKinds];
46
47
  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
48
  void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
49
  void checkEndFunction(const ReturnStmt *RS, CheckerContext &Ctx) const;
50
51
private:
52
  void checkReturnedBlockCaptures(const BlockDataRegion &B,
53
                                  CheckerContext &C) const;
54
  void checkAsyncExecutedBlockCaptures(const BlockDataRegion &B,
55
                                       CheckerContext &C) const;
56
  void EmitStackError(CheckerContext &C, const MemRegion *R,
57
                      const Expr *RetE) const;
58
  bool isSemaphoreCaptured(const BlockDecl &B) const;
59
  static SourceRange genName(raw_ostream &os, const MemRegion *R,
60
                             ASTContext &Ctx);
61
  static SmallVector<const MemRegion *, 4>
62
  getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C);
63
  static bool isArcManagedBlock(const MemRegion *R, CheckerContext &C);
64
  static bool isNotInCurrentFrame(const MemRegion *R, CheckerContext &C);
65
};
66
} // namespace
67
68
SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion *R,
69
55
                                            ASTContext &Ctx) {
70
55
  // Get the base region, stripping away fields and elements.
71
55
  R = R->getBaseRegion();
72
55
  SourceManager &SM = Ctx.getSourceManager();
73
55
  SourceRange range;
74
55
  os << "Address of ";
75
55
76
55
  // Check if the region is a compound literal.
77
55
  if (const auto *CR = dyn_cast<CompoundLiteralRegion>(R)) {
78
3
    const CompoundLiteralExpr *CL = CR->getLiteralExpr();
79
3
    os << "stack memory associated with a compound literal "
80
3
          "declared on line "
81
3
       << SM.getExpansionLineNumber(CL->getBeginLoc()) << " returned to caller";
82
3
    range = CL->getSourceRange();
83
52
  } else if (const auto *AR = dyn_cast<AllocaRegion>(R)) {
84
3
    const Expr *ARE = AR->getExpr();
85
3
    SourceLocation L = ARE->getBeginLoc();
86
3
    range = ARE->getSourceRange();
87
3
    os << "stack memory allocated by call to alloca() on line "
88
3
       << SM.getExpansionLineNumber(L);
89
49
  } else if (const auto *BR = dyn_cast<BlockDataRegion>(R)) {
90
2
    const BlockDecl *BD = BR->getCodeRegion()->getDecl();
91
2
    SourceLocation L = BD->getBeginLoc();
92
2
    range = BD->getSourceRange();
93
2
    os << "stack-allocated block declared on line "
94
2
       << SM.getExpansionLineNumber(L);
95
47
  } else if (const auto *VR = dyn_cast<VarRegion>(R)) {
96
35
    os << "stack memory associated with local variable '" << VR->getString()
97
35
       << '\'';
98
35
    range = VR->getDecl()->getSourceRange();
99
35
  } else 
if (const auto *12
TOR12
= dyn_cast<CXXTempObjectRegion>(R)) {
100
12
    QualType Ty = TOR->getValueType().getLocalUnqualifiedType();
101
12
    os << "stack memory associated with temporary object of type '";
102
12
    Ty.print(os, Ctx.getPrintingPolicy());
103
12
    os << "'";
104
12
    range = TOR->getExpr()->getSourceRange();
105
12
  } else {
106
0
    llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
107
0
  }
108
55
109
55
  return range;
110
55
}
111
112
bool StackAddrEscapeChecker::isArcManagedBlock(const MemRegion *R,
113
55
                                               CheckerContext &C) {
114
55
  assert(R && "MemRegion should not be null");
115
55
  return C.getASTContext().getLangOpts().ObjCAutoRefCount &&
116
55
         
isa<BlockDataRegion>(R)6
;
117
55
}
118
119
bool StackAddrEscapeChecker::isNotInCurrentFrame(const MemRegion *R,
120
6.35k
                                                 CheckerContext &C) {
121
6.35k
  const StackSpaceRegion *S = cast<StackSpaceRegion>(R->getMemorySpace());
122
6.35k
  return S->getStackFrame() != C.getStackFrame();
123
6.35k
}
124
125
15
bool StackAddrEscapeChecker::isSemaphoreCaptured(const BlockDecl &B) const {
126
15
  if (!dispatch_semaphore_tII)
127
2
    dispatch_semaphore_tII = &B.getASTContext().Idents.get("dispatch_semaphore_t");
128
18
  for (const auto &C : B.captures()) {
129
18
    const auto *T = C.getVariable()->getType()->getAs<TypedefType>();
130
18
    if (T && 
T->getDecl()->getIdentifier() == dispatch_semaphore_tII1
)
131
1
      return true;
132
18
  }
133
15
  
return false14
;
134
15
}
135
136
SmallVector<const MemRegion *, 4>
137
StackAddrEscapeChecker::getCapturedStackRegions(const BlockDataRegion &B,
138
26
                                                CheckerContext &C) {
139
26
  SmallVector<const MemRegion *, 4> Regions;
140
26
  BlockDataRegion::referenced_vars_iterator I = B.referenced_vars_begin();
141
26
  BlockDataRegion::referenced_vars_iterator E = B.referenced_vars_end();
142
53
  for (; I != E; 
++I27
) {
143
27
    SVal Val = C.getState()->getSVal(I.getCapturedRegion());
144
27
    const MemRegion *Region = Val.getAsRegion();
145
27
    if (Region && 
isa<StackSpaceRegion>(Region->getMemorySpace())15
)
146
15
      Regions.push_back(Region);
147
27
  }
148
26
  return Regions;
149
26
}
150
151
void StackAddrEscapeChecker::EmitStackError(CheckerContext &C,
152
                                            const MemRegion *R,
153
34
                                            const Expr *RetE) const {
154
34
  ExplodedNode *N = C.generateNonFatalErrorNode();
155
34
  if (!N)
156
1
    return;
157
33
  if (!BT_returnstack)
158
9
    BT_returnstack = llvm::make_unique<BuiltinBug>(
159
9
        this, "Return of address to stack-allocated memory");
160
33
  // Generate a report for this bug.
161
33
  SmallString<128> buf;
162
33
  llvm::raw_svector_ostream os(buf);
163
33
  SourceRange range = genName(os, R, C.getASTContext());
164
33
  os << " returned to caller";
165
33
  auto report = llvm::make_unique<BugReport>(*BT_returnstack, os.str(), N);
166
33
  report->addRange(RetE->getSourceRange());
167
33
  if (range.isValid())
168
33
    report->addRange(range);
169
33
  C.emitReport(std::move(report));
170
33
}
171
172
void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures(
173
15
    const BlockDataRegion &B, CheckerContext &C) const {
174
15
  // There is a not-too-uncommon idiom
175
15
  // where a block passed to dispatch_async captures a semaphore
176
15
  // and then the thread (which called dispatch_async) is blocked on waiting
177
15
  // for the completion of the execution of the block
178
15
  // via dispatch_semaphore_wait. To avoid false-positives (for now)
179
15
  // we ignore all the blocks which have captured
180
15
  // a variable of the type "dispatch_semaphore_t".
181
15
  if (isSemaphoreCaptured(*B.getDecl()))
182
1
    return;
183
14
  for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
184
12
    // The block passed to dispatch_async may capture another block
185
12
    // created on the stack. However, there is no leak in this situaton,
186
12
    // no matter if ARC or no ARC is enabled:
187
12
    // dispatch_async copies the passed "outer" block (via Block_copy)
188
12
    // and if the block has captured another "inner" block,
189
12
    // the "inner" block will be copied as well.
190
12
    if (isa<BlockDataRegion>(Region))
191
2
      continue;
192
10
    ExplodedNode *N = C.generateNonFatalErrorNode();
193
10
    if (!N)
194
0
      continue;
195
10
    if (!BT_capturedstackasync)
196
1
      BT_capturedstackasync = llvm::make_unique<BuiltinBug>(
197
1
          this, "Address of stack-allocated memory is captured");
198
10
    SmallString<128> Buf;
199
10
    llvm::raw_svector_ostream Out(Buf);
200
10
    SourceRange Range = genName(Out, Region, C.getASTContext());
201
10
    Out << " is captured by an asynchronously-executed block";
202
10
    auto Report =
203
10
        llvm::make_unique<BugReport>(*BT_capturedstackasync, Out.str(), N);
204
10
    if (Range.isValid())
205
10
      Report->addRange(Range);
206
10
    C.emitReport(std::move(Report));
207
10
  }
208
14
}
209
210
void StackAddrEscapeChecker::checkReturnedBlockCaptures(
211
12
    const BlockDataRegion &B, CheckerContext &C) const {
212
12
  for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
213
3
    if (isArcManagedBlock(Region, C) || isNotInCurrentFrame(Region, C))
214
1
      continue;
215
2
    ExplodedNode *N = C.generateNonFatalErrorNode();
216
2
    if (!N)
217
0
      continue;
218
2
    if (!BT_capturedstackret)
219
2
      BT_capturedstackret = llvm::make_unique<BuiltinBug>(
220
2
          this, "Address of stack-allocated memory is captured");
221
2
    SmallString<128> Buf;
222
2
    llvm::raw_svector_ostream Out(Buf);
223
2
    SourceRange Range = genName(Out, Region, C.getASTContext());
224
2
    Out << " is captured by a returned block";
225
2
    auto Report =
226
2
        llvm::make_unique<BugReport>(*BT_capturedstackret, Out.str(), N);
227
2
    if (Range.isValid())
228
2
      Report->addRange(Range);
229
2
    C.emitReport(std::move(Report));
230
2
  }
231
12
}
232
233
void StackAddrEscapeChecker::checkPreCall(const CallEvent &Call,
234
75.6k
                                          CheckerContext &C) const {
235
75.6k
  if (!ChecksEnabled[CK_StackAddrAsyncEscapeChecker])
236
73.3k
    return;
237
2.23k
  if (!Call.isGlobalCFunction("dispatch_after") &&
238
2.23k
      
!Call.isGlobalCFunction("dispatch_async")2.23k
)
239
2.21k
    return;
240
47
  
for (unsigned Idx = 0, NumArgs = Call.getNumArgs(); 15
Idx < NumArgs;
++Idx32
) {
241
32
    if (const BlockDataRegion *B = dyn_cast_or_null<BlockDataRegion>(
242
15
            Call.getArgSVal(Idx).getAsRegion()))
243
15
      checkAsyncExecutedBlockCaptures(*B, C);
244
32
  }
245
15
}
246
247
void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
248
20.7k
                                          CheckerContext &C) const {
249
20.7k
  if (!ChecksEnabled[CK_StackAddrEscapeChecker])
250
0
    return;
251
20.7k
252
20.7k
  const Expr *RetE = RS->getRetValue();
253
20.7k
  if (!RetE)
254
2.36k
    return;
255
18.3k
  RetE = RetE->IgnoreParens();
256
18.3k
257
18.3k
  SVal V = C.getSVal(RetE);
258
18.3k
  const MemRegion *R = V.getAsRegion();
259
18.3k
  if (!R)
260
10.2k
    return;
261
8.11k
262
8.11k
  if (const BlockDataRegion *B = dyn_cast<BlockDataRegion>(R))
263
12
    checkReturnedBlockCaptures(*B, C);
264
8.11k
265
8.11k
  if (!isa<StackSpaceRegion>(R->getMemorySpace()) ||
266
8.11k
      
isNotInCurrentFrame(R, C)6.34k
||
isArcManagedBlock(R, C)41
)
267
8.07k
    return;
268
38
269
38
  // Returning a record by value is fine. (In this case, the returned
270
38
  // expression will be a copy-constructor, possibly wrapped in an
271
38
  // ExprWithCleanups node.)
272
38
  if (const ExprWithCleanups *Cleanup = dyn_cast<ExprWithCleanups>(RetE))
273
13
    RetE = Cleanup->getSubExpr();
274
38
  if (isa<CXXConstructExpr>(RetE) && 
RetE->getType()->isRecordType()0
)
275
0
    return;
276
38
277
38
  // The CK_CopyAndAutoreleaseBlockObject cast causes the block to be copied
278
38
  // so the stack address is not escaping here.
279
38
  if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetE)) {
280
19
    if (isa<BlockDataRegion>(R) &&
281
19
        
ICE->getCastKind() == CK_CopyAndAutoreleaseBlockObject6
) {
282
4
      return;
283
4
    }
284
34
  }
285
34
286
34
  EmitStackError(C, R, RetE);
287
34
}
288
289
void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
290
54.9k
                                              CheckerContext &Ctx) const {
291
54.9k
  if (!ChecksEnabled[CK_StackAddrEscapeChecker])
292
0
    return;
293
54.9k
294
54.9k
  ProgramStateRef State = Ctx.getState();
295
54.9k
296
54.9k
  // Iterate over all bindings to global variables and see if it contains
297
54.9k
  // a memory region in the stack space.
298
54.9k
  class CallBack : public StoreManager::BindingsHandler {
299
54.9k
  private:
300
54.9k
    CheckerContext &Ctx;
301
54.9k
    const StackFrameContext *CurSFC;
302
54.9k
303
54.9k
  public:
304
54.9k
    SmallVector<std::pair<const MemRegion *, const MemRegion *>, 10> V;
305
54.9k
306
54.9k
    CallBack(CheckerContext &CC) : Ctx(CC), CurSFC(CC.getStackFrame()) {}
307
54.9k
308
54.9k
    bool HandleBinding(StoreManager &SMgr, Store S, const MemRegion *Region,
309
188k
                       SVal Val) override {
310
188k
311
188k
      if (!isa<GlobalsSpaceRegion>(Region->getMemorySpace()))
312
186k
        return true;
313
2.26k
      const MemRegion *VR = Val.getAsRegion();
314
2.26k
      if (VR && 
isa<StackSpaceRegion>(VR->getMemorySpace())127
&&
315
2.26k
          
!isArcManagedBlock(VR, Ctx)11
&&
!isNotInCurrentFrame(VR, Ctx)10
)
316
10
        V.emplace_back(Region, VR);
317
2.26k
      return true;
318
2.26k
    }
319
54.9k
  };
320
54.9k
321
54.9k
  CallBack Cb(Ctx);
322
54.9k
  State->getStateManager().getStoreManager().iterBindings(State->getStore(),
323
54.9k
                                                          Cb);
324
54.9k
325
54.9k
  if (Cb.V.empty())
326
54.9k
    return;
327
8
328
8
  // Generate an error node.
329
8
  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
330
8
  if (!N)
331
0
    return;
332
8
333
8
  if (!BT_stackleak)
334
2
    BT_stackleak = llvm::make_unique<BuiltinBug>(
335
2
        this, "Stack address stored into global variable",
336
2
        "Stack address was saved into a global variable. "
337
2
        "This is dangerous because the address will become "
338
2
        "invalid after returning from the function");
339
8
340
10
  for (const auto &P : Cb.V) {
341
10
    // Generate a report for this bug.
342
10
    SmallString<128> Buf;
343
10
    llvm::raw_svector_ostream Out(Buf);
344
10
    SourceRange Range = genName(Out, P.second, Ctx.getASTContext());
345
10
    Out << " is still referred to by the ";
346
10
    if (isa<StaticGlobalSpaceRegion>(P.first->getMemorySpace()))
347
4
      Out << "static";
348
6
    else
349
6
      Out << "global";
350
10
    Out << " variable '";
351
10
    const VarRegion *VR = cast<VarRegion>(P.first->getBaseRegion());
352
10
    Out << *VR->getDecl()
353
10
        << "' upon returning to the caller.  This will be a dangling reference";
354
10
    auto Report = llvm::make_unique<BugReport>(*BT_stackleak, Out.str(), N);
355
10
    if (Range.isValid())
356
10
      Report->addRange(Range);
357
10
358
10
    Ctx.emitReport(std::move(Report));
359
10
  }
360
8
}
361
362
675
void ento::registerStackAddrEscapeBase(CheckerManager &mgr) {
363
675
  mgr.registerChecker<StackAddrEscapeChecker>();
364
675
}
365
366
676
bool ento::shouldRegisterStackAddrEscapeBase(const LangOptions &LO) {
367
676
  return true;
368
676
}
369
370
#define REGISTER_CHECKER(name)                                                 \
371
746
  void ento::register##name(CheckerManager &Mgr) {                             \
372
746
    StackAddrEscapeChecker *Chk =                                              \
373
746
        Mgr.getChecker<StackAddrEscapeChecker>();                              \
374
746
    Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true;              \
375
746
  }                                                                            \
clang::ento::registerStackAddrEscapeChecker(clang::ento::CheckerManager&)
Line
Count
Source
371
675
  void ento::register##name(CheckerManager &Mgr) {                             \
372
675
    StackAddrEscapeChecker *Chk =                                              \
373
675
        Mgr.getChecker<StackAddrEscapeChecker>();                              \
374
675
    Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true;              \
375
675
  }                                                                            \
clang::ento::registerStackAddrAsyncEscapeChecker(clang::ento::CheckerManager&)
Line
Count
Source
371
71
  void ento::register##name(CheckerManager &Mgr) {                             \
372
71
    StackAddrEscapeChecker *Chk =                                              \
373
71
        Mgr.getChecker<StackAddrEscapeChecker>();                              \
374
71
    Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true;              \
375
71
  }                                                                            \
376
                                                                               \
377
747
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
378
747
    return true;                                                               \
379
747
  }
clang::ento::shouldRegisterStackAddrEscapeChecker(clang::LangOptions const&)
Line
Count
Source
377
676
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
378
676
    return true;                                                               \
379
676
  }
clang::ento::shouldRegisterStackAddrAsyncEscapeChecker(clang::LangOptions const&)
Line
Count
Source
377
71
  bool ento::shouldRegister##name(const LangOptions &LO) {                     \
378
71
    return true;                                                               \
379
71
  }
380
381
REGISTER_CHECKER(StackAddrEscapeChecker)
382
REGISTER_CHECKER(StackAddrAsyncEscapeChecker)