Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//== ValistChecker.cpp - stdarg.h macro usage checker -----------*- 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 defines checkers which detect usage of uninitialized va_list values
10
// and va_start calls with no matching va_end.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
16
#include "clang/StaticAnalyzer/Core/Checker.h"
17
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20
21
using namespace clang;
22
using namespace ento;
23
24
REGISTER_SET_WITH_PROGRAMSTATE(InitializedVALists, const MemRegion *)
25
26
namespace {
27
typedef SmallVector<const MemRegion *, 2> RegionVector;
28
29
class ValistChecker : public Checker<check::PreCall, check::PreStmt<VAArgExpr>,
30
                                     check::DeadSymbols> {
31
  mutable std::unique_ptr<BugType> BT_leakedvalist, BT_uninitaccess;
32
33
  struct VAListAccepter {
34
    CallDescription Func;
35
    int VAListPos;
36
  };
37
  static const SmallVector<VAListAccepter, 15> VAListAccepters;
38
  static const CallDescription VaStart, VaEnd, VaCopy;
39
40
public:
41
  enum CheckKind {
42
    CK_Uninitialized,
43
    CK_Unterminated,
44
    CK_CopyToSelf,
45
    CK_NumCheckKinds
46
  };
47
48
  DefaultBool ChecksEnabled[CK_NumCheckKinds];
49
  CheckName CheckNames[CK_NumCheckKinds];
50
51
  void checkPreStmt(const VAArgExpr *VAA, CheckerContext &C) const;
52
  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
53
  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
54
55
private:
56
  const MemRegion *getVAListAsRegion(SVal SV, const Expr *VAExpr,
57
                                     bool &IsSymbolic, CheckerContext &C) const;
58
  const ExplodedNode *getStartCallSite(const ExplodedNode *N,
59
                                       const MemRegion *Reg) const;
60
61
  void reportUninitializedAccess(const MemRegion *VAList, StringRef Msg,
62
                                 CheckerContext &C) const;
63
  void reportLeakedVALists(const RegionVector &LeakedVALists, StringRef Msg1,
64
                           StringRef Msg2, CheckerContext &C, ExplodedNode *N,
65
                           bool ReportUninit = false) const;
66
67
  void checkVAListStartCall(const CallEvent &Call, CheckerContext &C,
68
                            bool IsCopy) const;
69
  void checkVAListEndCall(const CallEvent &Call, CheckerContext &C) const;
70
71
  class ValistBugVisitor : public BugReporterVisitor {
72
  public:
73
    ValistBugVisitor(const MemRegion *Reg, bool IsLeak = false)
74
76
        : Reg(Reg), IsLeak(IsLeak) {}
75
76
    void Profile(llvm::FoldingSetNodeID &ID) const override {
76
76
      static int X = 0;
77
76
      ID.AddPointer(&X);
78
76
      ID.AddPointer(Reg);
79
76
    }
80
    std::shared_ptr<PathDiagnosticPiece>
81
    getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
82
75
               BugReport &BR) override {
83
75
      if (!IsLeak)
84
32
        return nullptr;
85
43
86
43
      PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(
87
43
          EndPathNode, BRC.getSourceManager());
88
43
      // Do not add the statement itself as a range in case of leak.
89
43
      return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(), false);
90
43
    }
91
    std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
92
                                                   BugReporterContext &BRC,
93
                                                   BugReport &BR) override;
94
95
  private:
96
    const MemRegion *Reg;
97
    bool IsLeak;
98
  };
99
};
100
101
const SmallVector<ValistChecker::VAListAccepter, 15>
102
    ValistChecker::VAListAccepters = {
103
        {{"vfprintf", 3}, 2},
104
        {{"vfscanf", 3}, 2},
105
        {{"vprintf", 2}, 1},
106
        {{"vscanf", 2}, 1},
107
        {{"vsnprintf", 4}, 3},
108
        {{"vsprintf", 3}, 2},
109
        {{"vsscanf", 3}, 2},
110
        {{"vfwprintf", 3}, 2},
111
        {{"vfwscanf", 3}, 2},
112
        {{"vwprintf", 2}, 1},
113
        {{"vwscanf", 2}, 1},
114
        {{"vswprintf", 4}, 3},
115
        // vswprintf is the wide version of vsnprintf,
116
        // vsprintf has no wide version
117
        {{"vswscanf", 3}, 2}};
