clang 24.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(const ExplodedNode *EndPathNode,
100 BugReporterContext &BRC,
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 const Expr *ArgExpr = VAA->getSubExpr();
201 const MemRegion *VAList = getVAListAsRegion(C.getSVal(ArgExpr), ArgExpr, C);
202 if (!VAList)
203 return;
204 VAListState S = getVAListState(C.getState(), VAList);
205 if (S == VAListState::Initialized || S == VAListState::Unknown)
206 return;
207
208 std::string ErrMsg =
209 formatv("va_arg() is called on an {0} va_list", describeState(S));
210 reportUninitializedAccess(VAList, ErrMsg, C);
211}
212
213void VAListChecker::checkDeadSymbols(SymbolReaper &SR,
214 CheckerContext &C) const {
215 ProgramStateRef State = C.getState();
216 VAListStateMapTy Tracked = State->get<VAListStateMap>();
217 RegionVector Leaked;
218 for (const auto &[Reg, S] : Tracked) {
219 if (SR.isLiveRegion(Reg))
220 continue;
221 if (S == VAListState::Initialized)
222 Leaked.push_back(Reg);
223 State = State->remove<VAListStateMap>(Reg);
224 }
225 if (ExplodedNode *N = C.addTransition(State)) {
226 reportLeaked(Leaked, "Initialized va_list", " is leaked", C, N);
227 }
228}
229
230// This function traverses the exploded graph backwards and finds the node where
231// the va_list becomes initialized. That node is used for uniquing the bug
232// paths. It is not likely that there are several different va_lists that
233// belongs to different stack frames, so that case is not yet handled.
234const ExplodedNode *
235VAListChecker::getStartCallSite(const ExplodedNode *N,
236 const MemRegion *Reg) const {
237 const StackFrame *LeakSF = N->getStackFrame();
238 const ExplodedNode *StartCallNode = N;
239
240 bool SeenInitializedState = false;
241
242 while (N) {
243 VAListState S = getVAListState(N->getState(), Reg);
244 if (S == VAListState::Initialized) {
245 SeenInitializedState = true;
246 } else if (SeenInitializedState) {
247 break;
248 }
249 if (N->getStackFrame() == LeakSF || N->getStackFrame()->isParentOf(LeakSF))
250 StartCallNode = N;
251 N = N->pred_empty() ? nullptr : *(N->pred_begin());
252 }
253
254 return StartCallNode;
255}
256
257void VAListChecker::reportUninitializedAccess(const MemRegion *VAList,
258 StringRef Msg,
259 CheckerContext &C) const {
260 if (ExplodedNode *N = C.generateErrorNode()) {
261 auto R = std::make_unique<PathSensitiveBugReport>(UninitAccessBug, Msg, N);
262 R->markInteresting(VAList);
263 R->addVisitor(std::make_unique<VAListBugVisitor>(VAList));
264 C.emitReport(std::move(R));
265 }
266}
267
268void VAListChecker::reportLeaked(const RegionVector &Leaked, StringRef Msg1,
269 StringRef Msg2, CheckerContext &C,
270 ExplodedNode *N) const {
271 for (const MemRegion *Reg : Leaked) {
272 const ExplodedNode *StartNode = getStartCallSite(N, Reg);
273 PathDiagnosticLocation LocUsedForUniqueing;
274
275 if (const Stmt *StartCallStmt = StartNode->getStmtForDiagnostics())
276 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
277 StartCallStmt, C.getSourceManager(), StartNode->getStackFrame());
278
279 SmallString<100> Buf;
280 llvm::raw_svector_ostream OS(Buf);
281 OS << Msg1;
282 std::string VariableName = Reg->getDescriptiveName();
283 if (!VariableName.empty())
284 OS << " " << VariableName;
285 OS << Msg2;
286
287 auto R = std::make_unique<PathSensitiveBugReport>(
288 LeakBug, OS.str(), N, LocUsedForUniqueing,
289 StartNode->getStackFrame()->getDecl());
290 R->markInteresting(Reg);
291 R->addVisitor(std::make_unique<VAListBugVisitor>(Reg, true));
292 C.emitReport(std::move(R));
293 }
294}
295
296void VAListChecker::checkVAListStartCall(const CallEvent &Call,
297 CheckerContext &C) const {
298 if (Call.getNumArgs() == 0)
299 return; // Prevent a crash on grossly invalid input.
300
301 const MemRegion *Arg =
302 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), C);
303 if (!Arg)
304 return;
305
306 ProgramStateRef State = C.getState();
307 VAListState ArgState = getVAListState(State, Arg);
308
309 if (ArgState == VAListState::Initialized) {
310 RegionVector Leaked{Arg};
311 if (ExplodedNode *N = C.addTransition(State))
312 reportLeaked(Leaked, "Initialized va_list", " is initialized again", C,
313 N);
314 return;
315 }
316
317 State = State->set<VAListStateMap>(Arg, VAListState::Initialized);
318 C.addTransition(State);
319}
320
321void VAListChecker::checkVAListCopyCall(const CallEvent &Call,
322 CheckerContext &C) const {
323 const MemRegion *Arg1 =
324 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), C);
325 const MemRegion *Arg2 =
326 getVAListAsRegion(Call.getArgSVal(1), Call.getArgExpr(1), C);
327 if (!Arg1 || !Arg2)
328 return;
329
330 ProgramStateRef State = C.getState();
331 if (Arg1 == Arg2) {
332 RegionVector Leaked{Arg1};
333 if (ExplodedNode *N = C.addTransition(State))
334 reportLeaked(Leaked, "va_list", " is copied onto itself", C, N);
335 return;
336 }
337 VAListState State1 = getVAListState(State, Arg1);
338 VAListState State2 = getVAListState(State, Arg2);
339 // Update the ProgramState by copying the state of Arg2 to Arg1.
340 State = State->set<VAListStateMap>(Arg1, State2);
341 if (State1 == VAListState::Initialized) {
342 RegionVector Leaked{Arg1};
343 std::string Msg2 =
344 formatv(" is overwritten by {0} {1} one",
345 (State2 == VAListState::Initialized) ? "another" : "an",
346 describeState(State2));
347 if (ExplodedNode *N = C.addTransition(State))
348 reportLeaked(Leaked, "Initialized va_list", Msg2, C, N);
349 return;
350 }
351 if (State2 != VAListState::Initialized && State2 != VAListState::Unknown) {
352 std::string Msg = formatv("{0} va_list is copied", describeState(State2));
353 Msg[0] = toupper(Msg[0]);
354 reportUninitializedAccess(Arg2, Msg, C);
355 return;
356 }
357 C.addTransition(State);
358}
359
360void VAListChecker::checkVAListEndCall(const CallEvent &Call,
361 CheckerContext &C) const {
362 const MemRegion *Arg =
363 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), C);
364 if (!Arg)
365 return;
366
367 ProgramStateRef State = C.getState();
368 VAListState ArgState = getVAListState(State, Arg);
369
370 if (ArgState != VAListState::Unknown &&
371 ArgState != VAListState::Initialized) {
372 std::string Msg = formatv("va_end() is called on an {0} va_list",
373 describeState(ArgState));
374 reportUninitializedAccess(Arg, Msg, C);
375 return;
376 }
377 State = State->set<VAListStateMap>(Arg, VAListState::Released);
378 C.addTransition(State);
379}
380
381PathDiagnosticPieceRef VAListChecker::VAListBugVisitor::VisitNode(
382 const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) {
383 ProgramStateRef State = N->getState();
384 ProgramStateRef StatePrev = N->getFirstPred()->getState();
385
386 const Stmt *S = N->getStmtForDiagnostics();
387 if (!S)
388 return nullptr;
389
390 VAListState After = getVAListState(State, Reg);
391 VAListState Before = getVAListState(StatePrev, Reg);
392 if (Before == After)
393 return nullptr;
394
395 StringRef Msg;
396 switch (After) {
397 case VAListState::Uninitialized:
398 Msg = "Copied uninitialized contents into the va_list";
399 break;
400 case VAListState::Unknown:
401 Msg = "Copied unknown contents into the va_list";
402 break;
403 case VAListState::Initialized:
404 Msg = "Initialized va_list";
405 break;
406 case VAListState::Released:
407 Msg = "Ended va_list";
408 break;
409 }
410
411 if (Msg.empty())
412 return nullptr;
413
414 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), N->getStackFrame());
415 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
416}
417
418void ento::registerVAListChecker(CheckerManager &Mgr) {
419 Mgr.registerChecker<VAListChecker>();
420}
421
422bool 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 StackFrame *SF) const
const Decl * getDecl() const
bool isPointerType() const
Definition TypeBase.h:8732
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:8859
const Expr * getSubExpr() const
Definition Expr.h:4983
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:152
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:565
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
std::string getDescriptiveName(bool UseQuotes=true) const
Get descriptive name for memory region.
const RegionTy * getAs() const
Definition MemRegion.h:1419
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:84
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:2820
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',...