Coverage Report

Created: 2022-01-15 10:30

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