118
const CallDescription ValistChecker::VaStart("__builtin_va_start", 2),
119
    ValistChecker::VaCopy("__builtin_va_copy", 2),
120
    ValistChecker::VaEnd("__builtin_va_end", 1);
121
} // end anonymous namespace
122
123
void ValistChecker::checkPreCall(const CallEvent &Call,
124
232
                                 CheckerContext &C) const {
125
232
  if (!Call.isGlobalCFunction())
126
0
    return;
127
232
  if (Call.isCalled(VaStart))
128
98
    checkVAListStartCall(Call, C, false);
129
134
  else if (Call.isCalled(VaCopy))
130
32
    checkVAListStartCall(Call, C, true);
131
102
  else if (Call.isCalled(VaEnd))
132
85
    checkVAListEndCall(Call, C);
133
17
  else {
134
127
    for (auto FuncInfo : VAListAccepters) {
135
127
      if (!Call.isCalled(FuncInfo.Func))
136
117
        continue;
137
10
      bool Symbolic;
138
10
      const MemRegion *VAList =
139
10
          getVAListAsRegion(Call.getArgSVal(FuncInfo.VAListPos),
140
10
                            Call.getArgExpr(FuncInfo.VAListPos), Symbolic, C);
141
10
      if (!VAList)
142
1
        return;
143
9
144
9
      if (C.getState()->contains<InitializedVALists>(VAList))
145
4
        return;
146
5
147
5
      // We did not see va_start call, but the source of the region is unknown.
148
5
      // Be conservative and assume the best.
149
5
      if (Symbolic)
150
2
        return;
151
3
152
3
      SmallString<80> Errmsg("Function '");
153
3
      Errmsg += FuncInfo.Func.getFunctionName();
154
3
      Errmsg += "' is called with an uninitialized va_list argument";
155
3
      reportUninitializedAccess(VAList, Errmsg.c_str(), C);
156
3
      break;
157
3
    }
158
17
  }
159
232
}
160
161
const MemRegion *ValistChecker::getVAListAsRegion(SVal SV, const Expr *E,
162
                                                  bool &IsSymbolic,
163
306
                                                  CheckerContext &C) const {
164
306
  const MemRegion *Reg = SV.getAsRegion();
165
306
  if (!Reg)
166
1
    return nullptr;
167
305
  // TODO: In the future this should be abstracted away by the analyzer.
168
305
  bool VaListModelledAsArray = false;
169
305
  if (const auto *Cast = dyn_cast<CastExpr>(E)) {
170
191
    QualType Ty = Cast->getType();
171
191
    VaListModelledAsArray =
172
191
        Ty->isPointerType() && Ty->getPointeeType()->isRecordType();
173
191
  }
174
305
  if (const auto *DeclReg = Reg->getAs<DeclRegion>()) {
175
106
    if (isa<ParmVarDecl>(DeclReg->getDecl()))
176
8
      Reg = C.getState()->getSVal(SV.castAs<Loc>()).getAsRegion();
177
106
  }
178
305
  IsSymbolic = Reg && Reg->getAs<SymbolicRegion>();
179
305
  // Some VarRegion based VA lists reach here as ElementRegions.
180
305
  const auto *EReg = dyn_cast_or_null<ElementRegion>(Reg);
181
305
  return (EReg && 
VaListModelledAsArray180
) ?
EReg->getSuperRegion()176
:
Reg129
;
182
305
}
183
184
void ValistChecker::checkPreStmt(const VAArgExpr *VAA,
185
49
                                 CheckerContext &C) const {
186
49
  ProgramStateRef State = C.getState();
187
49
  const Expr *VASubExpr = VAA->getSubExpr();
188
49
  SVal VAListSVal = C.getSVal(VASubExpr);
189
49
  bool Symbolic;
190
49
  const MemRegion *VAList =
191
49
      getVAListAsRegion(VAListSVal, VASubExpr, Symbolic, C);
192
49
  if (!VAList)
193
0
    return;
194
49
  if (Symbolic)
195
8
    return;
196
41
  if (!State->contains<InitializedVALists>(VAList))
197
15
    reportUninitializedAccess(
198
15
        VAList, "va_arg() is called on an uninitialized va_list", C);
199
41
}
200
201
void ValistChecker::checkDeadSymbols(SymbolReaper &SR,
202
585
                                     CheckerContext &C) const {
203
585
  ProgramStateRef State = C.getState();
204
585
  InitializedVAListsTy TrackedVALists = State->get<InitializedVALists>();
205
585
  RegionVector LeakedVALists;
206
585
  for (auto Reg : TrackedVALists) {
207
226
    if (SR.isLiveRegion(Reg))
208
194
      continue;
209
32
    LeakedVALists.push_back(Reg);
210
32
    State = State->remove<InitializedVALists>(Reg);
211
32
  }
212
585
  if (ExplodedNode *N = C.addTransition(State))
213
585
    reportLeakedVALists(LeakedVALists, "Initialized va_list", " is leaked", C,
214
585
                        N);
215
585
}
216
217
// This function traverses the exploded graph backwards and finds the node where
218
// the va_list is initialized. That node is used for uniquing the bug paths.
219
// It is not likely that there are several different va_lists that belongs to
220
// different stack frames, so that case is not yet handled.
221
const ExplodedNode *
222
ValistChecker::getStartCallSite(const ExplodedNode *N,
223
43
                                const MemRegion *Reg) const {
224
43
  const LocationContext *LeakContext = N->getLocationContext();
225
43
  const ExplodedNode *StartCallNode = N;
226
43
227
43
  bool FoundInitializedState = false;
228
43
229
416
  while (N) {
230
412
    ProgramStateRef State = N->getState();
231
412
    if (!State->contains<InitializedVALists>(Reg)) {
232
122
      if (FoundInitializedState)
233
39
        break;
234
290
    } else {
235
290
      FoundInitializedState = true;
236
290
    }
237
412
    const LocationContext *NContext = N->getLocationContext();
238
373
    if (NContext == LeakContext || 
NContext->isParentOf(LeakContext)0
)
239
373
      StartCallNode = N;
240
373
    N = N->pred_empty() ? 
nullptr4
:
*(N->pred_begin())369
;
241
373
  }
242
43
243
43
  return StartCallNode;
244
43
}
245
246
void ValistChecker::reportUninitializedAccess(const MemRegion *VAList,
247
                                              StringRef Msg,
248
37
                                              CheckerContext &C) const {
249
37
  if (!ChecksEnabled[CK_Uninitialized])
250
4
    return;
251
33
  if (ExplodedNode *N = C.generateErrorNode()) {
252
33
    if (!BT_uninitaccess)
253
4
      BT_uninitaccess.reset(new BugType(CheckNames[CK_Uninitialized],
254
4
                                        "Uninitialized va_list",
255
4
                                        categories::MemoryError));
256
33
    auto R = llvm::make_unique<BugReport>(*BT_uninitaccess, Msg, N);
257
33
    R->markInteresting(VAList);
258
33
    R->addVisitor(llvm::make_unique<ValistBugVisitor>(VAList));
259
33
    C.emitReport(std::move(R));
260
33
  }
261
33
}
262
263
void ValistChecker::reportLeakedVALists(const RegionVector &LeakedVALists,
264
                                        StringRef Msg1, StringRef Msg2,
265
                                        CheckerContext &C, ExplodedNode *N,
266
606
                                        bool ReportUninit) const {
267
606
  if (!(ChecksEnabled[CK_Unterminated] ||
268
606
        
(414
ChecksEnabled[CK_Uninitialized]414
&&
ReportUninit414
)))
269
407
    return;
270
199
  for (auto Reg : LeakedVALists) {
271
43
    if (!BT_leakedvalist) {
272
5
      // FIXME: maybe creating a new check name for this type of bug is a better
273
5
      // solution.
274
5
      BT_leakedvalist.reset(
275
5
          new BugType(CheckNames[CK_Unterminated].getName().empty()
276
5
                          ? 
CheckNames[CK_Uninitialized]3
277
5
                          : 
CheckNames[CK_Unterminated]2
,
278
5
                      "Leaked va_list", categories::MemoryError,
279
5
                      /*SuppressOnSink=*/true));
280
5
    }
281
43
282
43
    const ExplodedNode *StartNode = getStartCallSite(N, Reg);
283
43
    PathDiagnosticLocation LocUsedForUniqueing;
284
43
285
43
    if (const Stmt *StartCallStmt = PathDiagnosticLocation::getStmt(StartNode))
286
39
      LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
287
39
          StartCallStmt, C.getSourceManager(), StartNode->getLocationContext());
288
43
289
43
    SmallString<100> Buf;
290
43
    llvm::raw_svector_ostream OS(Buf);
291
43
    OS << Msg1;
292
43
    std::string VariableName = Reg->getDescriptiveName();
293
43
    if (!VariableName.empty())
294
37
      OS << " " << VariableName;
295
43
    OS << Msg2;
296
43
297
43
    auto R = llvm::make_unique<BugReport>(
298
43
        *BT_leakedvalist, OS.str(), N, LocUsedForUniqueing,
299
43
        StartNode->getLocationContext()->getDecl());
300
43
    R->markInteresting(Reg);
301
43
    R->addVisitor(llvm::make_unique<ValistBugVisitor>(Reg, true));
302
43
    C.emitReport(std::move(R));
303
43
  }
