Coverage Report

Created: 2022-01-15 10:30

/Users/buildslave/jenkins/workspace/coverage/llvm-project/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/AST/ExprCXX.h"
15
#include "clang/Basic/SourceManager.h"
16
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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
  CheckerNameRef CheckNames[CK_NumCheckKinds];
47
48
  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
49
  void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
50
  void checkEndFunction(const ReturnStmt *RS, CheckerContext &Ctx) const;
51
52
private:
53
  void checkReturnedBlockCaptures(const BlockDataRegion &B,
54
                                  CheckerContext &C) const;
55
  void checkAsyncExecutedBlockCaptures(const BlockDataRegion &B,
56
                                       CheckerContext &C) const;
57
  void EmitStackError(CheckerContext &C, const MemRegion *R,
58
                      const Expr *RetE) const;
59
  bool isSemaphoreCaptured(const BlockDecl &B) const;
60
  static SourceRange genName(raw_ostream &os, const MemRegion *R,
61
                             ASTContext &Ctx);
62
  static SmallVector<const MemRegion *, 4>
63
  getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C);
64
  static bool isArcManagedBlock(const MemRegion *R, CheckerContext &C);
65
  static bool isNotInCurrentFrame(const MemRegion *R, CheckerContext &C);
66
};
67
} // namespace
68
69
SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion *R,
70
111
                                            ASTContext &Ctx) {
71
  // Get the base region, stripping away fields and elements.
72
111
  R = R->getBaseRegion();
73
111
  SourceManager &SM = Ctx.getSourceManager();
74
111
  SourceRange range;
75
111
  os << "Address of ";
76
77
  // Check if the region is a compound literal.
78
111
  if (const auto *CR = dyn_cast<CompoundLiteralRegion>(R)) {
79
3
    const CompoundLiteralExpr *CL = CR->getLiteralExpr();
80
3
    os << "stack memory associated with a compound literal "
81
3
          "declared on line "
82
3
       << SM.getExpansionLineNumber(CL->getBeginLoc()) << " returned to caller";
83
3
    range = CL->getSourceRange();
84
108
  } else if (const auto *AR = dyn_cast<AllocaRegion>(R)) {
85
9
    const Expr *ARE = AR->getExpr();
86
9
    SourceLocation L = ARE->getBeginLoc();
87
9
    range = ARE->getSourceRange();
88
9
    os << "stack memory allocated by call to alloca() on line "
89
9
       << SM.getExpansionLineNumber(L);
90
99
  } else if (const auto *BR = dyn_cast<BlockDataRegion>(R)) {
91
2
    const BlockDecl *BD = BR->getCodeRegion()->getDecl();
92
2
    SourceLocation L = BD->getBeginLoc();
93
2
    range = BD->getSourceRange();
94
2
    os << "stack-allocated block declared on line "
95
2
       << SM.getExpansionLineNumber(L);
96
97
  } else if (const auto *VR = dyn_cast<VarRegion>(R)) {
97
64
    os << "stack memory associated with local variable '" << VR->getString()
98
64
       << '\'';
99
64
    range = VR->getDecl()->getSourceRange();
100
64
  } else 
if (const auto *33
TOR33
= dyn_cast<CXXTempObjectRegion>(R)) {
101
33
    QualType Ty = TOR->getValueType().getLocalUnqualifiedType();
102
33
    os << "stack memory associated with temporary object of type '";
103
33
    Ty.print(os, Ctx.getPrintingPolicy());
104
33
    os << "'";
105
33
    range = TOR->getExpr()->getSourceRange();
106
33
  } else {
107
0
    llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
108
0
  }
109
110
111
  return range;
111
111
}
112
113
bool StackAddrEscapeChecker::isArcManagedBlock(const MemRegion *R,
114
59
                                               CheckerContext &C) {
115
59
  assert(R && "MemRegion should not be null");
116
59
  return C.getASTContext().getLangOpts().ObjCAutoRefCount &&
117
59
         
isa<BlockDataRegion>(R)8
;
118
59
}
119
120
bool StackAddrEscapeChecker::isNotInCurrentFrame(const MemRegion *R,
121
6.72k
                                                 CheckerContext &C) {
122
6.72k
  const StackSpaceRegion *S = cast<StackSpaceRegion>(R->getMemorySpace());
123
6.72k
  return S->getStackFrame() != C.getStackFrame();
124
6.72k
}
125
126
16
bool StackAddrEscapeChecker::isSemaphoreCaptured(const BlockDecl &B) const {
127
16
  if (!dispatch_semaphore_tII)
128
3
    dispatch_semaphore_tII = &B.getASTContext().Idents.get("dispatch_semaphore_t");
129
19
  for (const auto &C : B.captures()) {
130
19
    const auto *T = C.getVariable()->getType()->getAs<TypedefType>();
131
19
    if (T && 
T->getDecl()->getIdentifier() == dispatch_semaphore_tII1
)
132
1
      return true;
133
19
  }
134
15
  return false;
135
16
}
136
137
SmallVector<const MemRegion *, 4>
138
StackAddrEscapeChecker::getCapturedStackRegions(const BlockDataRegion &B,
139
28
                                                CheckerContext &C) {
140
28
  SmallVector<const MemRegion *, 4> Regions;
141
28
  BlockDataRegion::referenced_vars_iterator I = B.referenced_vars_begin();
142
28
  BlockDataRegion::referenced_vars_iterator E = B.referenced_vars_end();
143
57
  for (; I != E; 
++I29
) {
144
29
    SVal Val = C.getState()->getSVal(I.getCapturedRegion());
145
29
    const MemRegion *Region = Val.getAsRegion();
146
29
    if (Region && 
isa<StackSpaceRegion>(Region->getMemorySpace())17
)
147
17
      Regions.push_back(Region);
148
29
  }
149
28
  return Regions;
150
28
}
151
152
void StackAddrEscapeChecker::EmitStackError(CheckerContext &C,
153
                                            const MemRegion *R,
154
35
                                            const Expr *RetE) const {
155
35
  ExplodedNode *N = C.generateNonFatalErrorNode();
156
35
  if (!N)
157
1
    return;
158
34
  if (!BT_returnstack)
159
10
    BT_returnstack = std::make_unique<BuiltinBug>(
160
10
        CheckNames[CK_StackAddrEscapeChecker],
161
10
        "Return of address to stack-allocated memory");
162
  // Generate a report for this bug.
163
34
  SmallString<128> buf;
164
34
  llvm::raw_svector_ostream os(buf);
165
34
  SourceRange range = genName(os, R, C.getASTContext());
166
34
  os << " returned to caller";
167
34
  auto report =
168
34
      std::make_unique<PathSensitiveBugReport>(*BT_returnstack, os.str(), N);
169
34
  report->addRange(RetE->getSourceRange());
170
34
  if (range.isValid())
171
34
    report->addRange(range);
172
34
  C.emitReport(std::move(report));
173
34
}
174
175
void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures(
176
16
    const BlockDataRegion &B, CheckerContext &C) const {
177
  // There is a not-too-uncommon idiom
178
  // where a block passed to dispatch_async captures a semaphore
179
  // and then the thread (which called dispatch_async) is blocked on waiting
180
  // for the completion of the execution of the block
181
  // via dispatch_semaphore_wait. To avoid false-positives (for now)
182
  // we ignore all the blocks which have captured
183
  // a variable of the type "dispatch_semaphore_t".
184
16
  if (isSemaphoreCaptured(*B.getDecl()))
185
1
    return;
186
15
  for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
187
    // The block passed to dispatch_async may capture another block
188
    // created on the stack. However, there is no leak in this situaton,
189
    // no matter if ARC or no ARC is enabled:
190
    // dispatch_async copies the passed "outer" block (via Block_copy)
191
    // and if the block has captured another "inner" block,
192
    // the "inner" block will be copied as well.
193
13
    if (isa<BlockDataRegion>(Region))
194
2
      continue;
195
11
    ExplodedNode *N = C.generateNonFatalErrorNode();
196
11
    if (!N)
197
0
      continue;
198
11
    if (!BT_capturedstackasync)
199
2
      BT_capturedstackasync = std::make_unique<BuiltinBug>(
200
2
          CheckNames[CK_StackAddrAsyncEscapeChecker],
201
2
          "Address of stack-allocated memory is captured");
202
11
    SmallString<128> Buf;
203
11
    llvm::raw_svector_ostream Out(Buf);
204
11
    SourceRange Range = genName(Out, Region, C.getASTContext());
205
11
    Out << " is captured by an asynchronously-executed block";
206
11
    auto Report = std::make_unique<PathSensitiveBugReport>(
207
11
        *BT_capturedstackasync, Out.str(), N);
208
11
    if (Range.isValid())
209
11
      Report->addRange(Range);
210
11
    C.emitReport(std::move(Report));
211
11
  }
