xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp (revision f1a0ff755a9f5ec716585dc166df9778e270c554)
1 //== ValistChecker.cpp - stdarg.h macro usage checker -----------*- C++ -*--==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This defines checkers which detect usage of uninitialized va_list values
11 // and va_start calls with no matching va_end.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
21 
22 using namespace clang;
23 using namespace ento;
24 
25 REGISTER_SET_WITH_PROGRAMSTATE(InitializedVALists, const MemRegion *)
26 
27 namespace {
28 typedef SmallVector<const MemRegion *, 2> RegionVector;
29 
30 class ValistChecker : public Checker<check::PreCall, check::PreStmt<VAArgExpr>,
31                                      check::DeadSymbols> {
32   mutable std::unique_ptr<BugType> BT_leakedvalist, BT_uninitaccess;
33 
34   struct VAListAccepter {
35     CallDescription Func;
36     int VAListPos;
37   };
38   static const SmallVector<VAListAccepter, 15> VAListAccepters;
39   static const CallDescription VaStart, VaEnd, VaCopy;
40 
41 public:
42   enum CheckKind {
43     CK_Uninitialized,
44     CK_Unterminated,
45     CK_CopyToSelf,
46     CK_NumCheckKinds
47   };
48 
49   DefaultBool ChecksEnabled[CK_NumCheckKinds];
50   CheckName CheckNames[CK_NumCheckKinds];
51 
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;
55 
56 private:
57   const MemRegion *getVAListAsRegion(SVal SV, const Expr *VAExpr,
58                                      bool &IsSymbolic, CheckerContext &C) const;
59   const ExplodedNode *getStartCallSite(const ExplodedNode *N,
60                                        const MemRegion *Reg) const;
61 
62   void reportUninitializedAccess(const MemRegion *VAList, StringRef Msg,
63                                  CheckerContext &C) const;
64   void reportLeakedVALists(const RegionVector &LeakedVALists, StringRef Msg1,
65                            StringRef Msg2, CheckerContext &C, ExplodedNode *N,
66                            bool ReportUninit = false) const;
67 
68   void checkVAListStartCall(const CallEvent &Call, CheckerContext &C,
69                             bool IsCopy) const;
70   void checkVAListEndCall(const CallEvent &Call, CheckerContext &C) const;
71 
72   class ValistBugVisitor : public BugReporterVisitorImpl<ValistBugVisitor> {
73   public:
74     ValistBugVisitor(const MemRegion *Reg, bool IsLeak = false)
75         : Reg(Reg), IsLeak(IsLeak) {}
76     void Profile(llvm::FoldingSetNodeID &ID) const override {
77       static int X = 0;
78       ID.AddPointer(&X);
79       ID.AddPointer(Reg);
80     }
81     std::unique_ptr<PathDiagnosticPiece>
82     getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
83                BugReport &BR) override {
84       if (!IsLeak)
85         return nullptr;
86 
87       PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(
88           EndPathNode, BRC.getSourceManager());
89       // Do not add the statement itself as a range in case of leak.
90       return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
91                                                          false);
92     }
93     std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
94                                                    const ExplodedNode *PrevN,
95                                                    BugReporterContext &BRC,
96                                                    BugReport &BR) override;
97 
98   private:
99     const MemRegion *Reg;
100     bool IsLeak;
101   };
102 };
103 
104 const SmallVector<ValistChecker::VAListAccepter, 15>
105     ValistChecker::VAListAccepters = {
106         {{"vfprintf", 3}, 2},
107         {{"vfscanf", 3}, 2},
108         {{"vprintf", 2}, 1},
109         {{"vscanf", 2}, 1},
110         {{"vsnprintf", 4}, 3},
111         {{"vsprintf", 3}, 2},
112         {{"vsscanf", 3}, 2},
113         {{"vfwprintf", 3}, 2},
114         {{"vfwscanf", 3}, 2},
115         {{"vwprintf", 2}, 1},
116         {{"vwscanf", 2}, 1},
117         {{"vswprintf", 4}, 3},
118         // vswprintf is the wide version of vsnprintf,
119         // vsprintf has no wide version
120         {{"vswscanf", 3}, 2}};
121 const CallDescription ValistChecker::VaStart("__builtin_va_start", 2),
122     ValistChecker::VaCopy("__builtin_va_copy", 2),
123     ValistChecker::VaEnd("__builtin_va_end", 1);
124 } // end anonymous namespace
125 
126 void ValistChecker::checkPreCall(const CallEvent &Call,
127                                  CheckerContext &C) const {
128   if (!Call.isGlobalCFunction())
129     return;
130   if (Call.isCalled(VaStart))
131     checkVAListStartCall(Call, C, false);
132   else if (Call.isCalled(VaCopy))
133     checkVAListStartCall(Call, C, true);
134   else if (Call.isCalled(VaEnd))
135     checkVAListEndCall(Call, C);
136   else {
137     for (auto FuncInfo : VAListAccepters) {
138       if (!Call.isCalled(FuncInfo.Func))
139         continue;
140       bool Symbolic;
141       const MemRegion *VAList =
142           getVAListAsRegion(Call.getArgSVal(FuncInfo.VAListPos),
143                             Call.getArgExpr(FuncInfo.VAListPos), Symbolic, C);
144       if (!VAList)
145         return;
146 
147       if (C.getState()->contains<InitializedVALists>(VAList))
148         return;
149 
150       // We did not see va_start call, but the source of the region is unknown.
151       // Be conservative and assume the best.
152       if (Symbolic)
153         return;
154 
155       SmallString<80> Errmsg("Function '");
156       Errmsg += FuncInfo.Func.getFunctionName();
157       Errmsg += "' is called with an uninitialized va_list argument";
158       reportUninitializedAccess(VAList, Errmsg.c_str(), C);
159       break;
160     }
161   }
162 }
163 
164 const MemRegion *ValistChecker::getVAListAsRegion(SVal SV, const Expr *E,
165                                                   bool &IsSymbolic,
166                                                   CheckerContext &C) const {
167   const MemRegion *Reg = SV.getAsRegion();
168   if (!Reg)
169     return nullptr;
170   // TODO: In the future this should be abstracted away by the analyzer.
171   bool VaListModelledAsArray = false;
172   if (const auto *Cast = dyn_cast<CastExpr>(E)) {
173     QualType Ty = Cast->getType();
174     VaListModelledAsArray =
175         Ty->isPointerType() && Ty->getPointeeType()->isRecordType();
176   }
177   if (const auto *DeclReg = Reg->getAs<DeclRegion>()) {
178     if (isa<ParmVarDecl>(DeclReg->getDecl()))
179       Reg = C.getState()->getSVal(SV.castAs<Loc>()).getAsRegion();
180   }
181   IsSymbolic = Reg && Reg->getAs<SymbolicRegion>();
182   // Some VarRegion based VA lists reach here as ElementRegions.
183   const auto *EReg = dyn_cast_or_null<ElementRegion>(Reg);
184   return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg;
185 }
186 
187 void ValistChecker::checkPreStmt(const VAArgExpr *VAA,
188                                  CheckerContext &C) const {
189   ProgramStateRef State = C.getState();
190   const Expr *VASubExpr = VAA->getSubExpr();
191   SVal VAListSVal = C.getSVal(VASubExpr);
192   bool Symbolic;
193   const MemRegion *VAList =
194       getVAListAsRegion(VAListSVal, VASubExpr, Symbolic, C);
195   if (!VAList)
196     return;
197   if (Symbolic)
198     return;
199   if (!State->contains<InitializedVALists>(VAList))
200     reportUninitializedAccess(
201         VAList, "va_arg() is called on an uninitialized va_list", C);
202 }
203 
204 void ValistChecker::checkDeadSymbols(SymbolReaper &SR,
205                                      CheckerContext &C) const {
206   ProgramStateRef State = C.getState();
207   InitializedVAListsTy TrackedVALists = State->get<InitializedVALists>();
208   RegionVector LeakedVALists;
209   for (auto Reg : TrackedVALists) {
210     if (SR.isLiveRegion(Reg))
211       continue;
212     LeakedVALists.push_back(Reg);
213     State = State->remove<InitializedVALists>(Reg);
214   }
215   if (ExplodedNode *N = C.addTransition(State))
216     reportLeakedVALists(LeakedVALists, "Initialized va_list", " is leaked", C,
217                         N);
218 }
219 
220 // This function traverses the exploded graph backwards and finds the node where
221 // the va_list is initialized. That node is used for uniquing the bug paths.
222 // It is not likely that there are several different va_lists that belongs to
223 // different stack frames, so that case is not yet handled.
224 const ExplodedNode *
225 ValistChecker::getStartCallSite(const ExplodedNode *N,
226                                 const MemRegion *Reg) const {
227   const LocationContext *LeakContext = N->getLocationContext();
228   const ExplodedNode *StartCallNode = N;
229 
230   bool FoundInitializedState = false;
231 
232   while (N) {
233     ProgramStateRef State = N->getState();
234     if (!State->contains<InitializedVALists>(Reg)) {
235       if (FoundInitializedState)
236         break;
237     } else {
238       FoundInitializedState = true;
239     }
240     const LocationContext *NContext = N->getLocationContext();
241     if (NContext == LeakContext || NContext->isParentOf(LeakContext))
242       StartCallNode = N;
243     N = N->pred_empty() ? nullptr : *(N->pred_begin());
244   }
245 
246   return StartCallNode;
247 }
248 
249 void ValistChecker::reportUninitializedAccess(const MemRegion *VAList,
250                                               StringRef Msg,
251                                               CheckerContext &C) const {
252   if (!ChecksEnabled[CK_Uninitialized])
253     return;
254   if (ExplodedNode *N = C.generateErrorNode()) {
255     if (!BT_uninitaccess)
256       BT_uninitaccess.reset(new BugType(CheckNames[CK_Uninitialized],
257                                         "Uninitialized va_list",
258                                         categories::MemoryError));
259     auto R = llvm::make_unique<BugReport>(*BT_uninitaccess, Msg, N);
260     R->markInteresting(VAList);
261     R->addVisitor(llvm::make_unique<ValistBugVisitor>(VAList));
262     C.emitReport(std::move(R));
263   }
264 }
265 
266 void ValistChecker::reportLeakedVALists(const RegionVector &LeakedVALists,
267                                         StringRef Msg1, StringRef Msg2,
268                                         CheckerContext &C, ExplodedNode *N,
269                                         bool ReportUninit) const {
270   if (!(ChecksEnabled[CK_Unterminated] ||
271         (ChecksEnabled[CK_Uninitialized] && ReportUninit)))
272     return;
273   for (auto Reg : LeakedVALists) {
274     if (!BT_leakedvalist) {
275       // FIXME: maybe creating a new check name for this type of bug is a better
276       // solution.
277       BT_leakedvalist.reset(
278           new BugType(CheckNames[CK_Unterminated].getName().empty()
279                           ? CheckNames[CK_Uninitialized]
280                           : CheckNames[CK_Unterminated],
281                       "Leaked va_list", categories::MemoryError));
282       BT_leakedvalist->setSuppressOnSink(true);
283     }
284 
285     const ExplodedNode *StartNode = getStartCallSite(N, Reg);
286     PathDiagnosticLocation LocUsedForUniqueing;
287 
288     if (const Stmt *StartCallStmt = PathDiagnosticLocation::getStmt(StartNode))
289       LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
290           StartCallStmt, C.getSourceManager(), StartNode->getLocationContext());
291 
292     SmallString<100> Buf;
293     llvm::raw_svector_ostream OS(Buf);
294     OS << Msg1;
295     std::string VariableName = Reg->getDescriptiveName();
296     if (!VariableName.empty())
297       OS << " " << VariableName;
298     OS << Msg2;
299 
300     auto R = llvm::make_unique<BugReport>(
301         *BT_leakedvalist, OS.str(), N, LocUsedForUniqueing,
302         StartNode->getLocationContext()->getDecl());
303     R->markInteresting(Reg);
304     R->addVisitor(llvm::make_unique<ValistBugVisitor>(Reg, true));
305     C.emitReport(std::move(R));
306   }
307 }
308 
309 void ValistChecker::checkVAListStartCall(const CallEvent &Call,
310                                          CheckerContext &C, bool IsCopy) const {
311   bool Symbolic;
312   const MemRegion *VAList =
313       getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
314   if (!VAList)
315     return;
316 
317   ProgramStateRef State = C.getState();
318 
319   if (IsCopy) {
320     const MemRegion *Arg2 =
321         getVAListAsRegion(Call.getArgSVal(1), Call.getArgExpr(1), Symbolic, C);
322     if (Arg2) {
323       if (ChecksEnabled[CK_CopyToSelf] && VAList == Arg2) {
324         RegionVector LeakedVALists{VAList};
325         if (ExplodedNode *N = C.addTransition(State))
326           reportLeakedVALists(LeakedVALists, "va_list",
327                               " is copied onto itself", C, N, true);
328         return;
329       } else if (!State->contains<InitializedVALists>(Arg2) && !Symbolic) {
330         if (State->contains<InitializedVALists>(VAList)) {
331           State = State->remove<InitializedVALists>(VAList);
332           RegionVector LeakedVALists{VAList};
333           if (ExplodedNode *N = C.addTransition(State))
334             reportLeakedVALists(LeakedVALists, "Initialized va_list",
335                                 " is overwritten by an uninitialized one", C, N,
336                                 true);
337         } else {
338           reportUninitializedAccess(Arg2, "Uninitialized va_list is copied", C);
339         }
340         return;
341       }
342     }
343   }
344   if (State->contains<InitializedVALists>(VAList)) {
345     RegionVector LeakedVALists{VAList};
346     if (ExplodedNode *N = C.addTransition(State))
347       reportLeakedVALists(LeakedVALists, "Initialized va_list",
348                           " is initialized again", C, N);
349     return;
350   }
351 
352   State = State->add<InitializedVALists>(VAList);
353   C.addTransition(State);
354 }
355 
356 void ValistChecker::checkVAListEndCall(const CallEvent &Call,
357                                        CheckerContext &C) const {
358   bool Symbolic;
359   const MemRegion *VAList =
360       getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C);
361   if (!VAList)
362     return;
363 
364   // We did not see va_start call, but the source of the region is unknown.
365   // Be conservative and assume the best.
366   if (Symbolic)
367     return;
368 
369   if (!C.getState()->contains<InitializedVALists>(VAList)) {
370     reportUninitializedAccess(
371         VAList, "va_end() is called on an uninitialized va_list", C);
372     return;
373   }
374   ProgramStateRef State = C.getState();
375   State = State->remove<InitializedVALists>(VAList);
376   C.addTransition(State);
377 }
378 
379 std::shared_ptr<PathDiagnosticPiece> ValistChecker::ValistBugVisitor::VisitNode(
380     const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
381     BugReport &) {
382   ProgramStateRef State = N->getState();
383   ProgramStateRef StatePrev = PrevN->getState();
384 
385   const Stmt *S = PathDiagnosticLocation::getStmt(N);
386   if (!S)
387     return nullptr;
388 
389   StringRef Msg;
390   if (State->contains<InitializedVALists>(Reg) &&
391       !StatePrev->contains<InitializedVALists>(Reg))
392     Msg = "Initialized va_list";
393   else if (!State->contains<InitializedVALists>(Reg) &&
394            StatePrev->contains<InitializedVALists>(Reg))
395     Msg = "Ended va_list";
396 
397   if (Msg.empty())
398     return nullptr;
399 
400   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
401                              N->getLocationContext());
402   return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
403 }
404 
405 #define REGISTER_CHECKER(name)                                                 \
406   void ento::register##name##Checker(CheckerManager &mgr) {                    \
407     ValistChecker *checker = mgr.registerChecker<ValistChecker>();             \
408     checker->ChecksEnabled[ValistChecker::CK_##name] = true;                   \
409     checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \
410   }
411 
412 REGISTER_CHECKER(Uninitialized)
413 REGISTER_CHECKER(Unterminated)
414 REGISTER_CHECKER(CopyToSelf)
415