xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===-- StreamChecker.cpp -----------------------------------------*- C++ -*--//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file defines checkers that model and check stream handling functions.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
147330f729Sjoerg #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
157330f729Sjoerg #include "clang/StaticAnalyzer/Core/Checker.h"
167330f729Sjoerg #include "clang/StaticAnalyzer/Core/CheckerManager.h"
177330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
187330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
197330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
207330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
217330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
22*e038c9c4Sjoerg #include <functional>
237330f729Sjoerg 
247330f729Sjoerg using namespace clang;
257330f729Sjoerg using namespace ento;
26*e038c9c4Sjoerg using namespace std::placeholders;
277330f729Sjoerg 
287330f729Sjoerg namespace {
297330f729Sjoerg 
30*e038c9c4Sjoerg struct FnDescription;
317330f729Sjoerg 
32*e038c9c4Sjoerg /// State of the stream error flags.
33*e038c9c4Sjoerg /// Sometimes it is not known to the checker what error flags are set.
34*e038c9c4Sjoerg /// This is indicated by setting more than one flag to true.
35*e038c9c4Sjoerg /// This is an optimization to avoid state splits.
36*e038c9c4Sjoerg /// A stream can either be in FEOF or FERROR but not both at the same time.
37*e038c9c4Sjoerg /// Multiple flags are set to handle the corresponding states together.
38*e038c9c4Sjoerg struct StreamErrorState {
39*e038c9c4Sjoerg   /// The stream can be in state where none of the error flags set.
40*e038c9c4Sjoerg   bool NoError = true;
41*e038c9c4Sjoerg   /// The stream can be in state where the EOF indicator is set.
42*e038c9c4Sjoerg   bool FEof = false;
43*e038c9c4Sjoerg   /// The stream can be in state where the error indicator is set.
44*e038c9c4Sjoerg   bool FError = false;
457330f729Sjoerg 
isNoError__anon29813e7a0111::StreamErrorState46*e038c9c4Sjoerg   bool isNoError() const { return NoError && !FEof && !FError; }
isFEof__anon29813e7a0111::StreamErrorState47*e038c9c4Sjoerg   bool isFEof() const { return !NoError && FEof && !FError; }
isFError__anon29813e7a0111::StreamErrorState48*e038c9c4Sjoerg   bool isFError() const { return !NoError && !FEof && FError; }
497330f729Sjoerg 
operator ==__anon29813e7a0111::StreamErrorState50*e038c9c4Sjoerg   bool operator==(const StreamErrorState &ES) const {
51*e038c9c4Sjoerg     return NoError == ES.NoError && FEof == ES.FEof && FError == ES.FError;
527330f729Sjoerg   }
537330f729Sjoerg 
operator !=__anon29813e7a0111::StreamErrorState54*e038c9c4Sjoerg   bool operator!=(const StreamErrorState &ES) const { return !(*this == ES); }
55*e038c9c4Sjoerg 
operator |__anon29813e7a0111::StreamErrorState56*e038c9c4Sjoerg   StreamErrorState operator|(const StreamErrorState &E) const {
57*e038c9c4Sjoerg     return {NoError || E.NoError, FEof || E.FEof, FError || E.FError};
587330f729Sjoerg   }
59*e038c9c4Sjoerg 
operator &__anon29813e7a0111::StreamErrorState60*e038c9c4Sjoerg   StreamErrorState operator&(const StreamErrorState &E) const {
61*e038c9c4Sjoerg     return {NoError && E.NoError, FEof && E.FEof, FError && E.FError};
627330f729Sjoerg   }
637330f729Sjoerg 
operator ~__anon29813e7a0111::StreamErrorState64*e038c9c4Sjoerg   StreamErrorState operator~() const { return {!NoError, !FEof, !FError}; }
65*e038c9c4Sjoerg 
66*e038c9c4Sjoerg   /// Returns if the StreamErrorState is a valid object.
operator bool__anon29813e7a0111::StreamErrorState67*e038c9c4Sjoerg   operator bool() const { return NoError || FEof || FError; }
68*e038c9c4Sjoerg 
Profile__anon29813e7a0111::StreamErrorState697330f729Sjoerg   void Profile(llvm::FoldingSetNodeID &ID) const {
70*e038c9c4Sjoerg     ID.AddBoolean(NoError);
71*e038c9c4Sjoerg     ID.AddBoolean(FEof);
72*e038c9c4Sjoerg     ID.AddBoolean(FError);
737330f729Sjoerg   }
747330f729Sjoerg };
757330f729Sjoerg 
76*e038c9c4Sjoerg const StreamErrorState ErrorNone{true, false, false};
77*e038c9c4Sjoerg const StreamErrorState ErrorFEof{false, true, false};
78*e038c9c4Sjoerg const StreamErrorState ErrorFError{false, false, true};
79*e038c9c4Sjoerg 
80*e038c9c4Sjoerg /// Full state information about a stream pointer.
81*e038c9c4Sjoerg struct StreamState {
82*e038c9c4Sjoerg   /// The last file operation called in the stream.
83*e038c9c4Sjoerg   const FnDescription *LastOperation;
84*e038c9c4Sjoerg 
85*e038c9c4Sjoerg   /// State of a stream symbol.
86*e038c9c4Sjoerg   /// FIXME: We need maybe an "escaped" state later.
87*e038c9c4Sjoerg   enum KindTy {
88*e038c9c4Sjoerg     Opened, /// Stream is opened.
89*e038c9c4Sjoerg     Closed, /// Closed stream (an invalid stream pointer after it was closed).
90*e038c9c4Sjoerg     OpenFailed /// The last open operation has failed.
91*e038c9c4Sjoerg   } State;
92*e038c9c4Sjoerg 
93*e038c9c4Sjoerg   /// State of the error flags.
94*e038c9c4Sjoerg   /// Ignored in non-opened stream state but must be NoError.
95*e038c9c4Sjoerg   StreamErrorState const ErrorState;
96*e038c9c4Sjoerg 
97*e038c9c4Sjoerg   /// Indicate if the file has an "indeterminate file position indicator".
98*e038c9c4Sjoerg   /// This can be set at a failing read or write or seek operation.
99*e038c9c4Sjoerg   /// If it is set no more read or write is allowed.
100*e038c9c4Sjoerg   /// This value is not dependent on the stream error flags:
101*e038c9c4Sjoerg   /// The error flag may be cleared with `clearerr` but the file position
102*e038c9c4Sjoerg   /// remains still indeterminate.
103*e038c9c4Sjoerg   /// This value applies to all error states in ErrorState except FEOF.
104*e038c9c4Sjoerg   /// An EOF+indeterminate state is the same as EOF state.
105*e038c9c4Sjoerg   bool const FilePositionIndeterminate = false;
106*e038c9c4Sjoerg 
StreamState__anon29813e7a0111::StreamState107*e038c9c4Sjoerg   StreamState(const FnDescription *L, KindTy S, const StreamErrorState &ES,
108*e038c9c4Sjoerg               bool IsFilePositionIndeterminate)
109*e038c9c4Sjoerg       : LastOperation(L), State(S), ErrorState(ES),
110*e038c9c4Sjoerg         FilePositionIndeterminate(IsFilePositionIndeterminate) {
111*e038c9c4Sjoerg     assert((!ES.isFEof() || !IsFilePositionIndeterminate) &&
112*e038c9c4Sjoerg            "FilePositionIndeterminate should be false in FEof case.");
113*e038c9c4Sjoerg     assert((State == Opened || ErrorState.isNoError()) &&
114*e038c9c4Sjoerg            "ErrorState should be None in non-opened stream state.");
115*e038c9c4Sjoerg   }
116*e038c9c4Sjoerg 
isOpened__anon29813e7a0111::StreamState117*e038c9c4Sjoerg   bool isOpened() const { return State == Opened; }
isClosed__anon29813e7a0111::StreamState118*e038c9c4Sjoerg   bool isClosed() const { return State == Closed; }
isOpenFailed__anon29813e7a0111::StreamState119*e038c9c4Sjoerg   bool isOpenFailed() const { return State == OpenFailed; }
120*e038c9c4Sjoerg 
operator ==__anon29813e7a0111::StreamState121*e038c9c4Sjoerg   bool operator==(const StreamState &X) const {
122*e038c9c4Sjoerg     // In not opened state error state should always NoError, so comparison
123*e038c9c4Sjoerg     // here is no problem.
124*e038c9c4Sjoerg     return LastOperation == X.LastOperation && State == X.State &&
125*e038c9c4Sjoerg            ErrorState == X.ErrorState &&
126*e038c9c4Sjoerg            FilePositionIndeterminate == X.FilePositionIndeterminate;
127*e038c9c4Sjoerg   }
128*e038c9c4Sjoerg 
getOpened__anon29813e7a0111::StreamState129*e038c9c4Sjoerg   static StreamState getOpened(const FnDescription *L,
130*e038c9c4Sjoerg                                const StreamErrorState &ES = ErrorNone,
131*e038c9c4Sjoerg                                bool IsFilePositionIndeterminate = false) {
132*e038c9c4Sjoerg     return StreamState{L, Opened, ES, IsFilePositionIndeterminate};
133*e038c9c4Sjoerg   }
getClosed__anon29813e7a0111::StreamState134*e038c9c4Sjoerg   static StreamState getClosed(const FnDescription *L) {
135*e038c9c4Sjoerg     return StreamState{L, Closed, {}, false};
136*e038c9c4Sjoerg   }
getOpenFailed__anon29813e7a0111::StreamState137*e038c9c4Sjoerg   static StreamState getOpenFailed(const FnDescription *L) {
138*e038c9c4Sjoerg     return StreamState{L, OpenFailed, {}, false};
139*e038c9c4Sjoerg   }
140*e038c9c4Sjoerg 
Profile__anon29813e7a0111::StreamState141*e038c9c4Sjoerg   void Profile(llvm::FoldingSetNodeID &ID) const {
142*e038c9c4Sjoerg     ID.AddPointer(LastOperation);
143*e038c9c4Sjoerg     ID.AddInteger(State);
144*e038c9c4Sjoerg     ID.AddInteger(ErrorState);
145*e038c9c4Sjoerg     ID.AddBoolean(FilePositionIndeterminate);
146*e038c9c4Sjoerg   }
147*e038c9c4Sjoerg };
148*e038c9c4Sjoerg 
149*e038c9c4Sjoerg class StreamChecker;
150*e038c9c4Sjoerg using FnCheck = std::function<void(const StreamChecker *, const FnDescription *,
151*e038c9c4Sjoerg                                    const CallEvent &, CheckerContext &)>;
152*e038c9c4Sjoerg 
153*e038c9c4Sjoerg using ArgNoTy = unsigned int;
154*e038c9c4Sjoerg static const ArgNoTy ArgNone = std::numeric_limits<ArgNoTy>::max();
155*e038c9c4Sjoerg 
156*e038c9c4Sjoerg struct FnDescription {
157*e038c9c4Sjoerg   FnCheck PreFn;
158*e038c9c4Sjoerg   FnCheck EvalFn;
159*e038c9c4Sjoerg   ArgNoTy StreamArgNo;
160*e038c9c4Sjoerg };
161*e038c9c4Sjoerg 
162*e038c9c4Sjoerg /// Get the value of the stream argument out of the passed call event.
163*e038c9c4Sjoerg /// The call should contain a function that is described by Desc.
getStreamArg(const FnDescription * Desc,const CallEvent & Call)164*e038c9c4Sjoerg SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
165*e038c9c4Sjoerg   assert(Desc && Desc->StreamArgNo != ArgNone &&
166*e038c9c4Sjoerg          "Try to get a non-existing stream argument.");
167*e038c9c4Sjoerg   return Call.getArgSVal(Desc->StreamArgNo);
168*e038c9c4Sjoerg }
169*e038c9c4Sjoerg 
170*e038c9c4Sjoerg /// Create a conjured symbol return value for a call expression.
makeRetVal(CheckerContext & C,const CallExpr * CE)171*e038c9c4Sjoerg DefinedSVal makeRetVal(CheckerContext &C, const CallExpr *CE) {
172*e038c9c4Sjoerg   assert(CE && "Expecting a call expression.");
173*e038c9c4Sjoerg 
174*e038c9c4Sjoerg   const LocationContext *LCtx = C.getLocationContext();
175*e038c9c4Sjoerg   return C.getSValBuilder()
176*e038c9c4Sjoerg       .conjureSymbolVal(nullptr, CE, LCtx, C.blockCount())
177*e038c9c4Sjoerg       .castAs<DefinedSVal>();
178*e038c9c4Sjoerg }
179*e038c9c4Sjoerg 
bindAndAssumeTrue(ProgramStateRef State,CheckerContext & C,const CallExpr * CE)180*e038c9c4Sjoerg ProgramStateRef bindAndAssumeTrue(ProgramStateRef State, CheckerContext &C,
181*e038c9c4Sjoerg                                   const CallExpr *CE) {
182*e038c9c4Sjoerg   DefinedSVal RetVal = makeRetVal(C, CE);
183*e038c9c4Sjoerg   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
184*e038c9c4Sjoerg   State = State->assume(RetVal, true);
185*e038c9c4Sjoerg   assert(State && "Assumption on new value should not fail.");
186*e038c9c4Sjoerg   return State;
187*e038c9c4Sjoerg }
188*e038c9c4Sjoerg 
bindInt(uint64_t Value,ProgramStateRef State,CheckerContext & C,const CallExpr * CE)189*e038c9c4Sjoerg ProgramStateRef bindInt(uint64_t Value, ProgramStateRef State,
190*e038c9c4Sjoerg                         CheckerContext &C, const CallExpr *CE) {
191*e038c9c4Sjoerg   State = State->BindExpr(CE, C.getLocationContext(),
192*e038c9c4Sjoerg                           C.getSValBuilder().makeIntVal(Value, false));
193*e038c9c4Sjoerg   return State;
194*e038c9c4Sjoerg }
195*e038c9c4Sjoerg 
196*e038c9c4Sjoerg class StreamChecker : public Checker<check::PreCall, eval::Call,
197*e038c9c4Sjoerg                                      check::DeadSymbols, check::PointerEscape> {
198*e038c9c4Sjoerg   BugType BT_FileNull{this, "NULL stream pointer", "Stream handling error"};
199*e038c9c4Sjoerg   BugType BT_UseAfterClose{this, "Closed stream", "Stream handling error"};
200*e038c9c4Sjoerg   BugType BT_UseAfterOpenFailed{this, "Invalid stream",
201*e038c9c4Sjoerg                                 "Stream handling error"};
202*e038c9c4Sjoerg   BugType BT_IndeterminatePosition{this, "Invalid stream state",
203*e038c9c4Sjoerg                                    "Stream handling error"};
204*e038c9c4Sjoerg   BugType BT_IllegalWhence{this, "Illegal whence argument",
205*e038c9c4Sjoerg                            "Stream handling error"};
206*e038c9c4Sjoerg   BugType BT_StreamEof{this, "Stream already in EOF", "Stream handling error"};
207*e038c9c4Sjoerg   BugType BT_ResourceLeak{this, "Resource leak", "Stream handling error",
208*e038c9c4Sjoerg                           /*SuppressOnSink =*/true};
2097330f729Sjoerg 
2107330f729Sjoerg public:
211*e038c9c4Sjoerg   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
2127330f729Sjoerg   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
2137330f729Sjoerg   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
214*e038c9c4Sjoerg   ProgramStateRef checkPointerEscape(ProgramStateRef State,
215*e038c9c4Sjoerg                                      const InvalidatedSymbols &Escaped,
216*e038c9c4Sjoerg                                      const CallEvent *Call,
217*e038c9c4Sjoerg                                      PointerEscapeKind Kind) const;
218*e038c9c4Sjoerg 
219*e038c9c4Sjoerg   /// If true, evaluate special testing stream functions.
220*e038c9c4Sjoerg   bool TestMode = false;
2217330f729Sjoerg 
2227330f729Sjoerg private:
223*e038c9c4Sjoerg   CallDescriptionMap<FnDescription> FnDescriptions = {
224*e038c9c4Sjoerg       {{"fopen"}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
225*e038c9c4Sjoerg       {{"freopen", 3},
226*e038c9c4Sjoerg        {&StreamChecker::preFreopen, &StreamChecker::evalFreopen, 2}},
227*e038c9c4Sjoerg       {{"tmpfile"}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
228*e038c9c4Sjoerg       {{"fclose", 1},
229*e038c9c4Sjoerg        {&StreamChecker::preDefault, &StreamChecker::evalFclose, 0}},
230*e038c9c4Sjoerg       {{"fread", 4},
231*e038c9c4Sjoerg        {&StreamChecker::preFread,
232*e038c9c4Sjoerg         std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, true), 3}},
233*e038c9c4Sjoerg       {{"fwrite", 4},
234*e038c9c4Sjoerg        {&StreamChecker::preFwrite,
235*e038c9c4Sjoerg         std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, false), 3}},
236*e038c9c4Sjoerg       {{"fseek", 3}, {&StreamChecker::preFseek, &StreamChecker::evalFseek, 0}},
237*e038c9c4Sjoerg       {{"ftell", 1}, {&StreamChecker::preDefault, nullptr, 0}},
238*e038c9c4Sjoerg       {{"rewind", 1}, {&StreamChecker::preDefault, nullptr, 0}},
239*e038c9c4Sjoerg       {{"fgetpos", 2}, {&StreamChecker::preDefault, nullptr, 0}},
240*e038c9c4Sjoerg       {{"fsetpos", 2}, {&StreamChecker::preDefault, nullptr, 0}},
241*e038c9c4Sjoerg       {{"clearerr", 1},
242*e038c9c4Sjoerg        {&StreamChecker::preDefault, &StreamChecker::evalClearerr, 0}},
243*e038c9c4Sjoerg       {{"feof", 1},
244*e038c9c4Sjoerg        {&StreamChecker::preDefault,
245*e038c9c4Sjoerg         std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFEof),
246*e038c9c4Sjoerg         0}},
247*e038c9c4Sjoerg       {{"ferror", 1},
248*e038c9c4Sjoerg        {&StreamChecker::preDefault,
249*e038c9c4Sjoerg         std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFError),
250*e038c9c4Sjoerg         0}},
251*e038c9c4Sjoerg       {{"fileno", 1}, {&StreamChecker::preDefault, nullptr, 0}},
252*e038c9c4Sjoerg   };
2537330f729Sjoerg 
254*e038c9c4Sjoerg   CallDescriptionMap<FnDescription> FnTestDescriptions = {
255*e038c9c4Sjoerg       {{"StreamTesterChecker_make_feof_stream", 1},
256*e038c9c4Sjoerg        {nullptr,
257*e038c9c4Sjoerg         std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4, ErrorFEof),
258*e038c9c4Sjoerg         0}},
259*e038c9c4Sjoerg       {{"StreamTesterChecker_make_ferror_stream", 1},
260*e038c9c4Sjoerg        {nullptr,
261*e038c9c4Sjoerg         std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4,
262*e038c9c4Sjoerg                   ErrorFError),
263*e038c9c4Sjoerg         0}},
264*e038c9c4Sjoerg   };
2657330f729Sjoerg 
266*e038c9c4Sjoerg   void evalFopen(const FnDescription *Desc, const CallEvent &Call,
2677330f729Sjoerg                  CheckerContext &C) const;
268*e038c9c4Sjoerg 
269*e038c9c4Sjoerg   void preFreopen(const FnDescription *Desc, const CallEvent &Call,
2707330f729Sjoerg                   CheckerContext &C) const;
271*e038c9c4Sjoerg   void evalFreopen(const FnDescription *Desc, const CallEvent &Call,
272*e038c9c4Sjoerg                    CheckerContext &C) const;
273*e038c9c4Sjoerg 
274*e038c9c4Sjoerg   void evalFclose(const FnDescription *Desc, const CallEvent &Call,
275*e038c9c4Sjoerg                   CheckerContext &C) const;
276*e038c9c4Sjoerg 
277*e038c9c4Sjoerg   void preFread(const FnDescription *Desc, const CallEvent &Call,
278*e038c9c4Sjoerg                 CheckerContext &C) const;
279*e038c9c4Sjoerg 
280*e038c9c4Sjoerg   void preFwrite(const FnDescription *Desc, const CallEvent &Call,
281*e038c9c4Sjoerg                  CheckerContext &C) const;
282*e038c9c4Sjoerg 
283*e038c9c4Sjoerg   void evalFreadFwrite(const FnDescription *Desc, const CallEvent &Call,
284*e038c9c4Sjoerg                        CheckerContext &C, bool IsFread) const;
285*e038c9c4Sjoerg 
286*e038c9c4Sjoerg   void preFseek(const FnDescription *Desc, const CallEvent &Call,
287*e038c9c4Sjoerg                 CheckerContext &C) const;
288*e038c9c4Sjoerg   void evalFseek(const FnDescription *Desc, const CallEvent &Call,
289*e038c9c4Sjoerg                  CheckerContext &C) const;
290*e038c9c4Sjoerg 
291*e038c9c4Sjoerg   void preDefault(const FnDescription *Desc, const CallEvent &Call,
292*e038c9c4Sjoerg                   CheckerContext &C) const;
293*e038c9c4Sjoerg 
294*e038c9c4Sjoerg   void evalClearerr(const FnDescription *Desc, const CallEvent &Call,
295*e038c9c4Sjoerg                     CheckerContext &C) const;
296*e038c9c4Sjoerg 
297*e038c9c4Sjoerg   void evalFeofFerror(const FnDescription *Desc, const CallEvent &Call,
298*e038c9c4Sjoerg                       CheckerContext &C,
299*e038c9c4Sjoerg                       const StreamErrorState &ErrorKind) const;
300*e038c9c4Sjoerg 
301*e038c9c4Sjoerg   void evalSetFeofFerror(const FnDescription *Desc, const CallEvent &Call,
302*e038c9c4Sjoerg                          CheckerContext &C,
303*e038c9c4Sjoerg                          const StreamErrorState &ErrorKind) const;
304*e038c9c4Sjoerg 
305*e038c9c4Sjoerg   /// Check that the stream (in StreamVal) is not NULL.
306*e038c9c4Sjoerg   /// If it can only be NULL a fatal error is emitted and nullptr returned.
307*e038c9c4Sjoerg   /// Otherwise the return value is a new state where the stream is constrained
308*e038c9c4Sjoerg   /// to be non-null.
309*e038c9c4Sjoerg   ProgramStateRef ensureStreamNonNull(SVal StreamVal, CheckerContext &C,
310*e038c9c4Sjoerg                                       ProgramStateRef State) const;
311*e038c9c4Sjoerg 
312*e038c9c4Sjoerg   /// Check that the stream is the opened state.
313*e038c9c4Sjoerg   /// If the stream is known to be not opened an error is generated
314*e038c9c4Sjoerg   /// and nullptr returned, otherwise the original state is returned.
315*e038c9c4Sjoerg   ProgramStateRef ensureStreamOpened(SVal StreamVal, CheckerContext &C,
316*e038c9c4Sjoerg                                      ProgramStateRef State) const;
317*e038c9c4Sjoerg 
318*e038c9c4Sjoerg   /// Check that the stream has not an invalid ("indeterminate") file position,
319*e038c9c4Sjoerg   /// generate warning for it.
320*e038c9c4Sjoerg   /// (EOF is not an invalid position.)
321*e038c9c4Sjoerg   /// The returned state can be nullptr if a fatal error was generated.
322*e038c9c4Sjoerg   /// It can return non-null state if the stream has not an invalid position or
323*e038c9c4Sjoerg   /// there is execution path with non-invalid position.
324*e038c9c4Sjoerg   ProgramStateRef
325*e038c9c4Sjoerg   ensureNoFilePositionIndeterminate(SVal StreamVal, CheckerContext &C,
326*e038c9c4Sjoerg                                     ProgramStateRef State) const;
327*e038c9c4Sjoerg 
328*e038c9c4Sjoerg   /// Check the legality of the 'whence' argument of 'fseek'.
329*e038c9c4Sjoerg   /// Generate error and return nullptr if it is found to be illegal.
330*e038c9c4Sjoerg   /// Otherwise returns the state.
331*e038c9c4Sjoerg   /// (State is not changed here because the "whence" value is already known.)
332*e038c9c4Sjoerg   ProgramStateRef ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
333*e038c9c4Sjoerg                                            ProgramStateRef State) const;
334*e038c9c4Sjoerg 
335*e038c9c4Sjoerg   /// Generate warning about stream in EOF state.
336*e038c9c4Sjoerg   /// There will be always a state transition into the passed State,
337*e038c9c4Sjoerg   /// by the new non-fatal error node or (if failed) a normal transition,
338*e038c9c4Sjoerg   /// to ensure uniform handling.
339*e038c9c4Sjoerg   void reportFEofWarning(CheckerContext &C, ProgramStateRef State) const;
340*e038c9c4Sjoerg 
341*e038c9c4Sjoerg   /// Emit resource leak warnings for the given symbols.
342*e038c9c4Sjoerg   /// Createn a non-fatal error node for these, and returns it (if any warnings
343*e038c9c4Sjoerg   /// were generated). Return value is non-null.
344*e038c9c4Sjoerg   ExplodedNode *reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
345*e038c9c4Sjoerg                             CheckerContext &C, ExplodedNode *Pred) const;
346*e038c9c4Sjoerg 
347*e038c9c4Sjoerg   /// Find the description data of the function called by a call event.
348*e038c9c4Sjoerg   /// Returns nullptr if no function is recognized.
lookupFn(const CallEvent & Call) const349*e038c9c4Sjoerg   const FnDescription *lookupFn(const CallEvent &Call) const {
350*e038c9c4Sjoerg     // Recognize "global C functions" with only integral or pointer arguments
351*e038c9c4Sjoerg     // (and matching name) as stream functions.
352*e038c9c4Sjoerg     if (!Call.isGlobalCFunction())
353*e038c9c4Sjoerg       return nullptr;
354*e038c9c4Sjoerg     for (auto P : Call.parameters()) {
355*e038c9c4Sjoerg       QualType T = P->getType();
356*e038c9c4Sjoerg       if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
357*e038c9c4Sjoerg         return nullptr;
358*e038c9c4Sjoerg     }
359*e038c9c4Sjoerg 
360*e038c9c4Sjoerg     return FnDescriptions.lookup(Call);
361*e038c9c4Sjoerg   }
362*e038c9c4Sjoerg 
363*e038c9c4Sjoerg   /// Generate a message for BugReporterVisitor if the stored symbol is
364*e038c9c4Sjoerg   /// marked as interesting by the actual bug report.
365*e038c9c4Sjoerg   struct NoteFn {
366*e038c9c4Sjoerg     const CheckerNameRef CheckerName;
367*e038c9c4Sjoerg     SymbolRef StreamSym;
368*e038c9c4Sjoerg     std::string Message;
369*e038c9c4Sjoerg 
operator ()__anon29813e7a0111::StreamChecker::NoteFn370*e038c9c4Sjoerg     std::string operator()(PathSensitiveBugReport &BR) const {
371*e038c9c4Sjoerg       if (BR.isInteresting(StreamSym) &&
372*e038c9c4Sjoerg           CheckerName == BR.getBugType().getCheckerName())
373*e038c9c4Sjoerg         return Message;
374*e038c9c4Sjoerg 
375*e038c9c4Sjoerg       return "";
376*e038c9c4Sjoerg     }
377*e038c9c4Sjoerg   };
378*e038c9c4Sjoerg 
constructNoteTag(CheckerContext & C,SymbolRef StreamSym,const std::string & Message) const379*e038c9c4Sjoerg   const NoteTag *constructNoteTag(CheckerContext &C, SymbolRef StreamSym,
380*e038c9c4Sjoerg                                   const std::string &Message) const {
381*e038c9c4Sjoerg     return C.getNoteTag(NoteFn{getCheckerName(), StreamSym, Message});
382*e038c9c4Sjoerg   }
383*e038c9c4Sjoerg 
384*e038c9c4Sjoerg   /// Searches for the ExplodedNode where the file descriptor was acquired for
385*e038c9c4Sjoerg   /// StreamSym.
386*e038c9c4Sjoerg   static const ExplodedNode *getAcquisitionSite(const ExplodedNode *N,
387*e038c9c4Sjoerg                                                 SymbolRef StreamSym,
388*e038c9c4Sjoerg                                                 CheckerContext &C);
3897330f729Sjoerg };
3907330f729Sjoerg 
3917330f729Sjoerg } // end anonymous namespace
3927330f729Sjoerg 
REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap,SymbolRef,StreamState)3937330f729Sjoerg REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
3947330f729Sjoerg 
395*e038c9c4Sjoerg inline void assertStreamStateOpened(const StreamState *SS) {
396*e038c9c4Sjoerg   assert(SS->isOpened() &&
397*e038c9c4Sjoerg          "Previous create of error node for non-opened stream failed?");
398*e038c9c4Sjoerg }
399*e038c9c4Sjoerg 
getAcquisitionSite(const ExplodedNode * N,SymbolRef StreamSym,CheckerContext & C)400*e038c9c4Sjoerg const ExplodedNode *StreamChecker::getAcquisitionSite(const ExplodedNode *N,
401*e038c9c4Sjoerg                                                       SymbolRef StreamSym,
402*e038c9c4Sjoerg                                                       CheckerContext &C) {
403*e038c9c4Sjoerg   ProgramStateRef State = N->getState();
404*e038c9c4Sjoerg   // When bug type is resource leak, exploded node N may not have state info
405*e038c9c4Sjoerg   // for leaked file descriptor, but predecessor should have it.
406*e038c9c4Sjoerg   if (!State->get<StreamMap>(StreamSym))
407*e038c9c4Sjoerg     N = N->getFirstPred();
408*e038c9c4Sjoerg 
409*e038c9c4Sjoerg   const ExplodedNode *Pred = N;
410*e038c9c4Sjoerg   while (N) {
411*e038c9c4Sjoerg     State = N->getState();
412*e038c9c4Sjoerg     if (!State->get<StreamMap>(StreamSym))
413*e038c9c4Sjoerg       return Pred;
414*e038c9c4Sjoerg     Pred = N;
415*e038c9c4Sjoerg     N = N->getFirstPred();
416*e038c9c4Sjoerg   }
417*e038c9c4Sjoerg 
418*e038c9c4Sjoerg   return nullptr;
419*e038c9c4Sjoerg }
420*e038c9c4Sjoerg 
checkPreCall(const CallEvent & Call,CheckerContext & C) const421*e038c9c4Sjoerg void StreamChecker::checkPreCall(const CallEvent &Call,
422*e038c9c4Sjoerg                                  CheckerContext &C) const {
423*e038c9c4Sjoerg   const FnDescription *Desc = lookupFn(Call);
424*e038c9c4Sjoerg   if (!Desc || !Desc->PreFn)
425*e038c9c4Sjoerg     return;
426*e038c9c4Sjoerg 
427*e038c9c4Sjoerg   Desc->PreFn(this, Desc, Call, C);
428*e038c9c4Sjoerg }
4297330f729Sjoerg 
evalCall(const CallEvent & Call,CheckerContext & C) const4307330f729Sjoerg bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
431*e038c9c4Sjoerg   const FnDescription *Desc = lookupFn(Call);
432*e038c9c4Sjoerg   if (!Desc && TestMode)
433*e038c9c4Sjoerg     Desc = FnTestDescriptions.lookup(Call);
434*e038c9c4Sjoerg   if (!Desc || !Desc->EvalFn)
4357330f729Sjoerg     return false;
4367330f729Sjoerg 
437*e038c9c4Sjoerg   Desc->EvalFn(this, Desc, Call, C);
438*e038c9c4Sjoerg 
439*e038c9c4Sjoerg   return C.isDifferent();
440*e038c9c4Sjoerg }
441*e038c9c4Sjoerg 
evalFopen(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const442*e038c9c4Sjoerg void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call,
443*e038c9c4Sjoerg                               CheckerContext &C) const {
444*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
445*e038c9c4Sjoerg   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
4467330f729Sjoerg   if (!CE)
447*e038c9c4Sjoerg     return;
4487330f729Sjoerg 
449*e038c9c4Sjoerg   DefinedSVal RetVal = makeRetVal(C, CE);
450*e038c9c4Sjoerg   SymbolRef RetSym = RetVal.getAsSymbol();
451*e038c9c4Sjoerg   assert(RetSym && "RetVal must be a symbol here.");
4527330f729Sjoerg 
453*e038c9c4Sjoerg   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
4547330f729Sjoerg 
4557330f729Sjoerg   // Bifurcate the state into two: one with a valid FILE* pointer, the other
4567330f729Sjoerg   // with a NULL.
457*e038c9c4Sjoerg   ProgramStateRef StateNotNull, StateNull;
458*e038c9c4Sjoerg   std::tie(StateNotNull, StateNull) =
459*e038c9c4Sjoerg       C.getConstraintManager().assumeDual(State, RetVal);
4607330f729Sjoerg 
461*e038c9c4Sjoerg   StateNotNull =
462*e038c9c4Sjoerg       StateNotNull->set<StreamMap>(RetSym, StreamState::getOpened(Desc));
463*e038c9c4Sjoerg   StateNull =
464*e038c9c4Sjoerg       StateNull->set<StreamMap>(RetSym, StreamState::getOpenFailed(Desc));
4657330f729Sjoerg 
466*e038c9c4Sjoerg   C.addTransition(StateNotNull,
467*e038c9c4Sjoerg                   constructNoteTag(C, RetSym, "Stream opened here"));
468*e038c9c4Sjoerg   C.addTransition(StateNull);
4697330f729Sjoerg }
4707330f729Sjoerg 
preFreopen(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const471*e038c9c4Sjoerg void StreamChecker::preFreopen(const FnDescription *Desc, const CallEvent &Call,
4727330f729Sjoerg                                CheckerContext &C) const {
473*e038c9c4Sjoerg   // Do not allow NULL as passed stream pointer but allow a closed stream.
474*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
475*e038c9c4Sjoerg   State = ensureStreamNonNull(getStreamArg(Desc, Call), C, State);
476*e038c9c4Sjoerg   if (!State)
477*e038c9c4Sjoerg     return;
4787330f729Sjoerg 
479*e038c9c4Sjoerg   C.addTransition(State);
4807330f729Sjoerg }
4817330f729Sjoerg 
evalFreopen(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const482*e038c9c4Sjoerg void StreamChecker::evalFreopen(const FnDescription *Desc,
483*e038c9c4Sjoerg                                 const CallEvent &Call,
4847330f729Sjoerg                                 CheckerContext &C) const {
485*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
486*e038c9c4Sjoerg 
487*e038c9c4Sjoerg   auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
488*e038c9c4Sjoerg   if (!CE)
489*e038c9c4Sjoerg     return;
490*e038c9c4Sjoerg 
491*e038c9c4Sjoerg   Optional<DefinedSVal> StreamVal =
492*e038c9c4Sjoerg       getStreamArg(Desc, Call).getAs<DefinedSVal>();
493*e038c9c4Sjoerg   if (!StreamVal)
494*e038c9c4Sjoerg     return;
495*e038c9c4Sjoerg 
496*e038c9c4Sjoerg   SymbolRef StreamSym = StreamVal->getAsSymbol();
497*e038c9c4Sjoerg   // Do not care about concrete values for stream ("(FILE *)0x12345"?).
498*e038c9c4Sjoerg   // FIXME: Can be stdin, stdout, stderr such values?
499*e038c9c4Sjoerg   if (!StreamSym)
500*e038c9c4Sjoerg     return;
501*e038c9c4Sjoerg 
502*e038c9c4Sjoerg   // Do not handle untracked stream. It is probably escaped.
503*e038c9c4Sjoerg   if (!State->get<StreamMap>(StreamSym))
504*e038c9c4Sjoerg     return;
505*e038c9c4Sjoerg 
506*e038c9c4Sjoerg   // Generate state for non-failed case.
507*e038c9c4Sjoerg   // Return value is the passed stream pointer.
508*e038c9c4Sjoerg   // According to the documentations, the stream is closed first
509*e038c9c4Sjoerg   // but any close error is ignored. The state changes to (or remains) opened.
510*e038c9c4Sjoerg   ProgramStateRef StateRetNotNull =
511*e038c9c4Sjoerg       State->BindExpr(CE, C.getLocationContext(), *StreamVal);
512*e038c9c4Sjoerg   // Generate state for NULL return value.
513*e038c9c4Sjoerg   // Stream switches to OpenFailed state.
514*e038c9c4Sjoerg   ProgramStateRef StateRetNull = State->BindExpr(CE, C.getLocationContext(),
515*e038c9c4Sjoerg                                                  C.getSValBuilder().makeNull());
516*e038c9c4Sjoerg 
517*e038c9c4Sjoerg   StateRetNotNull =
518*e038c9c4Sjoerg       StateRetNotNull->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
519*e038c9c4Sjoerg   StateRetNull =
520*e038c9c4Sjoerg       StateRetNull->set<StreamMap>(StreamSym, StreamState::getOpenFailed(Desc));
521*e038c9c4Sjoerg 
522*e038c9c4Sjoerg   C.addTransition(StateRetNotNull,
523*e038c9c4Sjoerg                   constructNoteTag(C, StreamSym, "Stream reopened here"));
524*e038c9c4Sjoerg   C.addTransition(StateRetNull);
525*e038c9c4Sjoerg }
526*e038c9c4Sjoerg 
evalFclose(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const527*e038c9c4Sjoerg void StreamChecker::evalFclose(const FnDescription *Desc, const CallEvent &Call,
528*e038c9c4Sjoerg                                CheckerContext &C) const {
529*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
530*e038c9c4Sjoerg   SymbolRef Sym = getStreamArg(Desc, Call).getAsSymbol();
5317330f729Sjoerg   if (!Sym)
532*e038c9c4Sjoerg     return;
5337330f729Sjoerg 
534*e038c9c4Sjoerg   const StreamState *SS = State->get<StreamMap>(Sym);
5357330f729Sjoerg   if (!SS)
536*e038c9c4Sjoerg     return;
5377330f729Sjoerg 
538*e038c9c4Sjoerg   assertStreamStateOpened(SS);
5397330f729Sjoerg 
5407330f729Sjoerg   // Close the File Descriptor.
541*e038c9c4Sjoerg   // Regardless if the close fails or not, stream becomes "closed"
542*e038c9c4Sjoerg   // and can not be used any more.
543*e038c9c4Sjoerg   State = State->set<StreamMap>(Sym, StreamState::getClosed(Desc));
544*e038c9c4Sjoerg 
545*e038c9c4Sjoerg   C.addTransition(State);
546*e038c9c4Sjoerg }
547*e038c9c4Sjoerg 
preFread(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const548*e038c9c4Sjoerg void StreamChecker::preFread(const FnDescription *Desc, const CallEvent &Call,
549*e038c9c4Sjoerg                              CheckerContext &C) const {
550*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
551*e038c9c4Sjoerg   SVal StreamVal = getStreamArg(Desc, Call);
552*e038c9c4Sjoerg   State = ensureStreamNonNull(StreamVal, C, State);
553*e038c9c4Sjoerg   if (!State)
554*e038c9c4Sjoerg     return;
555*e038c9c4Sjoerg   State = ensureStreamOpened(StreamVal, C, State);
556*e038c9c4Sjoerg   if (!State)
557*e038c9c4Sjoerg     return;
558*e038c9c4Sjoerg   State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
559*e038c9c4Sjoerg   if (!State)
560*e038c9c4Sjoerg     return;
561*e038c9c4Sjoerg 
562*e038c9c4Sjoerg   SymbolRef Sym = StreamVal.getAsSymbol();
563*e038c9c4Sjoerg   if (Sym && State->get<StreamMap>(Sym)) {
564*e038c9c4Sjoerg     const StreamState *SS = State->get<StreamMap>(Sym);
565*e038c9c4Sjoerg     if (SS->ErrorState & ErrorFEof)
566*e038c9c4Sjoerg       reportFEofWarning(C, State);
567*e038c9c4Sjoerg   } else {
568*e038c9c4Sjoerg     C.addTransition(State);
569*e038c9c4Sjoerg   }
570*e038c9c4Sjoerg }
571*e038c9c4Sjoerg 
preFwrite(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const572*e038c9c4Sjoerg void StreamChecker::preFwrite(const FnDescription *Desc, const CallEvent &Call,
573*e038c9c4Sjoerg                               CheckerContext &C) const {
574*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
575*e038c9c4Sjoerg   SVal StreamVal = getStreamArg(Desc, Call);
576*e038c9c4Sjoerg   State = ensureStreamNonNull(StreamVal, C, State);
577*e038c9c4Sjoerg   if (!State)
578*e038c9c4Sjoerg     return;
579*e038c9c4Sjoerg   State = ensureStreamOpened(StreamVal, C, State);
580*e038c9c4Sjoerg   if (!State)
581*e038c9c4Sjoerg     return;
582*e038c9c4Sjoerg   State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
583*e038c9c4Sjoerg   if (!State)
584*e038c9c4Sjoerg     return;
585*e038c9c4Sjoerg 
586*e038c9c4Sjoerg   C.addTransition(State);
587*e038c9c4Sjoerg }
588*e038c9c4Sjoerg 
evalFreadFwrite(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C,bool IsFread) const589*e038c9c4Sjoerg void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
590*e038c9c4Sjoerg                                     const CallEvent &Call, CheckerContext &C,
591*e038c9c4Sjoerg                                     bool IsFread) const {
592*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
593*e038c9c4Sjoerg   SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
594*e038c9c4Sjoerg   if (!StreamSym)
595*e038c9c4Sjoerg     return;
596*e038c9c4Sjoerg 
597*e038c9c4Sjoerg   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
598*e038c9c4Sjoerg   if (!CE)
599*e038c9c4Sjoerg     return;
600*e038c9c4Sjoerg 
601*e038c9c4Sjoerg   Optional<NonLoc> SizeVal = Call.getArgSVal(1).getAs<NonLoc>();
602*e038c9c4Sjoerg   if (!SizeVal)
603*e038c9c4Sjoerg     return;
604*e038c9c4Sjoerg   Optional<NonLoc> NMembVal = Call.getArgSVal(2).getAs<NonLoc>();
605*e038c9c4Sjoerg   if (!NMembVal)
606*e038c9c4Sjoerg     return;
607*e038c9c4Sjoerg 
608*e038c9c4Sjoerg   const StreamState *SS = State->get<StreamMap>(StreamSym);
609*e038c9c4Sjoerg   if (!SS)
610*e038c9c4Sjoerg     return;
611*e038c9c4Sjoerg 
612*e038c9c4Sjoerg   assertStreamStateOpened(SS);
613*e038c9c4Sjoerg 
614*e038c9c4Sjoerg   // C'99 standard, §7.19.8.1.3, the return value of fread:
615*e038c9c4Sjoerg   // The fread function returns the number of elements successfully read, which
616*e038c9c4Sjoerg   // may be less than nmemb if a read error or end-of-file is encountered. If
617*e038c9c4Sjoerg   // size or nmemb is zero, fread returns zero and the contents of the array and
618*e038c9c4Sjoerg   // the state of the stream remain unchanged.
619*e038c9c4Sjoerg 
620*e038c9c4Sjoerg   if (State->isNull(*SizeVal).isConstrainedTrue() ||
621*e038c9c4Sjoerg       State->isNull(*NMembVal).isConstrainedTrue()) {
622*e038c9c4Sjoerg     // This is the "size or nmemb is zero" case.
623*e038c9c4Sjoerg     // Just return 0, do nothing more (not clear the error flags).
624*e038c9c4Sjoerg     State = bindInt(0, State, C, CE);
625*e038c9c4Sjoerg     C.addTransition(State);
626*e038c9c4Sjoerg     return;
627*e038c9c4Sjoerg   }
628*e038c9c4Sjoerg 
629*e038c9c4Sjoerg   // Generate a transition for the success state.
630*e038c9c4Sjoerg   // If we know the state to be FEOF at fread, do not add a success state.
631*e038c9c4Sjoerg   if (!IsFread || (SS->ErrorState != ErrorFEof)) {
632*e038c9c4Sjoerg     ProgramStateRef StateNotFailed =
633*e038c9c4Sjoerg         State->BindExpr(CE, C.getLocationContext(), *NMembVal);
634*e038c9c4Sjoerg     if (StateNotFailed) {
635*e038c9c4Sjoerg       StateNotFailed = StateNotFailed->set<StreamMap>(
636*e038c9c4Sjoerg           StreamSym, StreamState::getOpened(Desc));
637*e038c9c4Sjoerg       C.addTransition(StateNotFailed);
638*e038c9c4Sjoerg     }
639*e038c9c4Sjoerg   }
640*e038c9c4Sjoerg 
641*e038c9c4Sjoerg   // Add transition for the failed state.
642*e038c9c4Sjoerg   Optional<NonLoc> RetVal = makeRetVal(C, CE).castAs<NonLoc>();
643*e038c9c4Sjoerg   assert(RetVal && "Value should be NonLoc.");
644*e038c9c4Sjoerg   ProgramStateRef StateFailed =
645*e038c9c4Sjoerg       State->BindExpr(CE, C.getLocationContext(), *RetVal);
646*e038c9c4Sjoerg   if (!StateFailed)
647*e038c9c4Sjoerg     return;
648*e038c9c4Sjoerg   auto Cond = C.getSValBuilder()
649*e038c9c4Sjoerg                   .evalBinOpNN(State, BO_LT, *RetVal, *NMembVal,
650*e038c9c4Sjoerg                                C.getASTContext().IntTy)
651*e038c9c4Sjoerg                   .getAs<DefinedOrUnknownSVal>();
652*e038c9c4Sjoerg   if (!Cond)
653*e038c9c4Sjoerg     return;
654*e038c9c4Sjoerg   StateFailed = StateFailed->assume(*Cond, true);
655*e038c9c4Sjoerg   if (!StateFailed)
656*e038c9c4Sjoerg     return;
657*e038c9c4Sjoerg 
658*e038c9c4Sjoerg   StreamErrorState NewES;
659*e038c9c4Sjoerg   if (IsFread)
660*e038c9c4Sjoerg     NewES = (SS->ErrorState == ErrorFEof) ? ErrorFEof : ErrorFEof | ErrorFError;
661*e038c9c4Sjoerg   else
662*e038c9c4Sjoerg     NewES = ErrorFError;
663*e038c9c4Sjoerg   // If a (non-EOF) error occurs, the resulting value of the file position
664*e038c9c4Sjoerg   // indicator for the stream is indeterminate.
665*e038c9c4Sjoerg   StreamState NewState = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
666*e038c9c4Sjoerg   StateFailed = StateFailed->set<StreamMap>(StreamSym, NewState);
667*e038c9c4Sjoerg   C.addTransition(StateFailed);
668*e038c9c4Sjoerg }
669*e038c9c4Sjoerg 
preFseek(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const670*e038c9c4Sjoerg void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
671*e038c9c4Sjoerg                              CheckerContext &C) const {
672*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
673*e038c9c4Sjoerg   SVal StreamVal = getStreamArg(Desc, Call);
674*e038c9c4Sjoerg   State = ensureStreamNonNull(StreamVal, C, State);
675*e038c9c4Sjoerg   if (!State)
676*e038c9c4Sjoerg     return;
677*e038c9c4Sjoerg   State = ensureStreamOpened(StreamVal, C, State);
678*e038c9c4Sjoerg   if (!State)
679*e038c9c4Sjoerg     return;
680*e038c9c4Sjoerg   State = ensureFseekWhenceCorrect(Call.getArgSVal(2), C, State);
681*e038c9c4Sjoerg   if (!State)
682*e038c9c4Sjoerg     return;
683*e038c9c4Sjoerg 
684*e038c9c4Sjoerg   C.addTransition(State);
685*e038c9c4Sjoerg }
686*e038c9c4Sjoerg 
evalFseek(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const687*e038c9c4Sjoerg void StreamChecker::evalFseek(const FnDescription *Desc, const CallEvent &Call,
688*e038c9c4Sjoerg                               CheckerContext &C) const {
689*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
690*e038c9c4Sjoerg   SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
691*e038c9c4Sjoerg   if (!StreamSym)
692*e038c9c4Sjoerg     return;
693*e038c9c4Sjoerg 
694*e038c9c4Sjoerg   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
695*e038c9c4Sjoerg   if (!CE)
696*e038c9c4Sjoerg     return;
697*e038c9c4Sjoerg 
698*e038c9c4Sjoerg   // Ignore the call if the stream is not tracked.
699*e038c9c4Sjoerg   if (!State->get<StreamMap>(StreamSym))
700*e038c9c4Sjoerg     return;
701*e038c9c4Sjoerg 
702*e038c9c4Sjoerg   DefinedSVal RetVal = makeRetVal(C, CE);
703*e038c9c4Sjoerg 
704*e038c9c4Sjoerg   // Make expression result.
705*e038c9c4Sjoerg   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
706*e038c9c4Sjoerg 
707*e038c9c4Sjoerg   // Bifurcate the state into failed and non-failed.
708*e038c9c4Sjoerg   // Return zero on success, nonzero on error.
709*e038c9c4Sjoerg   ProgramStateRef StateNotFailed, StateFailed;
710*e038c9c4Sjoerg   std::tie(StateFailed, StateNotFailed) =
711*e038c9c4Sjoerg       C.getConstraintManager().assumeDual(State, RetVal);
712*e038c9c4Sjoerg 
713*e038c9c4Sjoerg   // Reset the state to opened with no error.
714*e038c9c4Sjoerg   StateNotFailed =
715*e038c9c4Sjoerg       StateNotFailed->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
716*e038c9c4Sjoerg   // We get error.
717*e038c9c4Sjoerg   // It is possible that fseek fails but sets none of the error flags.
718*e038c9c4Sjoerg   // If fseek failed, assume that the file position becomes indeterminate in any
719*e038c9c4Sjoerg   // case.
720*e038c9c4Sjoerg   StateFailed = StateFailed->set<StreamMap>(
721*e038c9c4Sjoerg       StreamSym,
722*e038c9c4Sjoerg       StreamState::getOpened(Desc, ErrorNone | ErrorFEof | ErrorFError, true));
723*e038c9c4Sjoerg 
724*e038c9c4Sjoerg   C.addTransition(StateNotFailed);
725*e038c9c4Sjoerg   C.addTransition(StateFailed);
726*e038c9c4Sjoerg }
727*e038c9c4Sjoerg 
evalClearerr(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const728*e038c9c4Sjoerg void StreamChecker::evalClearerr(const FnDescription *Desc,
729*e038c9c4Sjoerg                                  const CallEvent &Call,
730*e038c9c4Sjoerg                                  CheckerContext &C) const {
731*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
732*e038c9c4Sjoerg   SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
733*e038c9c4Sjoerg   if (!StreamSym)
734*e038c9c4Sjoerg     return;
735*e038c9c4Sjoerg 
736*e038c9c4Sjoerg   const StreamState *SS = State->get<StreamMap>(StreamSym);
737*e038c9c4Sjoerg   if (!SS)
738*e038c9c4Sjoerg     return;
739*e038c9c4Sjoerg 
740*e038c9c4Sjoerg   assertStreamStateOpened(SS);
741*e038c9c4Sjoerg 
742*e038c9c4Sjoerg   // FilePositionIndeterminate is not cleared.
743*e038c9c4Sjoerg   State = State->set<StreamMap>(
744*e038c9c4Sjoerg       StreamSym,
745*e038c9c4Sjoerg       StreamState::getOpened(Desc, ErrorNone, SS->FilePositionIndeterminate));
746*e038c9c4Sjoerg   C.addTransition(State);
747*e038c9c4Sjoerg }
748*e038c9c4Sjoerg 
evalFeofFerror(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C,const StreamErrorState & ErrorKind) const749*e038c9c4Sjoerg void StreamChecker::evalFeofFerror(const FnDescription *Desc,
750*e038c9c4Sjoerg                                    const CallEvent &Call, CheckerContext &C,
751*e038c9c4Sjoerg                                    const StreamErrorState &ErrorKind) const {
752*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
753*e038c9c4Sjoerg   SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
754*e038c9c4Sjoerg   if (!StreamSym)
755*e038c9c4Sjoerg     return;
756*e038c9c4Sjoerg 
757*e038c9c4Sjoerg   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
758*e038c9c4Sjoerg   if (!CE)
759*e038c9c4Sjoerg     return;
760*e038c9c4Sjoerg 
761*e038c9c4Sjoerg   const StreamState *SS = State->get<StreamMap>(StreamSym);
762*e038c9c4Sjoerg   if (!SS)
763*e038c9c4Sjoerg     return;
764*e038c9c4Sjoerg 
765*e038c9c4Sjoerg   assertStreamStateOpened(SS);
766*e038c9c4Sjoerg 
767*e038c9c4Sjoerg   if (SS->ErrorState & ErrorKind) {
768*e038c9c4Sjoerg     // Execution path with error of ErrorKind.
769*e038c9c4Sjoerg     // Function returns true.
770*e038c9c4Sjoerg     // From now on it is the only one error state.
771*e038c9c4Sjoerg     ProgramStateRef TrueState = bindAndAssumeTrue(State, C, CE);
772*e038c9c4Sjoerg     C.addTransition(TrueState->set<StreamMap>(
773*e038c9c4Sjoerg         StreamSym, StreamState::getOpened(Desc, ErrorKind,
774*e038c9c4Sjoerg                                           SS->FilePositionIndeterminate &&
775*e038c9c4Sjoerg                                               !ErrorKind.isFEof())));
776*e038c9c4Sjoerg   }
777*e038c9c4Sjoerg   if (StreamErrorState NewES = SS->ErrorState & (~ErrorKind)) {
778*e038c9c4Sjoerg     // Execution path(s) with ErrorKind not set.
779*e038c9c4Sjoerg     // Function returns false.
780*e038c9c4Sjoerg     // New error state is everything before minus ErrorKind.
781*e038c9c4Sjoerg     ProgramStateRef FalseState = bindInt(0, State, C, CE);
782*e038c9c4Sjoerg     C.addTransition(FalseState->set<StreamMap>(
783*e038c9c4Sjoerg         StreamSym,
784*e038c9c4Sjoerg         StreamState::getOpened(
785*e038c9c4Sjoerg             Desc, NewES, SS->FilePositionIndeterminate && !NewES.isFEof())));
786*e038c9c4Sjoerg   }
787*e038c9c4Sjoerg }
788*e038c9c4Sjoerg 
preDefault(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C) const789*e038c9c4Sjoerg void StreamChecker::preDefault(const FnDescription *Desc, const CallEvent &Call,
790*e038c9c4Sjoerg                                CheckerContext &C) const {
791*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
792*e038c9c4Sjoerg   SVal StreamVal = getStreamArg(Desc, Call);
793*e038c9c4Sjoerg   State = ensureStreamNonNull(StreamVal, C, State);
794*e038c9c4Sjoerg   if (!State)
795*e038c9c4Sjoerg     return;
796*e038c9c4Sjoerg   State = ensureStreamOpened(StreamVal, C, State);
797*e038c9c4Sjoerg   if (!State)
798*e038c9c4Sjoerg     return;
799*e038c9c4Sjoerg 
800*e038c9c4Sjoerg   C.addTransition(State);
801*e038c9c4Sjoerg }
802*e038c9c4Sjoerg 
evalSetFeofFerror(const FnDescription * Desc,const CallEvent & Call,CheckerContext & C,const StreamErrorState & ErrorKind) const803*e038c9c4Sjoerg void StreamChecker::evalSetFeofFerror(const FnDescription *Desc,
804*e038c9c4Sjoerg                                       const CallEvent &Call, CheckerContext &C,
805*e038c9c4Sjoerg                                       const StreamErrorState &ErrorKind) const {
806*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
807*e038c9c4Sjoerg   SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
808*e038c9c4Sjoerg   assert(StreamSym && "Operation not permitted on non-symbolic stream value.");
809*e038c9c4Sjoerg   const StreamState *SS = State->get<StreamMap>(StreamSym);
810*e038c9c4Sjoerg   assert(SS && "Stream should be tracked by the checker.");
811*e038c9c4Sjoerg   State = State->set<StreamMap>(
812*e038c9c4Sjoerg       StreamSym, StreamState::getOpened(SS->LastOperation, ErrorKind));
813*e038c9c4Sjoerg   C.addTransition(State);
814*e038c9c4Sjoerg }
815*e038c9c4Sjoerg 
816*e038c9c4Sjoerg ProgramStateRef
ensureStreamNonNull(SVal StreamVal,CheckerContext & C,ProgramStateRef State) const817*e038c9c4Sjoerg StreamChecker::ensureStreamNonNull(SVal StreamVal, CheckerContext &C,
818*e038c9c4Sjoerg                                    ProgramStateRef State) const {
819*e038c9c4Sjoerg   auto Stream = StreamVal.getAs<DefinedSVal>();
820*e038c9c4Sjoerg   if (!Stream)
821*e038c9c4Sjoerg     return State;
822*e038c9c4Sjoerg 
823*e038c9c4Sjoerg   ConstraintManager &CM = C.getConstraintManager();
824*e038c9c4Sjoerg 
825*e038c9c4Sjoerg   ProgramStateRef StateNotNull, StateNull;
826*e038c9c4Sjoerg   std::tie(StateNotNull, StateNull) = CM.assumeDual(C.getState(), *Stream);
827*e038c9c4Sjoerg 
828*e038c9c4Sjoerg   if (!StateNotNull && StateNull) {
829*e038c9c4Sjoerg     if (ExplodedNode *N = C.generateErrorNode(StateNull)) {
830*e038c9c4Sjoerg       C.emitReport(std::make_unique<PathSensitiveBugReport>(
831*e038c9c4Sjoerg           BT_FileNull, "Stream pointer might be NULL.", N));
832*e038c9c4Sjoerg     }
833*e038c9c4Sjoerg     return nullptr;
834*e038c9c4Sjoerg   }
835*e038c9c4Sjoerg 
836*e038c9c4Sjoerg   return StateNotNull;
837*e038c9c4Sjoerg }
838*e038c9c4Sjoerg 
ensureStreamOpened(SVal StreamVal,CheckerContext & C,ProgramStateRef State) const839*e038c9c4Sjoerg ProgramStateRef StreamChecker::ensureStreamOpened(SVal StreamVal,
840*e038c9c4Sjoerg                                                   CheckerContext &C,
841*e038c9c4Sjoerg                                                   ProgramStateRef State) const {
842*e038c9c4Sjoerg   SymbolRef Sym = StreamVal.getAsSymbol();
843*e038c9c4Sjoerg   if (!Sym)
844*e038c9c4Sjoerg     return State;
845*e038c9c4Sjoerg 
846*e038c9c4Sjoerg   const StreamState *SS = State->get<StreamMap>(Sym);
847*e038c9c4Sjoerg   if (!SS)
848*e038c9c4Sjoerg     return State;
849*e038c9c4Sjoerg 
850*e038c9c4Sjoerg   if (SS->isClosed()) {
851*e038c9c4Sjoerg     // Using a stream pointer after 'fclose' causes undefined behavior
852*e038c9c4Sjoerg     // according to cppreference.com .
853*e038c9c4Sjoerg     ExplodedNode *N = C.generateErrorNode();
854*e038c9c4Sjoerg     if (N) {
855*e038c9c4Sjoerg       C.emitReport(std::make_unique<PathSensitiveBugReport>(
856*e038c9c4Sjoerg           BT_UseAfterClose,
857*e038c9c4Sjoerg           "Stream might be already closed. Causes undefined behaviour.", N));
858*e038c9c4Sjoerg       return nullptr;
859*e038c9c4Sjoerg     }
860*e038c9c4Sjoerg 
861*e038c9c4Sjoerg     return State;
862*e038c9c4Sjoerg   }
863*e038c9c4Sjoerg 
864*e038c9c4Sjoerg   if (SS->isOpenFailed()) {
865*e038c9c4Sjoerg     // Using a stream that has failed to open is likely to cause problems.
866*e038c9c4Sjoerg     // This should usually not occur because stream pointer is NULL.
867*e038c9c4Sjoerg     // But freopen can cause a state when stream pointer remains non-null but
868*e038c9c4Sjoerg     // failed to open.
869*e038c9c4Sjoerg     ExplodedNode *N = C.generateErrorNode();
870*e038c9c4Sjoerg     if (N) {
871*e038c9c4Sjoerg       C.emitReport(std::make_unique<PathSensitiveBugReport>(
872*e038c9c4Sjoerg           BT_UseAfterOpenFailed,
873*e038c9c4Sjoerg           "Stream might be invalid after "
874*e038c9c4Sjoerg           "(re-)opening it has failed. "
875*e038c9c4Sjoerg           "Can cause undefined behaviour.",
876*e038c9c4Sjoerg           N));
877*e038c9c4Sjoerg       return nullptr;
878*e038c9c4Sjoerg     }
879*e038c9c4Sjoerg     return State;
880*e038c9c4Sjoerg   }
881*e038c9c4Sjoerg 
882*e038c9c4Sjoerg   return State;
883*e038c9c4Sjoerg }
884*e038c9c4Sjoerg 
ensureNoFilePositionIndeterminate(SVal StreamVal,CheckerContext & C,ProgramStateRef State) const885*e038c9c4Sjoerg ProgramStateRef StreamChecker::ensureNoFilePositionIndeterminate(
886*e038c9c4Sjoerg     SVal StreamVal, CheckerContext &C, ProgramStateRef State) const {
887*e038c9c4Sjoerg   static const char *BugMessage =
888*e038c9c4Sjoerg       "File position of the stream might be 'indeterminate' "
889*e038c9c4Sjoerg       "after a failed operation. "
890*e038c9c4Sjoerg       "Can cause undefined behavior.";
891*e038c9c4Sjoerg 
892*e038c9c4Sjoerg   SymbolRef Sym = StreamVal.getAsSymbol();
893*e038c9c4Sjoerg   if (!Sym)
894*e038c9c4Sjoerg     return State;
895*e038c9c4Sjoerg 
896*e038c9c4Sjoerg   const StreamState *SS = State->get<StreamMap>(Sym);
897*e038c9c4Sjoerg   if (!SS)
898*e038c9c4Sjoerg     return State;
899*e038c9c4Sjoerg 
900*e038c9c4Sjoerg   assert(SS->isOpened() && "First ensure that stream is opened.");
901*e038c9c4Sjoerg 
902*e038c9c4Sjoerg   if (SS->FilePositionIndeterminate) {
903*e038c9c4Sjoerg     if (SS->ErrorState & ErrorFEof) {
904*e038c9c4Sjoerg       // The error is unknown but may be FEOF.
905*e038c9c4Sjoerg       // Continue analysis with the FEOF error state.
906*e038c9c4Sjoerg       // Report warning because the other possible error states.
907*e038c9c4Sjoerg       ExplodedNode *N = C.generateNonFatalErrorNode(State);
908*e038c9c4Sjoerg       if (!N)
909*e038c9c4Sjoerg         return nullptr;
910*e038c9c4Sjoerg 
911*e038c9c4Sjoerg       C.emitReport(std::make_unique<PathSensitiveBugReport>(
912*e038c9c4Sjoerg           BT_IndeterminatePosition, BugMessage, N));
913*e038c9c4Sjoerg       return State->set<StreamMap>(
914*e038c9c4Sjoerg           Sym, StreamState::getOpened(SS->LastOperation, ErrorFEof, false));
915*e038c9c4Sjoerg     }
916*e038c9c4Sjoerg 
917*e038c9c4Sjoerg     // Known or unknown error state without FEOF possible.
918*e038c9c4Sjoerg     // Stop analysis, report error.
919*e038c9c4Sjoerg     ExplodedNode *N = C.generateErrorNode(State);
920*e038c9c4Sjoerg     if (N)
921*e038c9c4Sjoerg       C.emitReport(std::make_unique<PathSensitiveBugReport>(
922*e038c9c4Sjoerg           BT_IndeterminatePosition, BugMessage, N));
923*e038c9c4Sjoerg 
924*e038c9c4Sjoerg     return nullptr;
925*e038c9c4Sjoerg   }
926*e038c9c4Sjoerg 
927*e038c9c4Sjoerg   return State;
928*e038c9c4Sjoerg }
929*e038c9c4Sjoerg 
930*e038c9c4Sjoerg ProgramStateRef
ensureFseekWhenceCorrect(SVal WhenceVal,CheckerContext & C,ProgramStateRef State) const931*e038c9c4Sjoerg StreamChecker::ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
932*e038c9c4Sjoerg                                         ProgramStateRef State) const {
933*e038c9c4Sjoerg   Optional<nonloc::ConcreteInt> CI = WhenceVal.getAs<nonloc::ConcreteInt>();
934*e038c9c4Sjoerg   if (!CI)
935*e038c9c4Sjoerg     return State;
936*e038c9c4Sjoerg 
937*e038c9c4Sjoerg   int64_t X = CI->getValue().getSExtValue();
938*e038c9c4Sjoerg   if (X >= 0 && X <= 2)
939*e038c9c4Sjoerg     return State;
940*e038c9c4Sjoerg 
941*e038c9c4Sjoerg   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
942*e038c9c4Sjoerg     C.emitReport(std::make_unique<PathSensitiveBugReport>(
943*e038c9c4Sjoerg         BT_IllegalWhence,
944*e038c9c4Sjoerg         "The whence argument to fseek() should be "
945*e038c9c4Sjoerg         "SEEK_SET, SEEK_END, or SEEK_CUR.",
946*e038c9c4Sjoerg         N));
947*e038c9c4Sjoerg     return nullptr;
948*e038c9c4Sjoerg   }
949*e038c9c4Sjoerg 
950*e038c9c4Sjoerg   return State;
951*e038c9c4Sjoerg }
952*e038c9c4Sjoerg 
reportFEofWarning(CheckerContext & C,ProgramStateRef State) const953*e038c9c4Sjoerg void StreamChecker::reportFEofWarning(CheckerContext &C,
954*e038c9c4Sjoerg                                       ProgramStateRef State) const {
955*e038c9c4Sjoerg   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
956*e038c9c4Sjoerg     C.emitReport(std::make_unique<PathSensitiveBugReport>(
957*e038c9c4Sjoerg         BT_StreamEof,
958*e038c9c4Sjoerg         "Read function called when stream is in EOF state. "
959*e038c9c4Sjoerg         "Function has no effect.",
960*e038c9c4Sjoerg         N));
961*e038c9c4Sjoerg     return;
962*e038c9c4Sjoerg   }
963*e038c9c4Sjoerg   C.addTransition(State);
964*e038c9c4Sjoerg }
965*e038c9c4Sjoerg 
966*e038c9c4Sjoerg ExplodedNode *
reportLeaks(const SmallVector<SymbolRef,2> & LeakedSyms,CheckerContext & C,ExplodedNode * Pred) const967*e038c9c4Sjoerg StreamChecker::reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
968*e038c9c4Sjoerg                            CheckerContext &C, ExplodedNode *Pred) const {
969*e038c9c4Sjoerg   ExplodedNode *Err = C.generateNonFatalErrorNode(C.getState(), Pred);
970*e038c9c4Sjoerg   if (!Err)
971*e038c9c4Sjoerg     return Pred;
972*e038c9c4Sjoerg 
973*e038c9c4Sjoerg   for (SymbolRef LeakSym : LeakedSyms) {
974*e038c9c4Sjoerg     // Resource leaks can result in multiple warning that describe the same kind
975*e038c9c4Sjoerg     // of programming error:
976*e038c9c4Sjoerg     //  void f() {
977*e038c9c4Sjoerg     //    FILE *F = fopen("a.txt");
978*e038c9c4Sjoerg     //    if (rand()) // state split
979*e038c9c4Sjoerg     //      return; // warning
980*e038c9c4Sjoerg     //  } // warning
981*e038c9c4Sjoerg     // While this isn't necessarily true (leaking the same stream could result
982*e038c9c4Sjoerg     // from a different kinds of errors), the reduction in redundant reports
983*e038c9c4Sjoerg     // makes this a worthwhile heuristic.
984*e038c9c4Sjoerg     // FIXME: Add a checker option to turn this uniqueing feature off.
985*e038c9c4Sjoerg     const ExplodedNode *StreamOpenNode = getAcquisitionSite(Err, LeakSym, C);
986*e038c9c4Sjoerg     assert(StreamOpenNode && "Could not find place of stream opening.");
987*e038c9c4Sjoerg     PathDiagnosticLocation LocUsedForUniqueing =
988*e038c9c4Sjoerg         PathDiagnosticLocation::createBegin(
989*e038c9c4Sjoerg             StreamOpenNode->getStmtForDiagnostics(), C.getSourceManager(),
990*e038c9c4Sjoerg             StreamOpenNode->getLocationContext());
991*e038c9c4Sjoerg 
992*e038c9c4Sjoerg     std::unique_ptr<PathSensitiveBugReport> R =
993*e038c9c4Sjoerg         std::make_unique<PathSensitiveBugReport>(
994*e038c9c4Sjoerg             BT_ResourceLeak,
995*e038c9c4Sjoerg             "Opened stream never closed. Potential resource leak.", Err,
996*e038c9c4Sjoerg             LocUsedForUniqueing,
997*e038c9c4Sjoerg             StreamOpenNode->getLocationContext()->getDecl());
998*e038c9c4Sjoerg     R->markInteresting(LeakSym);
999*e038c9c4Sjoerg     C.emitReport(std::move(R));
1000*e038c9c4Sjoerg   }
1001*e038c9c4Sjoerg 
1002*e038c9c4Sjoerg   return Err;
10037330f729Sjoerg }
10047330f729Sjoerg 
checkDeadSymbols(SymbolReaper & SymReaper,CheckerContext & C) const10057330f729Sjoerg void StreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
10067330f729Sjoerg                                      CheckerContext &C) const {
1007*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
10087330f729Sjoerg 
1009*e038c9c4Sjoerg   llvm::SmallVector<SymbolRef, 2> LeakedSyms;
1010*e038c9c4Sjoerg 
1011*e038c9c4Sjoerg   const StreamMapTy &Map = State->get<StreamMap>();
10127330f729Sjoerg   for (const auto &I : Map) {
10137330f729Sjoerg     SymbolRef Sym = I.first;
10147330f729Sjoerg     const StreamState &SS = I.second;
1015*e038c9c4Sjoerg     if (!SymReaper.isDead(Sym))
10167330f729Sjoerg       continue;
1017*e038c9c4Sjoerg     if (SS.isOpened())
1018*e038c9c4Sjoerg       LeakedSyms.push_back(Sym);
1019*e038c9c4Sjoerg     State = State->remove<StreamMap>(Sym);
10207330f729Sjoerg   }
10217330f729Sjoerg 
1022*e038c9c4Sjoerg   ExplodedNode *N = C.getPredecessor();
1023*e038c9c4Sjoerg   if (!LeakedSyms.empty())
1024*e038c9c4Sjoerg     N = reportLeaks(LeakedSyms, C, N);
1025*e038c9c4Sjoerg 
1026*e038c9c4Sjoerg   C.addTransition(State, N);
10277330f729Sjoerg }
10287330f729Sjoerg 
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const1029*e038c9c4Sjoerg ProgramStateRef StreamChecker::checkPointerEscape(
1030*e038c9c4Sjoerg     ProgramStateRef State, const InvalidatedSymbols &Escaped,
1031*e038c9c4Sjoerg     const CallEvent *Call, PointerEscapeKind Kind) const {
1032*e038c9c4Sjoerg   // Check for file-handling system call that is not handled by the checker.
1033*e038c9c4Sjoerg   // FIXME: The checker should be updated to handle all system calls that take
1034*e038c9c4Sjoerg   // 'FILE*' argument. These are now ignored.
1035*e038c9c4Sjoerg   if (Kind == PSK_DirectEscapeOnCall && Call->isInSystemHeader())
1036*e038c9c4Sjoerg     return State;
1037*e038c9c4Sjoerg 
1038*e038c9c4Sjoerg   for (SymbolRef Sym : Escaped) {
1039*e038c9c4Sjoerg     // The symbol escaped.
1040*e038c9c4Sjoerg     // From now the stream can be manipulated in unknown way to the checker,
1041*e038c9c4Sjoerg     // it is not possible to handle it any more.
1042*e038c9c4Sjoerg     // Optimistically, assume that the corresponding file handle will be closed
1043*e038c9c4Sjoerg     // somewhere else.
1044*e038c9c4Sjoerg     // Remove symbol from state so the following stream calls on this symbol are
1045*e038c9c4Sjoerg     // not handled by the checker.
1046*e038c9c4Sjoerg     State = State->remove<StreamMap>(Sym);
1047*e038c9c4Sjoerg   }
1048*e038c9c4Sjoerg   return State;
1049*e038c9c4Sjoerg }
1050*e038c9c4Sjoerg 
registerStreamChecker(CheckerManager & Mgr)1051*e038c9c4Sjoerg void ento::registerStreamChecker(CheckerManager &Mgr) {
1052*e038c9c4Sjoerg   Mgr.registerChecker<StreamChecker>();
1053*e038c9c4Sjoerg }
1054*e038c9c4Sjoerg 
shouldRegisterStreamChecker(const CheckerManager & Mgr)1055*e038c9c4Sjoerg bool ento::shouldRegisterStreamChecker(const CheckerManager &Mgr) {
1056*e038c9c4Sjoerg   return true;
1057*e038c9c4Sjoerg }
1058*e038c9c4Sjoerg 
registerStreamTesterChecker(CheckerManager & Mgr)1059*e038c9c4Sjoerg void ento::registerStreamTesterChecker(CheckerManager &Mgr) {
1060*e038c9c4Sjoerg   auto *Checker = Mgr.getChecker<StreamChecker>();
1061*e038c9c4Sjoerg   Checker->TestMode = true;
1062*e038c9c4Sjoerg }
1063*e038c9c4Sjoerg 
shouldRegisterStreamTesterChecker(const CheckerManager & Mgr)1064*e038c9c4Sjoerg bool ento::shouldRegisterStreamTesterChecker(const CheckerManager &Mgr) {
10657330f729Sjoerg   return true;
10667330f729Sjoerg }
1067