1 //== ValistChecker.cpp - stdarg.h macro usage checker -----------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines checkers which detect usage of uninitialized va_list values
11 // and va_start calls with no matching va_end.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 using namespace clang;
25 REGISTER_SET_WITH_PROGRAMSTATE(InitializedVALists, const MemRegion *)
28 typedef SmallVector<const MemRegion *, 2> RegionVector;
30 class ValistChecker : public Checker<check::PreCall, check::PreStmt<VAArgExpr>,
32 mutable std::unique_ptr<BugType> BT_leakedvalist, BT_uninitaccess;
34 struct VAListAccepter {
38 static const SmallVector<VAListAccepter, 15> VAListAccepters;
39 static const CallDescription VaStart, VaEnd, VaCopy;
49 DefaultBool ChecksEnabled[CK_NumCheckKinds];
50 CheckName CheckNames[CK_NumCheckKinds];
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;
57 const MemRegion *getVAListAsRegion(SVal SV, const Expr *VAExpr,
58 bool &IsSymbolic, CheckerContext &C) const;
59 StringRef getVariableNameFromRegion(const MemRegion *Reg) const;
60 const ExplodedNode *getStartCallSite(const ExplodedNode *N,
61 const MemRegion *Reg) const;
63 void reportUninitializedAccess(const MemRegion *VAList, StringRef Msg,
64 CheckerContext &C) const;
65 void reportLeakedVALists(const RegionVector &LeakedVALists, StringRef Msg1,
66 StringRef Msg2, CheckerContext &C, ExplodedNode *N,
67 bool ReportUninit = false) const;
69 void checkVAListStartCall(const CallEvent &Call, CheckerContext &C,
71 void checkVAListEndCall(const CallEvent &Call, CheckerContext &C) const;
73 class ValistBugVisitor : public BugReporterVisitorImpl<ValistBugVisitor> {
75 ValistBugVisitor(const MemRegion *Reg, bool IsLeak = false)
76 : Reg(Reg), IsLeak(IsLeak) {}
77 void Profile(llvm::FoldingSetNodeID &ID) const override {
82 std::unique_ptr<PathDiagnosticPiece>
83 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
84 BugReport &BR) override {
88 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(
89 EndPathNode, BRC.getSourceManager());
90 // Do not add the statement itself as a range in case of leak.
91 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
94 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
95 const ExplodedNode *PrevN,
96 BugReporterContext &BRC,
97 BugReport &BR) override;
100 const MemRegion *Reg;
105 const SmallVector<ValistChecker::VAListAccepter, 15>
106 ValistChecker::VAListAccepters = {
107 {{"vfprintf", 3}, 2},
111 {{"vsnprintf", 4}, 3},
112 {{"vsprintf", 3}, 2},
114 {{"vfwprintf", 3}, 2},
115 {{"vfwscanf", 3}, 2},
116 {{"vwprintf", 2}, 1},
118 {{"vswprintf", 4}, 3},
119 // vswprintf is the wide version of vsnprintf,
120 // vsprintf has no wide version
121 {{"vswscanf", 3}, 2}};
122 const CallDescription ValistChecker::VaStart("__builtin_va_start", 2),
123 ValistChecker::VaCopy("__builtin_va_copy", 2),
124 ValistChecker::VaEnd("__builtin_va_end", 1);
125 } // end anonymous namespace
127 void ValistChecker::checkPreCall(const CallEvent &Call,
128 CheckerContext &C) const {
129 if (!Call.isGlobalCFunction())
131 if (Call.isCalled(VaStart))
132 checkVAListStartCall(Call, C, false);
133 else if (Call.isCalled(VaCopy))
134 checkVAListStartCall(Call, C, true);
135 else if (Call.isCalled(VaEnd))
136 checkVAListEndCall(Call, C);
138 for (auto FuncInfo : VAListAccepters) {
139 if (!Call.isCalled(FuncInfo.Func))
142 const MemRegion *VAList =
143 getVAListAsRegion(Call.getArgSVal(FuncInfo.VAListPos),
144 Call.getArgExpr(FuncInfo.VAListPos), Symbolic, C);
148 if (C.getState()->contains<InitializedVALists>(VAList))
151 // We did not see va_start call, but the source of the region is unknown.
152 // Be conservative and assume the best.
156 SmallString<80> Errmsg("Function '");
157 Errmsg += FuncInfo.Func.getFunctionName();
158 Errmsg += "' is called with an uninitialized va_list argument";
159 reportUninitializedAccess(VAList, Errmsg.c_str(), C);
165 const MemRegion *ValistChecker::getVAListAsRegion(SVal SV, const Expr *E,
167 CheckerContext &C) const {
168 const MemRegion *Reg = SV.getAsRegion();
171 // TODO: In the future this should be abstracted away by the analyzer.
172 bool VaListModelledAsArray = false;
173 if (const auto *Cast = dyn_cast<CastExpr>(E)) {
174 QualType Ty = Cast->getType();
175 VaListModelledAsArray =
176 Ty->isPointerType() && Ty->getPointeeType()->isRecordType();
178 if (const auto *DeclReg = Reg->getAs<DeclRegion>()) {
179 if (isa<ParmVarDecl>(DeclReg->getDecl()))
180 Reg = C.getState()->getSVal(SV.castAs<Loc>()).getAsRegion();
182 IsSymbolic = Reg && Reg->getAs<SymbolicRegion>();
183 // Some VarRegion based VA lists reach here as ElementRegions.
184 const auto *EReg = dyn_cast_or_null<ElementRegion>(Reg);
185 return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg;
188 void ValistChecker::checkPreStmt(const VAArgExpr *VAA,
189 CheckerContext &C) const {
190 ProgramStateRef State = C.getState();
191 const Expr *VASubExpr = VAA->getSubExpr();
192 SVal VAListSVal = State->getSVal(VASubExpr, C.getLocationContext());
194 const MemRegion *VAList =
195 getVAListAsRegion(VAListSVal, VASubExpr, Symbolic, C);
200 if (!State->contains<InitializedVALists>(VAList))
201 reportUninitializedAccess(
202 VAList, "va_arg() is called on an uninitialized va_list", C);
205 void ValistChecker::checkDeadSymbols(SymbolReaper &SR,
206 CheckerContext &C) const {
207 ProgramStateRef State = C.getState();
208 InitializedVAListsTy TrackedVALists = State->get<InitializedVALists>();
209 RegionVector LeakedVALists;
210 for (auto Reg : TrackedVALists) {
211 if (SR.isLiveRegion(Reg))
213 LeakedVALists.push_back(Reg);
214 State = State->remove<InitializedVALists>(Reg);
216 if (ExplodedNode *N = C.addTransition(State))
217 reportLeakedVALists(LeakedVALists, "Initialized va_list", " is leaked", C,
221 // This function traverses the exploded graph backwards and finds the node where
222 // the va_list is initialized. That node is used for uniquing the bug paths.
223 // It is not likely that there are several different va_lists that belongs to
224 // different stack frames, so that case is not yet handled.
226 ValistChecker::getStartCallSite(const ExplodedNode *N,
227 const MemRegion *Reg) const {
228 const LocationContext *LeakContext = N->getLocationContext();
229 const ExplodedNode *StartCallNode = N;
231 bool FoundInitializedState = false;
234 ProgramStateRef State = N->getState();
235 if (!State->contains<InitializedVALists>(Reg)) {
236 if (FoundInitializedState)
239 FoundInitializedState = true;
241 const LocationContext *NContext = N->getLocationContext();
242 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
244 N = N->pred_empty() ? nullptr : *(N->pred_begin());
247 return StartCallNode;
250 void ValistChecker::reportUninitializedAccess(const MemRegion *VAList,
252 CheckerContext &C) const {
253 if (!ChecksEnabled[CK_Uninitialized])
255 if (ExplodedNode *N = C.generateErrorNode()) {
256 if (!BT_uninitaccess)
257 BT_uninitaccess.reset(new BugType(CheckNames[CK_Uninitialized],
258 "Uninitialized va_list",
259 categories::MemoryError));
260 auto R = llvm::make_unique<BugReport>(*BT_uninitaccess, Msg, N);
261 R->markInteresting(VAList);
262 R->addVisitor(llvm::make_unique<ValistBugVisitor>(VAList));
263 C.emitReport(std::move(R));
267 void ValistChecker::reportLeakedVALists(const RegionVector &LeakedVALists,
268 StringRef Msg1, StringRef Msg2,
269 CheckerContext &C, ExplodedNode *N,
270 bool ReportUninit) const {
271 if (!(ChecksEnabled[CK_Unterminated] ||
272 (ChecksEnabled[CK_Uninitialized] && ReportUninit)))
274 for (auto Reg : LeakedVALists) {
275 if (!BT_leakedvalist) {
276 // FIXME: maybe creating a new check name for this type of bug is a better
278 BT_leakedvalist.reset(
279 new BugType(CheckNames[CK_Unterminated].getName().empty()
280 ? CheckNames[CK_Uninitialized]
281 : CheckNames[CK_Unterminated],
282 "Leaked va_list", categories::MemoryError));
283 BT_leakedvalist->setSuppressOnSink(true);
286 const ExplodedNode *StartNode = getStartCallSite(N, Reg);
287 PathDiagnosticLocation LocUsedForUniqueing;
289 if (const Stmt *StartCallStmt = PathDiagnosticLocation::getStmt(StartNode))
290 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
291 StartCallStmt, C.getSourceManager(), StartNode->getLocationContext());
293 SmallString<100> Buf;
294 llvm::raw_svector_ostream OS(Buf);
296 std::string VariableName = Reg->getDescriptiveName();
297 if (!VariableName.empty())
298 OS << " " << VariableName;
301 auto R = llvm::make_unique<BugReport>(
302 *BT_leakedvalist, OS.str(), N, LocUsedForUniqueing,
303 StartNode->getLocationContext()->getDecl());
304 R->markInteresting(Reg);
305 R->addVisitor(llvm::make_unique<ValistBugVisitor>(Reg, true));
306 C.emitReport(std::move(R));
310 void ValistChecker::checkVAListStartCall(const CallEvent &Call,
311 CheckerContext &C, bool IsCopy) const {
313 const MemRegion *VAList =
314 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
318 ProgramStateRef State = C.getState();
321 const MemRegion *Arg2 =
322 getVAListAsRegion(Call.getArgSVal(1), Call.getArgExpr(1), Symbolic, C);
324 if (ChecksEnabled[CK_CopyToSelf] && VAList == Arg2) {
325 RegionVector LeakedVALists{VAList};
326 if (ExplodedNode *N = C.addTransition(State))
327 reportLeakedVALists(LeakedVALists, "va_list",
328 " is copied onto itself", C, N, true);
330 } else if (!State->contains<InitializedVALists>(Arg2) && !Symbolic) {
331 if (State->contains<InitializedVALists>(VAList)) {
332 State = State->remove<InitializedVALists>(VAList);
333 RegionVector LeakedVALists{VAList};
334 if (ExplodedNode *N = C.addTransition(State))
335 reportLeakedVALists(LeakedVALists, "Initialized va_list",
336 " is overwritten by an uninitialized one", C, N,
339 reportUninitializedAccess(Arg2, "Uninitialized va_list is copied", C);
345 if (State->contains<InitializedVALists>(VAList)) {
346 RegionVector LeakedVALists{VAList};
347 if (ExplodedNode *N = C.addTransition(State))
348 reportLeakedVALists(LeakedVALists, "Initialized va_list",
349 " is initialized again", C, N);
353 State = State->add<InitializedVALists>(VAList);
354 C.addTransition(State);
357 void ValistChecker::checkVAListEndCall(const CallEvent &Call,
358 CheckerContext &C) const {
360 const MemRegion *VAList =
361 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
365 // We did not see va_start call, but the source of the region is unknown.
366 // Be conservative and assume the best.
370 if (!C.getState()->contains<InitializedVALists>(VAList)) {
371 reportUninitializedAccess(
372 VAList, "va_end() is called on an uninitialized va_list", C);
375 ProgramStateRef State = C.getState();
376 State = State->remove<InitializedVALists>(VAList);
377 C.addTransition(State);
380 std::shared_ptr<PathDiagnosticPiece> ValistChecker::ValistBugVisitor::VisitNode(
381 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
383 ProgramStateRef State = N->getState();
384 ProgramStateRef StatePrev = PrevN->getState();
386 const Stmt *S = PathDiagnosticLocation::getStmt(N);
391 if (State->contains<InitializedVALists>(Reg) &&
392 !StatePrev->contains<InitializedVALists>(Reg))
393 Msg = "Initialized va_list";
394 else if (!State->contains<InitializedVALists>(Reg) &&
395 StatePrev->contains<InitializedVALists>(Reg))
396 Msg = "Ended va_list";
401 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
402 N->getLocationContext());
403 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
406 #define REGISTER_CHECKER(name) \
407 void ento::register##name##Checker(CheckerManager &mgr) { \
408 ValistChecker *checker = mgr.registerChecker<ValistChecker>(); \
409 checker->ChecksEnabled[ValistChecker::CK_##name] = true; \
410 checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
413 REGISTER_CHECKER(Uninitialized)
414 REGISTER_CHECKER(Unterminated)
415 REGISTER_CHECKER(CopyToSelf)