304
199
}
305
306
void ValistChecker::checkVAListStartCall(const CallEvent &Call,
307
130
                                         CheckerContext &C, bool IsCopy) const {
308
130
  bool Symbolic;
309
130
  const MemRegion *VAList =
310
130
      getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
311
130
  if (!VAList)
312
0
    return;
313
130
314
130
  ProgramStateRef State = C.getState();
315
130
316
130
  if (IsCopy) {
317
32
    const MemRegion *Arg2 =
318
32
        getVAListAsRegion(Call.getArgSVal(1), Call.getArgExpr(1), Symbolic, C);
319
32
    if (Arg2) {
320
32
      if (ChecksEnabled[CK_CopyToSelf] && 
VAList == Arg226
) {
321
8
        RegionVector LeakedVALists{VAList};
322
8
        if (ExplodedNode *N = C.addTransition(State))
323
8
          reportLeakedVALists(LeakedVALists, "va_list",
324
8
                              " is copied onto itself", C, N, true);
325
8
        return;
326
24
      } else if (!State->contains<InitializedVALists>(Arg2) && 
!Symbolic14
) {
327
11
        if (State->contains<InitializedVALists>(VAList)) {
328
5
          State = State->remove<InitializedVALists>(VAList);
329
5
          RegionVector LeakedVALists{VAList};
330
5
          if (ExplodedNode *N = C.addTransition(State))
331
5
            reportLeakedVALists(LeakedVALists, "Initialized va_list",
332
5
                                " is overwritten by an uninitialized one", C, N,
333
5
                                true);
334
6
        } else {
335
6
          reportUninitializedAccess(Arg2, "Uninitialized va_list is copied", C);
336
6
        }
337
11
        return;
338
11
      }
339
111
    }
340
32
  }
341
111
  if (State->contains<InitializedVALists>(VAList)) {
342
8
    RegionVector LeakedVALists{VAList};
343
8
    if (ExplodedNode *N = C.addTransition(State))
344
8
      reportLeakedVALists(LeakedVALists, "Initialized va_list",
345
8
                          " is initialized again", C, N);
346
8
    return;
347
8
  }
348
103
349
103
  State = State->add<InitializedVALists>(VAList);
350
103
  C.addTransition(State);
351
103
}
352
353
void ValistChecker::checkVAListEndCall(const CallEvent &Call,
354
85
                                       CheckerContext &C) const {
355
85
  bool Symbolic;
356
85
  const MemRegion *VAList =
357
85
      getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
358
85
  if (!VAList)
359
0
    return;
360
85
361
85
  // We did not see va_start call, but the source of the region is unknown.
362
85
  // Be conservative and assume the best.
363
85
  if (Symbolic)
364
7
    return;
365
78
366
78
  if (!C.getState()->contains<InitializedVALists>(VAList)) {
367
13
    reportUninitializedAccess(
368
13
        VAList, "va_end() is called on an uninitialized va_list", C);
369
13
    return;
370
13
  }
371
65
  ProgramStateRef State = C.getState();
372
65
  State = State->remove<InitializedVALists>(VAList);
373
65
  C.addTransition(State);
374
65
}
375
376
std::shared_ptr<PathDiagnosticPiece> ValistChecker::ValistBugVisitor::VisitNode(
377
    const ExplodedNode *N, BugReporterContext &BRC,
378
1.69k
    BugReport &) {
379
1.69k
  ProgramStateRef State = N->getState();
380
1.69k
  ProgramStateRef StatePrev = N->getFirstPred()->getState();
381
1.69k
382
1.69k
  const Stmt *S = PathDiagnosticLocation::getStmt(N);
383
1.69k
  if (!S)
384
97
    return nullptr;
385
1.59k
386
1.59k
  StringRef Msg;
387
1.59k
  if (State->contains<InitializedVALists>(Reg) &&
388
1.59k
      
!StatePrev->contains<InitializedVALists>(Reg)464
)
389
57
    Msg = "Initialized va_list";
390
1.53k
  else if (!State->contains<InitializedVALists>(Reg) &&
391
1.53k
           
StatePrev->contains<InitializedVALists>(Reg)1.12k
)
392
18
    Msg = "Ended va_list";
393
1.59k
394
1.59k
  if (Msg.empty())
395
1.51k
    return nullptr;
396
75
397
75
  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
398
75
                             N->getLocationContext());
