Coverage Report

Created: 2023-09-30 09:22

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