212
15
}
213
214
void StackAddrEscapeChecker::checkReturnedBlockCaptures(
215
13
    const BlockDataRegion &B, CheckerContext &C) const {
216
13
  for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
217
4
    if (isArcManagedBlock(Region, C) || isNotInCurrentFrame(Region, C))
218
1
      continue;
219
3
    ExplodedNode *N = C.generateNonFatalErrorNode();
220
3
    if (!N)
221
0
      continue;
222
3
    if (!BT_capturedstackret)
223
3
      BT_capturedstackret = std::make_unique<BuiltinBug>(
224
3
          CheckNames[CK_StackAddrEscapeChecker],
225
3
          "Address of stack-allocated memory is captured");
226
3
    SmallString<128> Buf;
227
3
    llvm::raw_svector_ostream Out(Buf);
228
3
    SourceRange Range = genName(Out, Region, C.getASTContext());
229
3
    Out << " is captured by a returned block";
230
3
    auto Report = std::make_unique<PathSensitiveBugReport>(*BT_capturedstackret,
231
3
                                                           Out.str(), N);
232
3
    if (Range.isValid())
233
3
      Report->addRange(Range);
234
3
    C.emitReport(std::move(Report));
235
3
  }
236
13
}
237
238
void StackAddrEscapeChecker::checkPreCall(const CallEvent &Call,
239
98.2k
                                          CheckerContext &C) const {
240
98.2k
  if (!ChecksEnabled[CK_StackAddrAsyncEscapeChecker])
241
95.9k
    return;
242
2.28k
  if (!Call.isGlobalCFunction("dispatch_after") &&
243
2.28k
      
!Call.isGlobalCFunction("dispatch_async")2.28k
)
244
2.27k
    return;
245
50
  
for (unsigned Idx = 0, NumArgs = Call.getNumArgs(); 16
Idx < NumArgs;
++Idx34
) {
246
34
    if (const BlockDataRegion *B = dyn_cast_or_null<BlockDataRegion>(
247
34
            Call.getArgSVal(Idx).getAsRegion()))
248
16
      checkAsyncExecutedBlockCaptures(*B, C);
249
34
  }
250
16
}
251
252
void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
253
23.2k
                                          CheckerContext &C) const {
254
23.2k
  if (!ChecksEnabled[CK_StackAddrEscapeChecker])
255
0
    return;
256
257
23.2k
  const Expr *RetE = RS->getRetValue();
258
23.2k
  if (!RetE)
259
2.96k
    return;
260
20.3k
  RetE = RetE->IgnoreParens();
261
262
20.3k
  SVal V = C.getSVal(RetE);
263
20.3k
  const MemRegion *R = V.getAsRegion();
264
20.3k
  if (!R)
265
11.7k
    return;
266
267
8.53k
  if (const BlockDataRegion *B = dyn_cast<BlockDataRegion>(R))
268
13
    checkReturnedBlockCaptures(*B, C);
269
270
8.53k
  if (!isa<StackSpaceRegion>(R->getMemorySpace()) ||
271
8.53k
      
isNotInCurrentFrame(R, C)6.70k
||
isArcManagedBlock(R, C)43
)
272
8.49k
    return;
273
274
  // Returning a record by value is fine. (In this case, the returned
275
  // expression will be a copy-constructor, possibly wrapped in an
276
  // ExprWithCleanups node.)
277
39
  if (const ExprWithCleanups *Cleanup = dyn_cast<ExprWithCleanups>(RetE))
278
13
    RetE = Cleanup->getSubExpr();
279
39
  if (isa<CXXConstructExpr>(RetE) && 
RetE->getType()->isRecordType()0
)
280
0
    return;
281
282
  // The CK_CopyAndAutoreleaseBlockObject cast causes the block to be copied
283
  // so the stack address is not escaping here.
284
39
  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(RetE)) {
285
19
    if (isa<BlockDataRegion>(R) &&
286
19
        
ICE->getCastKind() == CK_CopyAndAutoreleaseBlockObject6
) {
287
4
      return;
288
4
    }
289
19
  }