399
75
  return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
400
75
}
401
402
7
void ento::registerValistBase(CheckerManager &mgr) {
403
7
  mgr.registerChecker<ValistChecker>();
404
7
}
405
406
0
bool ento::shouldRegisterValistBase(const LangOptions &LO) {
407
0
  return true;
408
0
}
409
410
#define REGISTER_CHECKER(name)                                                 \
411
13
  void ento::register##name##Checker(CheckerManager &mgr) {                    \
412
13
    ValistChecker *checker = mgr.getChecker<ValistChecker>();                  \
413
13
    checker->ChecksEnabled[ValistChecker::CK_##name] = true;                   \
414
13
    checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
415
13
  }                                                                            \
clang::ento::registerUninitializedChecker(clang::ento::CheckerManager&)
Line
Count
Source
411
5
  void ento::register##name##Checker(CheckerManager &mgr) {                    \
412
5
    ValistChecker *checker = mgr.getChecker<ValistChecker>();                  \
413
5
    checker->ChecksEnabled[ValistChecker::CK_##name] = true;                   \
414
5
    checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
415
5
  }                                                                            \
clang::ento::registerUnterminatedChecker(clang::ento::CheckerManager&)
Line
Count
Source
411
2
  void ento::register##name##Checker(CheckerManager &mgr) {                    \
