1 //== ValistChecker.cpp - stdarg.h macro usage checker -----------*- C++ -*--==//
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
7 //===----------------------------------------------------------------------===//
9 // This defines checkers which detect usage of uninitialized va_list values
10 // and va_start calls with no matching va_end.
12 //===----------------------------------------------------------------------===//
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"
21 using namespace clang;
24 REGISTER_SET_WITH_PROGRAMSTATE(InitializedVALists, const MemRegion *)
27 typedef SmallVector<const MemRegion *, 2> RegionVector;
29 class ValistChecker : public Checker<check::PreCall, check::PreStmt<VAArgExpr>,
31 mutable std::unique_ptr<BugType> BT_leakedvalist, BT_uninitaccess;
33 struct VAListAccepter {
37 static const SmallVector<VAListAccepter, 15> VAListAccepters;
38 static const CallDescription VaStart, VaEnd, VaCopy;
48 DefaultBool ChecksEnabled[CK_NumCheckKinds];
49 CheckName CheckNames[CK_NumCheckKinds];
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;
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;
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;
67 void checkVAListStartCall(const CallEvent &Call, CheckerContext &C,
69 void checkVAListEndCall(const CallEvent &Call, CheckerContext &C) const;
71 class ValistBugVisitor : public BugReporterVisitor {
73 ValistBugVisitor(const MemRegion *Reg, bool IsLeak = false)
74 : Reg(Reg), IsLeak(IsLeak) {}
75 void Profile(llvm::FoldingSetNodeID &ID) const override {
80 std::shared_ptr<PathDiagnosticPiece>
81 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
82 BugReport &BR) override {
86 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(
87 EndPathNode, BRC.getSourceManager());
88 // Do not add the statement itself as a range in case of leak.
89 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(), false);
91 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
92 BugReporterContext &BRC,
93 BugReport &BR) override;
101 const SmallVector<ValistChecker::VAListAccepter, 15>
102 ValistChecker::VAListAccepters = {
103 {{"vfprintf", 3}, 2},
107 {{"vsnprintf", 4}, 3},
108 {{"vsprintf", 3}, 2},
110 {{"vfwprintf", 3}, 2},
111 {{"vfwscanf", 3}, 2},
112 {{"vwprintf", 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
123 void ValistChecker::checkPreCall(const CallEvent &Call,
124 CheckerContext &C) const {
125 if (!Call.isGlobalCFunction())
127 if (Call.isCalled(VaStart))
128 checkVAListStartCall(Call, C, false);
129 else if (Call.isCalled(VaCopy))
130 checkVAListStartCall(Call, C, true);
131 else if (Call.isCalled(VaEnd))
132 checkVAListEndCall(Call, C);
134 for (auto FuncInfo : VAListAccepters) {
135 if (!Call.isCalled(FuncInfo.Func))
138 const MemRegion *VAList =
139 getVAListAsRegion(Call.getArgSVal(FuncInfo.VAListPos),
140 Call.getArgExpr(FuncInfo.VAListPos), Symbolic, C);
144 if (C.getState()->contains<InitializedVALists>(VAList))
147 // We did not see va_start call, but the source of the region is unknown.
148 // Be conservative and assume the best.
152 SmallString<80> Errmsg("Function '");
153 Errmsg += FuncInfo.Func.getFunctionName();
154 Errmsg += "' is called with an uninitialized va_list argument";
155 reportUninitializedAccess(VAList, Errmsg.c_str(), C);
161 const MemRegion *ValistChecker::getVAListAsRegion(SVal SV, const Expr *E,
163 CheckerContext &C) const {
164 const MemRegion *Reg = SV.getAsRegion();
167 // TODO: In the future this should be abstracted away by the analyzer.
168 bool VaListModelledAsArray = false;
169 if (const auto *Cast = dyn_cast<CastExpr>(E)) {
170 QualType Ty = Cast->getType();
171 VaListModelledAsArray =
172 Ty->isPointerType() && Ty->getPointeeType()->isRecordType();
174 if (const auto *DeclReg = Reg->getAs<DeclRegion>()) {
175 if (isa<ParmVarDecl>(DeclReg->getDecl()))
176 Reg = C.getState()->getSVal(SV.castAs<Loc>()).getAsRegion();
178 IsSymbolic = Reg && Reg->getAs<SymbolicRegion>();
179 // Some VarRegion based VA lists reach here as ElementRegions.
180 const auto *EReg = dyn_cast_or_null<ElementRegion>(Reg);
181 return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg;
184 void ValistChecker::checkPreStmt(const VAArgExpr *VAA,
185 CheckerContext &C) const {
186 ProgramStateRef State = C.getState();
187 const Expr *VASubExpr = VAA->getSubExpr();
188 SVal VAListSVal = C.getSVal(VASubExpr);
190 const MemRegion *VAList =
191 getVAListAsRegion(VAListSVal, VASubExpr, Symbolic, C);
196 if (!State->contains<InitializedVALists>(VAList))
197 reportUninitializedAccess(
198 VAList, "va_arg() is called on an uninitialized va_list", C);
201 void ValistChecker::checkDeadSymbols(SymbolReaper &SR,
202 CheckerContext &C) const {
203 ProgramStateRef State = C.getState();
204 InitializedVAListsTy TrackedVALists = State->get<InitializedVALists>();
205 RegionVector LeakedVALists;
206 for (auto Reg : TrackedVALists) {
207 if (SR.isLiveRegion(Reg))
209 LeakedVALists.push_back(Reg);
210 State = State->remove<InitializedVALists>(Reg);
212 if (ExplodedNode *N = C.addTransition(State))
213 reportLeakedVALists(LeakedVALists, "Initialized va_list", " is leaked", C,
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.
222 ValistChecker::getStartCallSite(const ExplodedNode *N,
223 const MemRegion *Reg) const {
224 const LocationContext *LeakContext = N->getLocationContext();
225 const ExplodedNode *StartCallNode = N;
227 bool FoundInitializedState = false;
230 ProgramStateRef State = N->getState();
231 if (!State->contains<InitializedVALists>(Reg)) {
232 if (FoundInitializedState)
235 FoundInitializedState = true;
237 const LocationContext *NContext = N->getLocationContext();
238 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
240 N = N->pred_empty() ? nullptr : *(N->pred_begin());
243 return StartCallNode;
246 void ValistChecker::reportUninitializedAccess(const MemRegion *VAList,
248 CheckerContext &C) const {
249 if (!ChecksEnabled[CK_Uninitialized])
251 if (ExplodedNode *N = C.generateErrorNode()) {
252 if (!BT_uninitaccess)
253 BT_uninitaccess.reset(new BugType(CheckNames[CK_Uninitialized],
254 "Uninitialized va_list",
255 categories::MemoryError));
256 auto R = llvm::make_unique<BugReport>(*BT_uninitaccess, Msg, N);
257 R->markInteresting(VAList);
258 R->addVisitor(llvm::make_unique<ValistBugVisitor>(VAList));
259 C.emitReport(std::move(R));
263 void ValistChecker::reportLeakedVALists(const RegionVector &LeakedVALists,
264 StringRef Msg1, StringRef Msg2,
265 CheckerContext &C, ExplodedNode *N,
266 bool ReportUninit) const {
267 if (!(ChecksEnabled[CK_Unterminated] ||
268 (ChecksEnabled[CK_Uninitialized] && ReportUninit)))
270 for (auto Reg : LeakedVALists) {
271 if (!BT_leakedvalist) {
272 // FIXME: maybe creating a new check name for this type of bug is a better
274 BT_leakedvalist.reset(
275 new BugType(CheckNames[CK_Unterminated].getName().empty()
276 ? CheckNames[CK_Uninitialized]
277 : CheckNames[CK_Unterminated],
278 "Leaked va_list", categories::MemoryError,
279 /*SuppressOnSink=*/true));
282 const ExplodedNode *StartNode = getStartCallSite(N, Reg);
283 PathDiagnosticLocation LocUsedForUniqueing;
285 if (const Stmt *StartCallStmt = PathDiagnosticLocation::getStmt(StartNode))
286 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
287 StartCallStmt, C.getSourceManager(), StartNode->getLocationContext());
289 SmallString<100> Buf;
290 llvm::raw_svector_ostream OS(Buf);
292 std::string VariableName = Reg->getDescriptiveName();
293 if (!VariableName.empty())
294 OS << " " << VariableName;
297 auto R = llvm::make_unique<BugReport>(
298 *BT_leakedvalist, OS.str(), N, LocUsedForUniqueing,
299 StartNode->getLocationContext()->getDecl());
300 R->markInteresting(Reg);
301 R->addVisitor(llvm::make_unique<ValistBugVisitor>(Reg, true));
302 C.emitReport(std::move(R));
306 void ValistChecker::checkVAListStartCall(const CallEvent &Call,
307 CheckerContext &C, bool IsCopy) const {
309 const MemRegion *VAList =
310 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
314 ProgramStateRef State = C.getState();
317 const MemRegion *Arg2 =
318 getVAListAsRegion(Call.getArgSVal(1), Call.getArgExpr(1), Symbolic, C);
320 if (ChecksEnabled[CK_CopyToSelf] && VAList == Arg2) {
321 RegionVector LeakedVALists{VAList};
322 if (ExplodedNode *N = C.addTransition(State))
323 reportLeakedVALists(LeakedVALists, "va_list",
324 " is copied onto itself", C, N, true);
326 } else if (!State->contains<InitializedVALists>(Arg2) && !Symbolic) {
327 if (State->contains<InitializedVALists>(VAList)) {
328 State = State->remove<InitializedVALists>(VAList);
329 RegionVector LeakedVALists{VAList};
330 if (ExplodedNode *N = C.addTransition(State))
331 reportLeakedVALists(LeakedVALists, "Initialized va_list",
332 " is overwritten by an uninitialized one", C, N,
335 reportUninitializedAccess(Arg2, "Uninitialized va_list is copied", C);
341 if (State->contains<InitializedVALists>(VAList)) {
342 RegionVector LeakedVALists{VAList};
343 if (ExplodedNode *N = C.addTransition(State))
344 reportLeakedVALists(LeakedVALists, "Initialized va_list",
345 " is initialized again", C, N);
349 State = State->add<InitializedVALists>(VAList);
350 C.addTransition(State);
353 void ValistChecker::checkVAListEndCall(const CallEvent &Call,
354 CheckerContext &C) const {
356 const MemRegion *VAList =
357 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
361 // We did not see va_start call, but the source of the region is unknown.
362 // Be conservative and assume the best.
366 if (!C.getState()->contains<InitializedVALists>(VAList)) {
367 reportUninitializedAccess(
368 VAList, "va_end() is called on an uninitialized va_list", C);
371 ProgramStateRef State = C.getState();
372 State = State->remove<InitializedVALists>(VAList);
373 C.addTransition(State);
376 std::shared_ptr<PathDiagnosticPiece> ValistChecker::ValistBugVisitor::VisitNode(
377 const ExplodedNode *N, BugReporterContext &BRC,
379 ProgramStateRef State = N->getState();
380 ProgramStateRef StatePrev = N->getFirstPred()->getState();
382 const Stmt *S = PathDiagnosticLocation::getStmt(N);
387 if (State->contains<InitializedVALists>(Reg) &&
388 !StatePrev->contains<InitializedVALists>(Reg))
389 Msg = "Initialized va_list";
390 else if (!State->contains<InitializedVALists>(Reg) &&
391 StatePrev->contains<InitializedVALists>(Reg))
392 Msg = "Ended va_list";
397 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
398 N->getLocationContext());
399 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
402 void ento::registerValistBase(CheckerManager &mgr) {
403 mgr.registerChecker<ValistChecker>();
406 bool ento::shouldRegisterValistBase(const LangOptions &LO) {
410 #define REGISTER_CHECKER(name) \
411 void ento::register##name##Checker(CheckerManager &mgr) { \
412 ValistChecker *checker = mgr.getChecker<ValistChecker>(); \
413 checker->ChecksEnabled[ValistChecker::CK_##name] = true; \
414 checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
417 bool ento::shouldRegister##name##Checker(const LangOptions &LO) { \
421 REGISTER_CHECKER(Uninitialized)
422 REGISTER_CHECKER(Unterminated)
423 REGISTER_CHECKER(CopyToSelf)