290
291
35
  EmitStackError(C, R, RetE);
292
35
}
293
294
void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
295
62.5k
                                              CheckerContext &Ctx) const {
296
62.5k
  if (!ChecksEnabled[CK_StackAddrEscapeChecker])
297
0
    return;
298
299
62.5k
  ProgramStateRef State = Ctx.getState();
300
301
  // Iterate over all bindings to global variables and see if it contains
302
  // a memory region in the stack space.
303
62.5k
  class CallBack : public StoreManager::BindingsHandler {
304
62.5k
  private:
305
62.5k
    CheckerContext &Ctx;
306
62.5k
    const StackFrameContext *PoppedFrame;
307
308
    /// Look for stack variables referring to popped stack variables.
309
    /// Returns true only if it found some dangling stack variables
310
    /// referred by an other stack variable from different stack frame.
311
62.5k
    bool checkForDanglingStackVariable(const MemRegion *Referrer,
312
89.5k
                                       const MemRegion *Referred) {
313
89.5k
      const auto *ReferrerMemSpace =
314
89.5k
          Referrer->getMemorySpace()->getAs<StackSpaceRegion>();
315
89.5k
      const auto *ReferredMemSpace =
316
89.5k
          Referred->getMemorySpace()->getAs<StackSpaceRegion>();
317
318
89.5k
      if (!ReferrerMemSpace || 
!ReferredMemSpace88.7k
)
319
29.4k
        return false;
320
321
60.1k
      const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
322
60.1k
      const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
323
324
60.1k
      if (ReferrerMemSpace && ReferredMemSpace) {
325
60.1k
        if (ReferredFrame == PoppedFrame &&
326
60.1k
            
ReferrerFrame->isParentOf(PoppedFrame)101
) {
327
52
          V.emplace_back(Referrer, Referred);
328
52
          return true;
329
52
        }
330
60.1k
      }
331
60.0k
      return false;
332
60.1k
    }
333
334
62.5k
  public:
335
62.5k
    SmallVector<std::pair<const MemRegion *, const MemRegion *>, 10> V;
336
337
62.5k
    CallBack(CheckerContext &CC) : Ctx(CC), PoppedFrame(CC.getStackFrame()) {}
338
339
62.5k
    bool HandleBinding(StoreManager &SMgr, Store S, const MemRegion *Region,
340
184k
                       SVal Val) override {
341
184k
      const MemRegion *VR = Val.getAsRegion();
342
184k
      if (!VR)
343
94.6k
        return true;
344
345
89.5k
      if (checkForDanglingStackVariable(Region, VR))
346
52
        return true;
347
348
      // Check the globals for the same.
349
89.5k
      if (!isa<GlobalsSpaceRegion>(Region->getMemorySpace()))
350
89.3k
        return true;
351
134
      if (VR && VR->hasStackStorage() && 
!isArcManagedBlock(VR, Ctx)12
&&
352
134
          
!isNotInCurrentFrame(VR, Ctx)11
)
353
11
        V.emplace_back(Region, VR);
354
134
      return true;
355
89.5k
    }
356
62.5k
  };
357
358
62.5k
  CallBack Cb(Ctx);
359
62.5k
  State->getStateManager().getStoreManager().iterBindings(State->getStore(),
360
62.5k
                                                          Cb);
361
362
62.5k
  if (Cb.V.empty())
363
62.5k
    return;
364
365
  // Generate an error node.
366
46
  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
367
46
  if (!N)
368
0
    return;
369
370
46
  if (!BT_stackleak)
371
11
    BT_stackleak = std::make_unique<BuiltinBug>(
372
11
        CheckNames[CK_StackAddrEscapeChecker],
373
11
        "Stack address stored into global variable",
374
11
        "Stack address was saved into a global variable. "
375
11
        "This is dangerous because the address will become "
376
11
        "invalid after returning from the function");
377
378
63
  for (const auto &P : Cb.V) {
379
63
    const MemRegion *Referrer = P.first;
380
63
    const MemRegion *Referred = P.second;
381
382
    // Generate a report for this bug.
383
63
    const StringRef CommonSuffix =
384
63
        "upon returning to the caller.  This will be a dangling reference";
385
63
    SmallString<128> Buf;
386
63
    llvm::raw_svector_ostream Out(Buf);
387
63
    const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
388
389
63
    if (isa<CXXTempObjectRegion>(Referrer)) {
390
12
      Out << " is still referred to by a temporary object on the stack "
391
12
          << CommonSuffix;
392
12
      auto Report =
393
12
          std::make_unique<PathSensitiveBugReport>(*BT_stackleak, Out.str(), N);
394
12
      Ctx.emitReport(std::move(Report));
395
12
      return;
396
12
    }
397
398
51
    const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
399
51
      if (isa<StaticGlobalSpaceRegion>(Space))
400
4
        return "static";
401
47
      if (isa<GlobalsSpaceRegion>(Space))
402
7
        return "global";
403
40
      assert(isa<StackSpaceRegion>(Space));
404
0
      return "stack";
405
47
    }(Referrer->getMemorySpace());
406
407
    // This cast supposed to succeed.
408
51
    const VarRegion *ReferrerVar = cast<VarRegion>(Referrer->getBaseRegion());
409
51
    const std::string ReferrerVarName =
410
51
        ReferrerVar->getDecl()->getDeclName().getAsString();
411
412
51
    Out << " is still referred to by the " << ReferrerMemorySpace
413
51
        << " variable '" << ReferrerVarName << "' " << CommonSuffix;
414
51
    auto Report =
415
51
        std::make_unique<PathSensitiveBugReport>(*BT_stackleak, Out.str(), N);
416
51
    if (Range.isValid())
417
51
      Report->addRange(Range);
418
419
51
    Ctx.emitReport(std::move(Report));
420
51
  }