412
2
    ValistChecker *checker = mgr.getChecker<ValistChecker>();                  \
413
2
    checker->ChecksEnabled[ValistChecker::CK_##name] = true;                   \
414
2
    checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
415
2
  }                                                                            \
clang::ento::registerCopyToSelfChecker(clang::ento::CheckerManager&)
Line
Count
Source
411
6
  void ento::register##name##Checker(CheckerManager &mgr) {                    \
412
6
    ValistChecker *checker = mgr.getChecker<ValistChecker>();                  \
413
6
    checker->ChecksEnabled[ValistChecker::CK_##name] = true;                   \
414
6
    checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
415
6
  }                                                                            \
416
                                                                               \
417
13
  bool ento::shouldRegister##name##Checker(const LangOptions &LO) {            \
418
13
    return true;                                                               \
419
13
  }
clang::ento::shouldRegisterUninitializedChecker(clang::LangOptions const&)
Line
Count
Source
417
5
  bool ento::shouldRegister##name##Checker(const LangOptions &LO) {            \
418
5
    return true;                                                               \
419
5
  }
clang::ento::shouldRegisterUnterminatedChecker(clang::LangOptions const&)
Line
Count
Source
417
2
  bool ento::shouldRegister##name##Checker(const LangOptions &LO) {            \
418
2
    return true;                                                               \
419
2
  }
clang::ento::shouldRegisterCopyToSelfChecker(clang::LangOptions const&)
Line
Count
Source
417
6
  bool ento::shouldRegister##name##Checker(const LangOptions &LO) {            \
418
6
    return true;                                                               \
419
6
  }
420
421
REGISTER_CHECKER(Uninitialized)
422
REGISTER_CHECKER(Unterminated)
423
REGISTER_CHECKER(CopyToSelf)