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, CheckerContext &C) const;
58 StringRef getVariableNameFromRegion(const MemRegion *Reg) const;
59 const ExplodedNode *getStartCallSite(const ExplodedNode *N,
61 CheckerContext &C) 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 ForceReport = 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))
141 const MemRegion *VAList =
142 getVAListAsRegion(Call.getArgSVal(FuncInfo.VAListPos), C);
146 if (C.getState()->contains<InitializedVALists>(VAList))
149 SmallString<80> Errmsg("Function '");
150 Errmsg += FuncInfo.Func.getFunctionName();
151 Errmsg += "' is called with an uninitialized va_list argument";
152 reportUninitializedAccess(VAList, Errmsg.c_str(), C);
158 void ValistChecker::checkPreStmt(const VAArgExpr *VAA,
159 CheckerContext &C) const {
160 ProgramStateRef State = C.getState();
161 SVal VAListSVal = State->getSVal(VAA->getSubExpr(), C.getLocationContext());
162 const MemRegion *VAList = getVAListAsRegion(VAListSVal, C);
165 if (!State->contains<InitializedVALists>(VAList))
166 reportUninitializedAccess(
167 VAList, "va_arg() is called on an uninitialized va_list", C);
170 void ValistChecker::checkDeadSymbols(SymbolReaper &SR,
171 CheckerContext &C) const {
172 ProgramStateRef State = C.getState();
173 InitializedVAListsTy TrackedVALists = State->get<InitializedVALists>();
174 RegionVector LeakedVALists;
175 for (auto Reg : TrackedVALists) {
176 if (SR.isLiveRegion(Reg))
178 LeakedVALists.push_back(Reg);
179 State = State->remove<InitializedVALists>(Reg);
181 if (ExplodedNode *N = C.addTransition(State))
182 reportLeakedVALists(LeakedVALists, "Initialized va_list", " is leaked", C,
186 const MemRegion *ValistChecker::getVAListAsRegion(SVal SV,
187 CheckerContext &C) const {
188 const MemRegion *Reg = SV.getAsRegion();
189 const auto *TReg = dyn_cast_or_null<TypedValueRegion>(Reg);
190 // Some VarRegion based VLAs reach here as ElementRegions.
191 const auto *EReg = dyn_cast_or_null<ElementRegion>(TReg);
192 return EReg ? EReg->getSuperRegion() : TReg;
195 // This function traverses the exploded graph backwards and finds the node where
196 // the va_list is initialized. That node is used for uniquing the bug paths.
197 // It is not likely that there are several different va_lists that belongs to
198 // different stack frames, so that case is not yet handled.
199 const ExplodedNode *ValistChecker::getStartCallSite(const ExplodedNode *N,
200 const MemRegion *Reg,
201 CheckerContext &C) const {
202 const LocationContext *LeakContext = N->getLocationContext();
203 const ExplodedNode *StartCallNode = N;
205 bool FoundInitializedState = false;
208 ProgramStateRef State = N->getState();
209 if (!State->contains<InitializedVALists>(Reg)) {
210 if (FoundInitializedState)
213 FoundInitializedState = true;
215 const LocationContext *NContext = N->getLocationContext();
216 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
218 N = N->pred_empty() ? nullptr : *(N->pred_begin());
221 return StartCallNode;
224 void ValistChecker::reportUninitializedAccess(const MemRegion *VAList,
226 CheckerContext &C) const {
227 if (!ChecksEnabled[CK_Uninitialized])
229 if (ExplodedNode *N = C.generateErrorNode()) {
230 if (!BT_uninitaccess)
231 BT_uninitaccess.reset(new BugType(CheckNames[CK_Uninitialized],
232 "Uninitialized va_list",
234 auto R = llvm::make_unique<BugReport>(*BT_uninitaccess, Msg, N);
235 R->markInteresting(VAList);
236 R->addVisitor(llvm::make_unique<ValistBugVisitor>(VAList));
237 C.emitReport(std::move(R));
241 void ValistChecker::reportLeakedVALists(const RegionVector &LeakedVALists,
242 StringRef Msg1, StringRef Msg2,
243 CheckerContext &C, ExplodedNode *N,
244 bool ForceReport) const {
245 if (!(ChecksEnabled[CK_Unterminated] ||
246 (ChecksEnabled[CK_Uninitialized] && ForceReport)))
248 for (auto Reg : LeakedVALists) {
249 if (!BT_leakedvalist) {
250 BT_leakedvalist.reset(new BugType(CheckNames[CK_Unterminated],
251 "Leaked va_list", "Memory Error"));
252 BT_leakedvalist->setSuppressOnSink(true);
255 const ExplodedNode *StartNode = getStartCallSite(N, Reg, C);
256 PathDiagnosticLocation LocUsedForUniqueing;
258 if (const Stmt *StartCallStmt = PathDiagnosticLocation::getStmt(StartNode))
259 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
260 StartCallStmt, C.getSourceManager(), StartNode->getLocationContext());
262 SmallString<100> Buf;
263 llvm::raw_svector_ostream OS(Buf);
265 std::string VariableName = Reg->getDescriptiveName();
266 if (!VariableName.empty())
267 OS << " " << VariableName;
270 auto R = llvm::make_unique<BugReport>(
271 *BT_leakedvalist, OS.str(), N, LocUsedForUniqueing,
272 StartNode->getLocationContext()->getDecl());
273 R->markInteresting(Reg);
274 R->addVisitor(llvm::make_unique<ValistBugVisitor>(Reg, true));
275 C.emitReport(std::move(R));
279 void ValistChecker::checkVAListStartCall(const CallEvent &Call,
280 CheckerContext &C, bool IsCopy) const {
281 const MemRegion *VAList = getVAListAsRegion(Call.getArgSVal(0), C);
282 ProgramStateRef State = C.getState();
287 const MemRegion *Arg2 = getVAListAsRegion(Call.getArgSVal(1), C);
289 if (ChecksEnabled[CK_CopyToSelf] && VAList == Arg2) {
290 RegionVector LeakedVALists{VAList};
291 if (ExplodedNode *N = C.addTransition(State))
292 reportLeakedVALists(LeakedVALists, "va_list",
293 " is copied onto itself", C, N, true);
295 } else if (!State->contains<InitializedVALists>(Arg2)) {
296 if (State->contains<InitializedVALists>(VAList)) {
297 State = State->remove<InitializedVALists>(VAList);
298 RegionVector LeakedVALists{VAList};
299 if (ExplodedNode *N = C.addTransition(State))
300 reportLeakedVALists(LeakedVALists, "Initialized va_list",
301 " is overwritten by an uninitialized one", C, N,
304 reportUninitializedAccess(Arg2, "Uninitialized va_list is copied", C);
310 if (State->contains<InitializedVALists>(VAList)) {
311 RegionVector LeakedVALists{VAList};
312 if (ExplodedNode *N = C.addTransition(State))
313 reportLeakedVALists(LeakedVALists, "Initialized va_list",
314 " is initialized again", C, N);
318 State = State->add<InitializedVALists>(VAList);
319 C.addTransition(State);
322 void ValistChecker::checkVAListEndCall(const CallEvent &Call,
323 CheckerContext &C) const {
324 const MemRegion *VAList = getVAListAsRegion(Call.getArgSVal(0), C);
328 if (!C.getState()->contains<InitializedVALists>(VAList)) {
329 reportUninitializedAccess(
330 VAList, "va_end() is called on an uninitialized va_list", C);
333 ProgramStateRef State = C.getState();
334 State = State->remove<InitializedVALists>(VAList);
335 C.addTransition(State);
338 std::shared_ptr<PathDiagnosticPiece> ValistChecker::ValistBugVisitor::VisitNode(
339 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
341 ProgramStateRef State = N->getState();
342 ProgramStateRef StatePrev = PrevN->getState();
344 const Stmt *S = PathDiagnosticLocation::getStmt(N);
349 if (State->contains<InitializedVALists>(Reg) &&
350 !StatePrev->contains<InitializedVALists>(Reg))
351 Msg = "Initialized va_list";
352 else if (!State->contains<InitializedVALists>(Reg) &&
353 StatePrev->contains<InitializedVALists>(Reg))
354 Msg = "Ended va_list";
359 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
360 N->getLocationContext());
361 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
364 #define REGISTER_CHECKER(name) \
365 void ento::register##name##Checker(CheckerManager &mgr) { \
366 ValistChecker *checker = mgr.registerChecker<ValistChecker>(); \
367 checker->ChecksEnabled[ValistChecker::CK_##name] = true; \
368 checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
371 REGISTER_CHECKER(Uninitialized)
372 REGISTER_CHECKER(Unterminated)
373 REGISTER_CHECKER(CopyToSelf)