421
46
}
422
423
1.15k
void ento::registerStackAddrEscapeBase(CheckerManager &mgr) {
424
1.15k
  mgr.registerChecker<StackAddrEscapeChecker>();
425
1.15k
}
426
427
4.77k
bool ento::shouldRegisterStackAddrEscapeBase(const CheckerManager &mgr) {
428
4.77k
  return true;
429
4.77k
}
430
431
#define REGISTER_CHECKER(name)                                                 \
432
1.22k
  void ento::register##name(CheckerManager &Mgr) {                             \
433
1.22k
    StackAddrEscapeChecker *Chk = Mgr.getChecker<StackAddrEscapeChecker>();    \
434
1.22k
    Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true;              \
435
1.22k
    Chk->CheckNames[StackAddrEscapeChecker::CK_##name] =                       \
436
1.22k
        Mgr.getCurrentCheckerName();                                           \
437
1.22k
  }                                                                            \
clang::ento::registerStackAddrEscapeChecker(clang::ento::CheckerManager&)
Line
Count
Source
432
1.15k
  void ento::register##name(CheckerManager &Mgr) {                             \
433
1.15k
    StackAddrEscapeChecker *Chk = Mgr.getChecker<StackAddrEscapeChecker>();    \
434
1.15k
    Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true;              \
435
1.15k
    Chk->CheckNames[StackAddrEscapeChecker::CK_##name] =                       \
436
1.15k
        Mgr.getCurrentCheckerName();                                           \
437
1.15k
  }                                                                            \
clang::ento::registerStackAddrAsyncEscapeChecker(clang::ento::CheckerManager&)
Line
Count
Source
432
71
  void ento::register##name(CheckerManager &Mgr) {                             \
433
71
    StackAddrEscapeChecker *Chk = Mgr.getChecker<StackAddrEscapeChecker>();    \
434
71
    Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true;              \
435
71
    Chk->CheckNames[StackAddrEscapeChecker::CK_##name] =                       \
436
71
        Mgr.getCurrentCheckerName();                                           \
437
71
  }                                                                            \
438
                                                                               \
439
2.45k
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
clang::ento::shouldRegisterStackAddrEscapeChecker(clang::ento::CheckerManager const&)
Line
Count
Source
439
2.31k
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
clang::ento::shouldRegisterStackAddrAsyncEscapeChecker(clang::ento::CheckerManager const&)
Line
Count
Source
439
142
  bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
440
441
REGISTER_CHECKER(StackAddrEscapeChecker)
442
REGISTER_CHECKER(StackAddrAsyncEscapeChecker)