clang 23.0.0git
VAListChecker.cpp
Go to the documentation of this file.
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 a checker which detects usage of uninitialized va_list values
10// and va_start calls with no matching va_end.
11//
12//===----------------------------------------------------------------------===//
13
21#include "llvm/Support/FormatVariadic.h"
22
23using namespace clang;
24using namespace ento;
25using llvm::formatv;
26
27namespace {
28enum class VAListState {
30 Unknown,
32 Released,
33};
34
35constexpr llvm::StringLiteral StateNames[] = {
36 "uninitialized", "unknown", "initialized", "already released"};
37} // end anonymous namespace
38
39static StringRef describeState(const VAListState S) {
40 return StateNames[static_cast<int>(S)];
41}
42
43REGISTER_MAP_WITH_PROGRAMSTATE(VAListStateMap, const MemRegion *, VAListState)
44
45static VAListState getVAListState(ProgramStateRef State, const MemRegion *Reg) {
46 if (const VAListState *Res = State->get<VAListStateMap>(Reg))
47 return *Res;
48 return Reg->getSymbolicBase() ? VAListState::Unknown
49 : VAListState::Uninitialized;
50}
51
52namespace {
53typedef SmallVector<const MemRegion *, 2> RegionVector;
54
55class VAListChecker : public Checker<check::PreCall, check::PreStmt<VAArgExpr>,
56 check::DeadSymbols> {
57 const BugType LeakBug{this, "Leaked va_list", categories::MemoryError,
58 /*SuppressOnSink=*/true};
59 const BugType UninitAccessBug{this, "Uninitialized va_list",
61
62 struct VAListAccepter {
63 CallDescription Func;
64 int ParamIndex;
65 };
66 static const SmallVector<VAListAccepter, 15> VAListAccepters;
67 static const CallDescriptionSet VaStart;
68 static const CallDescription VaEnd, VaCopy;
69
70public:
71 void checkPreStmt(const VAArgExpr *VAA, CheckerContext &C) const;
72 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
73 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
74
75private:
76 const MemRegion *getVAListAsRegion(SVal SV, const Expr *VAExpr,
77 CheckerContext &C) const;
78 const ExplodedNode *getStartCallSite(const ExplodedNode *N,
79 const MemRegion *Reg) const;
80
81 void reportUninitializedAccess(const MemRegion *VAList, StringRef Msg,
82 CheckerContext &C) const;
83 void reportLeaked(const RegionVector &Leaked, StringRef Msg1, StringRef Msg2,
84 CheckerContext &C, ExplodedNode *N) const;
85
86 void checkVAListStartCall(const CallEvent &Call, CheckerContext &C) const;
87 void checkVAListCopyCall(const CallEvent &Call, CheckerContext &C) const;
88 void checkVAListEndCall(const CallEvent &Call, CheckerContext &C) const;
89
90 class VAListBugVisitor : public BugReporterVisitor {
91 public:
92 VAListBugVisitor(const MemRegion *Reg, bool IsLeak = false)
93 : Reg(Reg), IsLeak(IsLeak) {}
94 void Profile(llvm::FoldingSetNodeID &ID) const override {
95 static int X = 0;
96 ID.AddPointer(&X);
97 ID.AddPointer(Reg);
98 }
99 PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC,
100 const ExplodedNode *EndPathNode,
101 PathSensitiveBugReport &BR) override {
102 if (!IsLeak)
103 return nullptr;
104
105 PathDiagnosticLocation L = BR.getLocation();
106 // Do not add the statement itself as a range in case of leak.
107 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
108 false);
109 }
110 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
111 BugReporterContext &BRC,
112 PathSensitiveBugReport &BR) override;
113
114 private:
115 const MemRegion *Reg;
116 bool IsLeak;
117 };
118};
119
121 VAListChecker::VAListAccepters = {{{CDM::CLibrary, {"vfprintf"}, 3}, 2},
122 {{CDM::CLibrary, {"vfscanf"}, 3}, 2},
123 {{CDM::CLibrary, {"vprintf"}, 2}, 1},
124 {{CDM::CLibrary, {"vscanf"}, 2}, 1},
125 {{CDM::CLibrary, {"vsnprintf"}, 4}, 3},
126 {{CDM::CLibrary, {"vsprintf"}, 3}, 2},
127 {{CDM::CLibrary, {"vsscanf"}, 3}, 2},
128 {{CDM::CLibrary, {"vfwprintf"}, 3}, 2},
129 {{CDM::CLibrary, {"vfwscanf"}, 3}, 2},
130 {{CDM::CLibrary, {"vwprintf"}, 2}, 1},
131 {{CDM::CLibrary, {"vwscanf"}, 2}, 1},
132 {{CDM::CLibrary, {"vswprintf"}, 4}, 3},
133 // vswprintf is the wide version of
134 // vsnprintf, vsprintf has no wide version
135 {{CDM::CLibrary, {"vswscanf"}, 3}, 2}};
136
137const CallDescriptionSet VAListChecker::VaStart{
138 {CDM::CLibrary, {"__builtin_va_start"}},
139 {CDM::CLibrary, {"__builtin_c23_va_start"}}};
140
141const CallDescription VAListChecker::VaCopy(CDM::CLibrary,
142 {"__builtin_va_copy"}, 2),
143 VAListChecker::VaEnd(CDM::CLibrary, {"__builtin_va_end"}, 1);
144} // end anonymous namespace
145
146void VAListChecker::checkPreCall(const CallEvent &Call,
147 CheckerContext &C) const {
148 if (VaStart.contains(Call))
149 checkVAListStartCall(Call, C);
150 else if (VaCopy.matches(Call))
151 checkVAListCopyCall(Call, C);
152 else if (VaEnd.matches(Call))
153 checkVAListEndCall(Call, C);
154 else {
155 for (const auto &FuncInfo : VAListAccepters) {
156 if (!FuncInfo.Func.matches(Call))
157 continue;
158 const MemRegion *VAList =
159 getVAListAsRegion(Call.getArgSVal(FuncInfo.ParamIndex),
160 Call.getArgExpr(FuncInfo.ParamIndex), C);
161 if (!VAList)
162 return;
163 VAListState S = getVAListState(C.getState(), VAList);
164
165 if (S == VAListState::Initialized || S == VAListState::Unknown)
166 return;
167
168 std::string ErrMsg =
169 formatv("Function '{0}' is called with an {1} va_list argument",
170 FuncInfo.Func.getFunctionName(), describeState(S));
171 reportUninitializedAccess(VAList, ErrMsg, C);
172 break;
173 }
174 }
175}
176
177const MemRegion *VAListChecker::getVAListAsRegion(SVal SV, const Expr *E,
178 CheckerContext &C) const {
179 const MemRegion *Reg = SV.getAsRegion();
180 if (!Reg)
181 return nullptr;
182 // TODO: In the future this should be abstracted away by the analyzer.
183 bool VAListModelledAsArray = false;
184 if (const auto *Cast = dyn_cast<CastExpr>(E)) {
185 QualType Ty = Cast->getType();
186 VAListModelledAsArray =
187 Ty->isPointerType() && Ty->getPointeeType()->isRecordType();
188 }
189 if (const auto *DeclReg = Reg->getAs<DeclRegion>()) {
190 if (isa<ParmVarDecl>(DeclReg->getDecl()))
191 Reg = C.getState()->getSVal(SV.castAs<Loc>()).getAsRegion();
192 }
193 // Some VarRegion based VA lists reach here as ElementRegions.
194 const auto *EReg = dyn_cast_or_null<ElementRegion>(Reg);
195 return (EReg && VAListModelledAsArray) ? EReg->getSuperRegion() : Reg;
196}
197
198void VAListChecker::checkPreStmt(const VAArgExpr *VAA,
199 CheckerContext &C) const {
200 ProgramStateRef State = C.getState();
201 const Expr *ArgExpr = VAA->getSubExpr();
202 const MemRegion *VAList = getVAListAsRegion(C.getSVal(ArgExpr), ArgExpr, C);
203 if (!VAList)
204 return;
205 VAListState S = getVAListState(C.getState(), VAList);
206 if (S == VAListState::Initialized || S == VAListState::Unknown)
207 return;
208
209 std::string ErrMsg =
210 formatv("va_arg() is called on an {0} va_list", describeState(S));
211 reportUninitializedAccess(VAList, ErrMsg, C);
212}
213
214void VAListChecker::checkDeadSymbols(SymbolReaper &SR,
215 CheckerContext &C) const {
216 ProgramStateRef State = C.getState();
217 VAListStateMapTy Tracked = State->get<VAListStateMap>();
218 RegionVector Leaked;
219 for (const auto &[Reg, S] : Tracked) {
220 if (SR.isLiveRegion(Reg))
221 continue;
222 if (S == VAListState::Initialized)
223 Leaked.push_back(Reg);
224 State = State->remove<VAListStateMap>(Reg);
225 }
226 if (ExplodedNode *N = C.addTransition(State)) {
227 reportLeaked(Leaked, "Initialized va_list", " is leaked", C, N);
228 }
229}
230
231// This function traverses the exploded graph backwards and finds the node where
232// the va_list becomes initialized. That node is used for uniquing the bug
233// paths. It is not likely that there are several different va_lists that
234// belongs to different stack frames, so that case is not yet handled.
235const ExplodedNode *
236VAListChecker::getStartCallSite(const ExplodedNode *N,
237 const MemRegion *Reg) const {
238 const LocationContext *LeakContext = N->getLocationContext();
239 const ExplodedNode *StartCallNode = N;
240
241 bool SeenInitializedState = false;
242
243 while (N) {
244 VAListState S = getVAListState(N->getState(), Reg);
245 if (S == VAListState::Initialized) {
246 SeenInitializedState = true;
247 } else if (SeenInitializedState) {
248 break;
249 }
250 const LocationContext *NContext = N->getLocationContext();
251 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
252 StartCallNode = N;
253 N = N->pred_empty() ? nullptr : *(N->pred_begin());
254 }
255
256 return StartCallNode;
257}
258
259void VAListChecker::reportUninitializedAccess(const MemRegion *VAList,
260 StringRef Msg,
261 CheckerContext &C) const {
262 if (ExplodedNode *N = C.generateErrorNode()) {
263 auto R = std::make_unique<PathSensitiveBugReport>(UninitAccessBug, Msg, N);
264 R->markInteresting(VAList);
265 R->addVisitor(std::make_unique<VAListBugVisitor>(VAList));
266 C.emitReport(std::move(R));
267 }
268}
269
270void VAListChecker::reportLeaked(const RegionVector &Leaked, StringRef Msg1,
271 StringRef Msg2, CheckerContext &C,
272 ExplodedNode *N) const {
273 for (const MemRegion *Reg : Leaked) {
274 const ExplodedNode *StartNode = getStartCallSite(N, Reg);
275 PathDiagnosticLocation LocUsedForUniqueing;
276
277 if (const Stmt *StartCallStmt = StartNode->getStmtForDiagnostics())
278 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
279 StartCallStmt, C.getSourceManager(), StartNode->getLocationContext());
280
281 SmallString<100> Buf;
282 llvm::raw_svector_ostream OS(Buf);
283 OS << Msg1;
284 std::string VariableName = Reg->getDescriptiveName();
285 if (!VariableName.empty())
286 OS << " " << VariableName;
287 OS << Msg2;
288
289 auto R = std::make_unique<PathSensitiveBugReport>(
290 LeakBug, OS.str(), N, LocUsedForUniqueing,
291 StartNode->getLocationContext()->getDecl());
292 R->markInteresting(Reg);
293 R->addVisitor(std::make_unique<VAListBugVisitor>(Reg, true));
294 C.emitReport(std::move(R));
295 }
296}
297
298void VAListChecker::checkVAListStartCall(const CallEvent &Call,
299 CheckerContext &C) const {
300 if (Call.getNumArgs() == 0)
301 return; // Prevent a crash on grossly invalid input.
302
303 const MemRegion *Arg =
304 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), C);
305 if (!Arg)
306 return;
307
308 ProgramStateRef State = C.getState();
309 VAListState ArgState = getVAListState(State, Arg);
310
311 if (ArgState == VAListState::Initialized) {
312 RegionVector Leaked{Arg};
313 if (ExplodedNode *N = C.addTransition(State))
314 reportLeaked(Leaked, "Initialized va_list", " is initialized again", C,
315 N);
316 return;
317 }
318
319 State = State->set<VAListStateMap>(Arg, VAListState::Initialized);
320 C.addTransition(State);
321}
322
323void VAListChecker::checkVAListCopyCall(const CallEvent &Call,
324 CheckerContext &C) const {
325 const MemRegion *Arg1 =
326 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), C);
327 const MemRegion *Arg2 =
328 getVAListAsRegion(Call.getArgSVal(1), Call.getArgExpr(1), C);
329 if (!Arg1 || !Arg2)
330 return;
331
332 ProgramStateRef State = C.getState();
333 if (Arg1 == Arg2) {
334 RegionVector Leaked{Arg1};
335 if (ExplodedNode *N = C.addTransition(State))
336 reportLeaked(Leaked, "va_list", " is copied onto itself", C, N);
337 return;
338 }
339 VAListState State1 = getVAListState(State, Arg1);
340 VAListState State2 = getVAListState(State, Arg2);
341 // Update the ProgramState by copying the state of Arg2 to Arg1.
342 State = State->set<VAListStateMap>(Arg1, State2);
343 if (State1 == VAListState::Initialized) {
344 RegionVector Leaked{Arg1};
345 std::string Msg2 =
346 formatv(" is overwritten by {0} {1} one",
347 (State2 == VAListState::Initialized) ? "another" : "an",
348 describeState(State2));
349 if (ExplodedNode *N = C.addTransition(State))
350 reportLeaked(Leaked, "Initialized va_list", Msg2, C, N);
351 return;
352 }
353 if (State2 != VAListState::Initialized && State2 != VAListState::Unknown) {
354 std::string Msg = formatv("{0} va_list is copied", describeState(State2));
355 Msg[0] = toupper(Msg[0]);
356 reportUninitializedAccess(Arg2, Msg, C);
357 return;
358 }
359 C.addTransition(State);
360}
361
362void VAListChecker::checkVAListEndCall(const CallEvent &Call,
363 CheckerContext &C) const {
364 const MemRegion *Arg =
365 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), C);
366 if (!Arg)
367 return;
368
369 ProgramStateRef State = C.getState();
370 VAListState ArgState = getVAListState(State, Arg);
371
372 if (ArgState != VAListState::Unknown &&
373 ArgState != VAListState::Initialized) {
374 std::string Msg = formatv("va_end() is called on an {0} va_list",
375 describeState(ArgState));
376 reportUninitializedAccess(Arg, Msg, C);
377 return;
378 }
379 State = State->set<VAListStateMap>(Arg, VAListState::Released);
380 C.addTransition(State);
381}
382
383PathDiagnosticPieceRef VAListChecker::VAListBugVisitor::VisitNode(
384 const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) {
385 ProgramStateRef State = N->getState();
386 ProgramStateRef StatePrev = N->getFirstPred()->getState();
387
388 const Stmt *S = N->getStmtForDiagnostics();
389 if (!S)
390 return nullptr;
391
392 VAListState After = getVAListState(State, Reg);
393 VAListState Before = getVAListState(StatePrev, Reg);
394 if (Before == After)
395 return nullptr;
396
397 StringRef Msg;
398 switch (After) {
399 case VAListState::Uninitialized:
400 Msg = "Copied uninitialized contents into the va_list";
401 break;
402 case VAListState::Unknown:
403 Msg = "Copied unknown contents into the va_list";
404 break;
405 case VAListState::Initialized:
406 Msg = "Initialized va_list";
407 break;
408 case VAListState::Released:
409 Msg = "Ended va_list";
410 break;
411 }
412
413 if (Msg.empty())
414 return nullptr;
415
416 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
417 N->getLocationContext());
418 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
419}
420
421void ento::registerVAListChecker(CheckerManager &Mgr) {
422 Mgr.registerChecker<VAListChecker>();
423}
424
425bool ento::shouldRegisterVAListChecker(const CheckerManager &) { return true; }
#define X(type, name)
Definition Value.h:97
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
static VAListState getVAListState(ProgramStateRef State, const MemRegion *Reg)
static StringRef describeState(const VAListState S)
bool isParentOf(const LocationContext *LC) const
const Decl * getDecl() const
bool isPointerType() const
Definition TypeBase.h:8682
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isRecordType() const
Definition TypeBase.h:8809
const Expr * getSubExpr() const
Definition Expr.h:4976
StringRef getDescription() const
A verbose warning message that is appropriate for displaying next to the source code that introduces ...
const SourceManager & getSourceManager() const
An immutable set of CallDescriptions.
bool contains(const CallEvent &Call) const
A CallDescription is a pattern that can be used to match calls based on the qualified name and the ar...
bool matches(const CallEvent &Call) const
Returns true if the CallEvent is a call to a function that matches the CallDescription.
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:153
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:553
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
const LocationContext * getLocationContext() const
ExplodedNode * getFirstPred()
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:98
std::string getDescriptiveName(bool UseQuotes=true) const
Get descriptive name for memory region.
const RegionTy * getAs() const
Definition MemRegion.h:1421
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
PathDiagnosticLocation getLocation() const override
The primary location of the bug report that points at the undesirable behavior in the code.
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:83
bool isLiveRegion(const MemRegion *region)
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
@ After
Like System, but searched after the system directories.
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2687
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...