xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (revision 13d39cb6f7b20e596b66f59ebf4dba766451398b)
1 //===-- StreamChecker.cpp -----------------------------------------*- C++ -*--//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines checkers that model and check stream handling functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "NoOwnershipChangeVisitor.h"
14 #include "clang/ASTMatchers/ASTMatchFinder.h"
15 #include "clang/ASTMatchers/ASTMatchers.h"
16 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
27 #include "llvm/ADT/Sequence.h"
28 #include <functional>
29 #include <optional>
30 
31 using namespace clang;
32 using namespace ento;
33 using namespace std::placeholders;
34 
35 //===----------------------------------------------------------------------===//
36 // Definition of state data structures.
37 //===----------------------------------------------------------------------===//
38 
39 namespace {
40 
41 struct FnDescription;
42 
43 /// State of the stream error flags.
44 /// Sometimes it is not known to the checker what error flags are set.
45 /// This is indicated by setting more than one flag to true.
46 /// This is an optimization to avoid state splits.
47 /// A stream can either be in FEOF or FERROR but not both at the same time.
48 /// Multiple flags are set to handle the corresponding states together.
49 struct StreamErrorState {
50   /// The stream can be in state where none of the error flags set.
51   bool NoError = true;
52   /// The stream can be in state where the EOF indicator is set.
53   bool FEof = false;
54   /// The stream can be in state where the error indicator is set.
55   bool FError = false;
56 
57   bool isNoError() const { return NoError && !FEof && !FError; }
58   bool isFEof() const { return !NoError && FEof && !FError; }
59   bool isFError() const { return !NoError && !FEof && FError; }
60 
61   bool operator==(const StreamErrorState &ES) const {
62     return NoError == ES.NoError && FEof == ES.FEof && FError == ES.FError;
63   }
64 
65   bool operator!=(const StreamErrorState &ES) const { return !(*this == ES); }
66 
67   StreamErrorState operator|(const StreamErrorState &E) const {
68     return {NoError || E.NoError, FEof || E.FEof, FError || E.FError};
69   }
70 
71   StreamErrorState operator&(const StreamErrorState &E) const {
72     return {NoError && E.NoError, FEof && E.FEof, FError && E.FError};
73   }
74 
75   StreamErrorState operator~() const { return {!NoError, !FEof, !FError}; }
76 
77   /// Returns if the StreamErrorState is a valid object.
78   operator bool() const { return NoError || FEof || FError; }
79 
80   LLVM_DUMP_METHOD void dump() const { dumpToStream(llvm::errs()); }
81   LLVM_DUMP_METHOD void dumpToStream(llvm::raw_ostream &os) const {
82     os << "NoError: " << NoError << ", FEof: " << FEof
83        << ", FError: " << FError;
84   }
85 
86   void Profile(llvm::FoldingSetNodeID &ID) const {
87     ID.AddBoolean(NoError);
88     ID.AddBoolean(FEof);
89     ID.AddBoolean(FError);
90   }
91 };
92 
93 const StreamErrorState ErrorNone{true, false, false};
94 const StreamErrorState ErrorFEof{false, true, false};
95 const StreamErrorState ErrorFError{false, false, true};
96 
97 /// Full state information about a stream pointer.
98 struct StreamState {
99   /// The last file operation called in the stream.
100   /// Can be nullptr.
101   const FnDescription *LastOperation;
102 
103   /// State of a stream symbol.
104   enum KindTy {
105     Opened, /// Stream is opened.
106     Closed, /// Closed stream (an invalid stream pointer after it was closed).
107     OpenFailed /// The last open operation has failed.
108   } State;
109 
110   StringRef getKindStr() const {
111     switch (State) {
112     case Opened:
113       return "Opened";
114     case Closed:
115       return "Closed";
116     case OpenFailed:
117       return "OpenFailed";
118     }
119     llvm_unreachable("Unknown StreamState!");
120   }
121 
122   /// State of the error flags.
123   /// Ignored in non-opened stream state but must be NoError.
124   StreamErrorState const ErrorState;
125 
126   /// Indicate if the file has an "indeterminate file position indicator".
127   /// This can be set at a failing read or write or seek operation.
128   /// If it is set no more read or write is allowed.
129   /// This value is not dependent on the stream error flags:
130   /// The error flag may be cleared with `clearerr` but the file position
131   /// remains still indeterminate.
132   /// This value applies to all error states in ErrorState except FEOF.
133   /// An EOF+indeterminate state is the same as EOF state.
134   bool const FilePositionIndeterminate = false;
135 
136   StreamState(const FnDescription *L, KindTy S, const StreamErrorState &ES,
137               bool IsFilePositionIndeterminate)
138       : LastOperation(L), State(S), ErrorState(ES),
139         FilePositionIndeterminate(IsFilePositionIndeterminate) {
140     assert((!ES.isFEof() || !IsFilePositionIndeterminate) &&
141            "FilePositionIndeterminate should be false in FEof case.");
142     assert((State == Opened || ErrorState.isNoError()) &&
143            "ErrorState should be None in non-opened stream state.");
144   }
145 
146   bool isOpened() const { return State == Opened; }
147   bool isClosed() const { return State == Closed; }
148   bool isOpenFailed() const { return State == OpenFailed; }
149 
150   bool operator==(const StreamState &X) const {
151     // In not opened state error state should always NoError, so comparison
152     // here is no problem.
153     return LastOperation == X.LastOperation && State == X.State &&
154            ErrorState == X.ErrorState &&
155            FilePositionIndeterminate == X.FilePositionIndeterminate;
156   }
157 
158   static StreamState getOpened(const FnDescription *L,
159                                const StreamErrorState &ES = ErrorNone,
160                                bool IsFilePositionIndeterminate = false) {
161     return StreamState{L, Opened, ES, IsFilePositionIndeterminate};
162   }
163   static StreamState getClosed(const FnDescription *L) {
164     return StreamState{L, Closed, {}, false};
165   }
166   static StreamState getOpenFailed(const FnDescription *L) {
167     return StreamState{L, OpenFailed, {}, false};
168   }
169 
170   LLVM_DUMP_METHOD void dump() const { dumpToStream(llvm::errs()); }
171   LLVM_DUMP_METHOD void dumpToStream(llvm::raw_ostream &os) const;
172 
173   void Profile(llvm::FoldingSetNodeID &ID) const {
174     ID.AddPointer(LastOperation);
175     ID.AddInteger(State);
176     ErrorState.Profile(ID);
177     ID.AddBoolean(FilePositionIndeterminate);
178   }
179 };
180 
181 } // namespace
182 
183 // This map holds the state of a stream.
184 // The stream is identified with a SymbolRef that is created when a stream
185 // opening function is modeled by the checker.
186 REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
187 
188 //===----------------------------------------------------------------------===//
189 // StreamChecker class and utility functions.
190 //===----------------------------------------------------------------------===//
191 
192 namespace {
193 
194 class StreamChecker;
195 using FnCheck = std::function<void(const StreamChecker *, const FnDescription *,
196                                    const CallEvent &, CheckerContext &)>;
197 
198 using ArgNoTy = unsigned int;
199 static const ArgNoTy ArgNone = std::numeric_limits<ArgNoTy>::max();
200 
201 const char *FeofNote = "Assuming stream reaches end-of-file here";
202 const char *FerrorNote = "Assuming this stream operation fails";
203 
204 struct FnDescription {
205   FnCheck PreFn;
206   FnCheck EvalFn;
207   ArgNoTy StreamArgNo;
208 };
209 
210 LLVM_DUMP_METHOD void StreamState::dumpToStream(llvm::raw_ostream &os) const {
211   os << "{Kind: " << getKindStr() << ", Last operation: " << LastOperation
212      << ", ErrorState: ";
213   ErrorState.dumpToStream(os);
214   os << ", FilePos: " << (FilePositionIndeterminate ? "Indeterminate" : "OK")
215      << '}';
216 }
217 
218 /// Get the value of the stream argument out of the passed call event.
219 /// The call should contain a function that is described by Desc.
220 SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
221   assert(Desc && Desc->StreamArgNo != ArgNone &&
222          "Try to get a non-existing stream argument.");
223   return Call.getArgSVal(Desc->StreamArgNo);
224 }
225 
226 /// Create a conjured symbol return value for a call expression.
227 DefinedSVal makeRetVal(CheckerContext &C, const CallExpr *CE) {
228   assert(CE && "Expecting a call expression.");
229 
230   const LocationContext *LCtx = C.getLocationContext();
231   return C.getSValBuilder()
232       .conjureSymbolVal(nullptr, CE, LCtx, C.blockCount())
233       .castAs<DefinedSVal>();
234 }
235 
236 ProgramStateRef bindAndAssumeTrue(ProgramStateRef State, CheckerContext &C,
237                                   const CallExpr *CE) {
238   DefinedSVal RetVal = makeRetVal(C, CE);
239   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
240   State = State->assume(RetVal, true);
241   assert(State && "Assumption on new value should not fail.");
242   return State;
243 }
244 
245 ProgramStateRef bindInt(uint64_t Value, ProgramStateRef State,
246                         CheckerContext &C, const CallExpr *CE) {
247   State = State->BindExpr(CE, C.getLocationContext(),
248                           C.getSValBuilder().makeIntVal(Value, CE->getType()));
249   return State;
250 }
251 
252 inline void assertStreamStateOpened(const StreamState *SS) {
253   assert(SS->isOpened() && "Stream is expected to be opened");
254 }
255 
256 class StreamChecker : public Checker<check::PreCall, eval::Call,
257                                      check::DeadSymbols, check::PointerEscape,
258                                      check::ASTDecl<TranslationUnitDecl>> {
259   BugType BT_FileNull{this, "NULL stream pointer", "Stream handling error"};
260   BugType BT_UseAfterClose{this, "Closed stream", "Stream handling error"};
261   BugType BT_UseAfterOpenFailed{this, "Invalid stream",
262                                 "Stream handling error"};
263   BugType BT_IndeterminatePosition{this, "Invalid stream state",
264                                    "Stream handling error"};
265   BugType BT_IllegalWhence{this, "Illegal whence argument",
266                            "Stream handling error"};
267   BugType BT_StreamEof{this, "Stream already in EOF", "Stream handling error"};
268   BugType BT_ResourceLeak{this, "Resource leak", "Stream handling error",
269                           /*SuppressOnSink =*/true};
270 
271 public:
272   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
273   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
274   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
275   ProgramStateRef checkPointerEscape(ProgramStateRef State,
276                                      const InvalidatedSymbols &Escaped,
277                                      const CallEvent *Call,
278                                      PointerEscapeKind Kind) const;
279 
280   /// Finds the declarations of 'FILE *stdin, *stdout, *stderr'.
281   void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &,
282                     BugReporter &) const;
283 
284   const BugType *getBT_StreamEof() const { return &BT_StreamEof; }
285   const BugType *getBT_IndeterminatePosition() const {
286     return &BT_IndeterminatePosition;
287   }
288 
289   /// Assumes that the result of 'fopen' can't alias with the pointee of
290   /// 'stdin', 'stdout' or 'stderr'.
291   ProgramStateRef assumeNoAliasingWithStdStreams(ProgramStateRef State,
292                                                  DefinedSVal RetVal,
293                                                  CheckerContext &C) const;
294 
295   const NoteTag *constructSetEofNoteTag(CheckerContext &C,
296                                         SymbolRef StreamSym) const {
297     return C.getNoteTag([this, StreamSym](PathSensitiveBugReport &BR) {
298       if (!BR.isInteresting(StreamSym) ||
299           &BR.getBugType() != this->getBT_StreamEof())
300         return "";
301 
302       BR.markNotInteresting(StreamSym);
303 
304       return FeofNote;
305     });
306   }
307 
308   const NoteTag *constructSetErrorNoteTag(CheckerContext &C,
309                                           SymbolRef StreamSym) const {
310     return C.getNoteTag([this, StreamSym](PathSensitiveBugReport &BR) {
311       if (!BR.isInteresting(StreamSym) ||
312           &BR.getBugType() != this->getBT_IndeterminatePosition())
313         return "";
314 
315       BR.markNotInteresting(StreamSym);
316 
317       return FerrorNote;
318     });
319   }
320 
321   const NoteTag *constructSetEofOrErrorNoteTag(CheckerContext &C,
322                                                SymbolRef StreamSym) const {
323     return C.getNoteTag([this, StreamSym](PathSensitiveBugReport &BR) {
324       if (!BR.isInteresting(StreamSym))
325         return "";
326 
327       if (&BR.getBugType() == this->getBT_StreamEof()) {
328         BR.markNotInteresting(StreamSym);
329         return FeofNote;
330       }
331       if (&BR.getBugType() == this->getBT_IndeterminatePosition()) {
332         BR.markNotInteresting(StreamSym);
333         return FerrorNote;
334       }
335 
336       return "";
337     });
338   }
339 
340   /// If true, evaluate special testing stream functions.
341   bool TestMode = false;
342 
343   /// If true, generate failure branches for cases that are often not checked.
344   bool PedanticMode = false;
345 
346   const CallDescription FCloseDesc = {CDM::CLibrary, {"fclose"}, 1};
347 
348 private:
349   CallDescriptionMap<FnDescription> FnDescriptions = {
350       {{CDM::CLibrary, {"fopen"}, 2},
351        {nullptr, &StreamChecker::evalFopen, ArgNone}},
352       {{CDM::CLibrary, {"fdopen"}, 2},
353        {nullptr, &StreamChecker::evalFopen, ArgNone}},
354       {{CDM::CLibrary, {"freopen"}, 3},
355        {&StreamChecker::preFreopen, &StreamChecker::evalFreopen, 2}},
356       {{CDM::CLibrary, {"tmpfile"}, 0},
357        {nullptr, &StreamChecker::evalFopen, ArgNone}},
358       {FCloseDesc, {&StreamChecker::preDefault, &StreamChecker::evalFclose, 0}},
359       {{CDM::CLibrary, {"fread"}, 4},
360        {&StreamChecker::preRead,
361         std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, true), 3}},
362       {{CDM::CLibrary, {"fwrite"}, 4},
363        {&StreamChecker::preWrite,
364         std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, false), 3}},
365       {{CDM::CLibrary, {"fgetc"}, 1},
366        {&StreamChecker::preRead,
367         std::bind(&StreamChecker::evalFgetx, _1, _2, _3, _4, true), 0}},
368       {{CDM::CLibrary, {"fgets"}, 3},
369        {&StreamChecker::preRead,
370         std::bind(&StreamChecker::evalFgetx, _1, _2, _3, _4, false), 2}},
371       {{CDM::CLibrary, {"getc"}, 1},
372        {&StreamChecker::preRead,
373         std::bind(&StreamChecker::evalFgetx, _1, _2, _3, _4, true), 0}},
374       {{CDM::CLibrary, {"fputc"}, 2},
375        {&StreamChecker::preWrite,
376         std::bind(&StreamChecker::evalFputx, _1, _2, _3, _4, true), 1}},
377       {{CDM::CLibrary, {"fputs"}, 2},
378        {&StreamChecker::preWrite,
379         std::bind(&StreamChecker::evalFputx, _1, _2, _3, _4, false), 1}},
380       {{CDM::CLibrary, {"putc"}, 2},
381        {&StreamChecker::preWrite,
382         std::bind(&StreamChecker::evalFputx, _1, _2, _3, _4, true), 1}},
383       {{CDM::CLibrary, {"fprintf"}},
384        {&StreamChecker::preWrite,
385         std::bind(&StreamChecker::evalFprintf, _1, _2, _3, _4), 0}},
386       {{CDM::CLibrary, {"vfprintf"}, 3},
387        {&StreamChecker::preWrite,
388         std::bind(&StreamChecker::evalFprintf, _1, _2, _3, _4), 0}},
389       {{CDM::CLibrary, {"fscanf"}},
390        {&StreamChecker::preRead,
391         std::bind(&StreamChecker::evalFscanf, _1, _2, _3, _4), 0}},
392       {{CDM::CLibrary, {"vfscanf"}, 3},
393        {&StreamChecker::preRead,
394         std::bind(&StreamChecker::evalFscanf, _1, _2, _3, _4), 0}},
395       {{CDM::CLibrary, {"ungetc"}, 2},
396        {&StreamChecker::preWrite,
397         std::bind(&StreamChecker::evalUngetc, _1, _2, _3, _4), 1}},
398       {{CDM::CLibrary, {"getdelim"}, 4},
399        {&StreamChecker::preRead,
400         std::bind(&StreamChecker::evalGetdelim, _1, _2, _3, _4), 3}},
401       {{CDM::CLibrary, {"getline"}, 3},
402        {&StreamChecker::preRead,
403         std::bind(&StreamChecker::evalGetdelim, _1, _2, _3, _4), 2}},
404       {{CDM::CLibrary, {"fseek"}, 3},
405        {&StreamChecker::preFseek, &StreamChecker::evalFseek, 0}},
406       {{CDM::CLibrary, {"fseeko"}, 3},
407        {&StreamChecker::preFseek, &StreamChecker::evalFseek, 0}},
408       {{CDM::CLibrary, {"ftell"}, 1},
409        {&StreamChecker::preWrite, &StreamChecker::evalFtell, 0}},
410       {{CDM::CLibrary, {"ftello"}, 1},
411        {&StreamChecker::preWrite, &StreamChecker::evalFtell, 0}},
412       {{CDM::CLibrary, {"fflush"}, 1},
413        {&StreamChecker::preFflush, &StreamChecker::evalFflush, 0}},
414       {{CDM::CLibrary, {"rewind"}, 1},
415        {&StreamChecker::preDefault, &StreamChecker::evalRewind, 0}},
416       {{CDM::CLibrary, {"fgetpos"}, 2},
417        {&StreamChecker::preWrite, &StreamChecker::evalFgetpos, 0}},
418       {{CDM::CLibrary, {"fsetpos"}, 2},
419        {&StreamChecker::preDefault, &StreamChecker::evalFsetpos, 0}},
420       {{CDM::CLibrary, {"clearerr"}, 1},
421        {&StreamChecker::preDefault, &StreamChecker::evalClearerr, 0}},
422       {{CDM::CLibrary, {"feof"}, 1},
423        {&StreamChecker::preDefault,
424         std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFEof),
425         0}},
426       {{CDM::CLibrary, {"ferror"}, 1},
427        {&StreamChecker::preDefault,
428         std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFError),
429         0}},
430       {{CDM::CLibrary, {"fileno"}, 1},
431        {&StreamChecker::preDefault, &StreamChecker::evalFileno, 0}},
432   };
433 
434   CallDescriptionMap<FnDescription> FnTestDescriptions = {
435       {{CDM::SimpleFunc, {"StreamTesterChecker_make_feof_stream"}, 1},
436        {nullptr,
437         std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4, ErrorFEof,
438                   false),
439         0}},
440       {{CDM::SimpleFunc, {"StreamTesterChecker_make_ferror_stream"}, 1},
441        {nullptr,
442         std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4,
443                   ErrorFError, false),
444         0}},
445       {{CDM::SimpleFunc,
446         {"StreamTesterChecker_make_ferror_indeterminate_stream"},
447         1},
448        {nullptr,
449         std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4,
450                   ErrorFError, true),
451         0}},
452   };
453 
454   /// Expanded value of EOF, empty before initialization.
455   mutable std::optional<int> EofVal;
456   /// Expanded value of SEEK_SET, 0 if not found.
457   mutable int SeekSetVal = 0;
458   /// Expanded value of SEEK_CUR, 1 if not found.
459   mutable int SeekCurVal = 1;
460   /// Expanded value of SEEK_END, 2 if not found.
461   mutable int SeekEndVal = 2;
462   /// The built-in va_list type is platform-specific
463   mutable QualType VaListType;
464 
465   mutable const VarDecl *StdinDecl = nullptr;
466   mutable const VarDecl *StdoutDecl = nullptr;
467   mutable const VarDecl *StderrDecl = nullptr;
468 
469   void evalFopen(const FnDescription *Desc, const CallEvent &Call,
470                  CheckerContext &C) const;
471 
472   void preFreopen(const FnDescription *Desc, const CallEvent &Call,
473                   CheckerContext &C) const;
474   void evalFreopen(const FnDescription *Desc, const CallEvent &Call,
475                    CheckerContext &C) const;
476 
477   void evalFclose(const FnDescription *Desc, const CallEvent &Call,
478                   CheckerContext &C) const;
479 
480   void preRead(const FnDescription *Desc, const CallEvent &Call,
481                CheckerContext &C) const;
482 
483   void preWrite(const FnDescription *Desc, const CallEvent &Call,
484                 CheckerContext &C) const;
485 
486   void evalFreadFwrite(const FnDescription *Desc, const CallEvent &Call,
487                        CheckerContext &C, bool IsFread) const;
488 
489   void evalFgetx(const FnDescription *Desc, const CallEvent &Call,
490                  CheckerContext &C, bool SingleChar) const;
491 
492   void evalFputx(const FnDescription *Desc, const CallEvent &Call,
493                  CheckerContext &C, bool IsSingleChar) const;
494 
495   void evalFprintf(const FnDescription *Desc, const CallEvent &Call,
496                    CheckerContext &C) const;
497 
498   void evalFscanf(const FnDescription *Desc, const CallEvent &Call,
499                   CheckerContext &C) const;
500 
501   void evalUngetc(const FnDescription *Desc, const CallEvent &Call,
502                   CheckerContext &C) const;
503 
504   void evalGetdelim(const FnDescription *Desc, const CallEvent &Call,
505                     CheckerContext &C) const;
506 
507   void preFseek(const FnDescription *Desc, const CallEvent &Call,
508                 CheckerContext &C) const;
509   void evalFseek(const FnDescription *Desc, const CallEvent &Call,
510                  CheckerContext &C) const;
511 
512   void evalFgetpos(const FnDescription *Desc, const CallEvent &Call,
513                    CheckerContext &C) const;
514 
515   void evalFsetpos(const FnDescription *Desc, const CallEvent &Call,
516                    CheckerContext &C) const;
517 
518   void evalFtell(const FnDescription *Desc, const CallEvent &Call,
519                  CheckerContext &C) const;
520 
521   void evalRewind(const FnDescription *Desc, const CallEvent &Call,
522                   CheckerContext &C) const;
523 
524   void preDefault(const FnDescription *Desc, const CallEvent &Call,
525                   CheckerContext &C) const;
526 
527   void evalClearerr(const FnDescription *Desc, const CallEvent &Call,
528                     CheckerContext &C) const;
529 
530   void evalFeofFerror(const FnDescription *Desc, const CallEvent &Call,
531                       CheckerContext &C,
532                       const StreamErrorState &ErrorKind) const;
533 
534   void evalSetFeofFerror(const FnDescription *Desc, const CallEvent &Call,
535                          CheckerContext &C, const StreamErrorState &ErrorKind,
536                          bool Indeterminate) const;
537 
538   void preFflush(const FnDescription *Desc, const CallEvent &Call,
539                  CheckerContext &C) const;
540 
541   void evalFflush(const FnDescription *Desc, const CallEvent &Call,
542                   CheckerContext &C) const;
543 
544   void evalFileno(const FnDescription *Desc, const CallEvent &Call,
545                   CheckerContext &C) const;
546 
547   /// Check that the stream (in StreamVal) is not NULL.
548   /// If it can only be NULL a fatal error is emitted and nullptr returned.
549   /// Otherwise the return value is a new state where the stream is constrained
550   /// to be non-null.
551   ProgramStateRef ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
552                                       CheckerContext &C,
553                                       ProgramStateRef State) const;
554 
555   /// Check that the stream is the opened state.
556   /// If the stream is known to be not opened an error is generated
557   /// and nullptr returned, otherwise the original state is returned.
558   ProgramStateRef ensureStreamOpened(SVal StreamVal, CheckerContext &C,
559                                      ProgramStateRef State) const;
560 
561   /// Check that the stream has not an invalid ("indeterminate") file position,
562   /// generate warning for it.
563   /// (EOF is not an invalid position.)
564   /// The returned state can be nullptr if a fatal error was generated.
565   /// It can return non-null state if the stream has not an invalid position or
566   /// there is execution path with non-invalid position.
567   ProgramStateRef
568   ensureNoFilePositionIndeterminate(SVal StreamVal, CheckerContext &C,
569                                     ProgramStateRef State) const;
570 
571   /// Check the legality of the 'whence' argument of 'fseek'.
572   /// Generate error and return nullptr if it is found to be illegal.
573   /// Otherwise returns the state.
574   /// (State is not changed here because the "whence" value is already known.)
575   ProgramStateRef ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
576                                            ProgramStateRef State) const;
577 
578   /// Generate warning about stream in EOF state.
579   /// There will be always a state transition into the passed State,
580   /// by the new non-fatal error node or (if failed) a normal transition,
581   /// to ensure uniform handling.
582   void reportFEofWarning(SymbolRef StreamSym, CheckerContext &C,
583                          ProgramStateRef State) const;
584 
585   /// Emit resource leak warnings for the given symbols.
586   /// Createn a non-fatal error node for these, and returns it (if any warnings
587   /// were generated). Return value is non-null.
588   ExplodedNode *reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
589                             CheckerContext &C, ExplodedNode *Pred) const;
590 
591   /// Find the description data of the function called by a call event.
592   /// Returns nullptr if no function is recognized.
593   const FnDescription *lookupFn(const CallEvent &Call) const {
594     // Recognize "global C functions" with only integral or pointer arguments
595     // (and matching name) as stream functions.
596     for (auto *P : Call.parameters()) {
597       QualType T = P->getType();
598       if (!T->isIntegralOrEnumerationType() && !T->isPointerType() &&
599           T.getCanonicalType() != VaListType)
600         return nullptr;
601     }
602 
603     return FnDescriptions.lookup(Call);
604   }
605 
606   /// Generate a message for BugReporterVisitor if the stored symbol is
607   /// marked as interesting by the actual bug report.
608   const NoteTag *constructLeakNoteTag(CheckerContext &C, SymbolRef StreamSym,
609                                       const std::string &Message) const {
610     return C.getNoteTag([this, StreamSym,
611                          Message](PathSensitiveBugReport &BR) -> std::string {
612       if (BR.isInteresting(StreamSym) && &BR.getBugType() == &BT_ResourceLeak)
613         return Message;
614       return "";
615     });
616   }
617 
618   void initMacroValues(const Preprocessor &PP) const {
619     if (EofVal)
620       return;
621 
622     if (const std::optional<int> OptInt = tryExpandAsInteger("EOF", PP))
623       EofVal = *OptInt;
624     else
625       EofVal = -1;
626     if (const std::optional<int> OptInt = tryExpandAsInteger("SEEK_SET", PP))
627       SeekSetVal = *OptInt;
628     if (const std::optional<int> OptInt = tryExpandAsInteger("SEEK_END", PP))
629       SeekEndVal = *OptInt;
630     if (const std::optional<int> OptInt = tryExpandAsInteger("SEEK_CUR", PP))
631       SeekCurVal = *OptInt;
632   }
633 
634   /// Searches for the ExplodedNode where the file descriptor was acquired for
635   /// StreamSym.
636   static const ExplodedNode *getAcquisitionSite(const ExplodedNode *N,
637                                                 SymbolRef StreamSym,
638                                                 CheckerContext &C);
639 };
640 
641 struct StreamOperationEvaluator {
642   SValBuilder &SVB;
643   const ASTContext &ACtx;
644 
645   SymbolRef StreamSym = nullptr;
646   const StreamState *SS = nullptr;
647   const CallExpr *CE = nullptr;
648   StreamErrorState NewES;
649 
650   StreamOperationEvaluator(CheckerContext &C)
651       : SVB(C.getSValBuilder()), ACtx(C.getASTContext()) {
652     ;
653   }
654 
655   bool Init(const FnDescription *Desc, const CallEvent &Call, CheckerContext &C,
656             ProgramStateRef State) {
657     StreamSym = getStreamArg(Desc, Call).getAsSymbol();
658     if (!StreamSym)
659       return false;
660     SS = State->get<StreamMap>(StreamSym);
661     if (!SS)
662       return false;
663     NewES = SS->ErrorState;
664     CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
665     if (!CE)
666       return false;
667 
668     assertStreamStateOpened(SS);
669 
670     return true;
671   }
672 
673   bool isStreamEof() const { return SS->ErrorState == ErrorFEof; }
674 
675   NonLoc getZeroVal(const CallEvent &Call) {
676     return *SVB.makeZeroVal(Call.getResultType()).getAs<NonLoc>();
677   }
678 
679   ProgramStateRef setStreamState(ProgramStateRef State,
680                                  const StreamState &NewSS) {
681     NewES = NewSS.ErrorState;
682     return State->set<StreamMap>(StreamSym, NewSS);
683   }
684 
685   ProgramStateRef makeAndBindRetVal(ProgramStateRef State, CheckerContext &C) {
686     NonLoc RetVal = makeRetVal(C, CE).castAs<NonLoc>();
687     return State->BindExpr(CE, C.getLocationContext(), RetVal);
688   }
689 
690   ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
691                                   uint64_t Val) {
692     return State->BindExpr(CE, C.getLocationContext(),
693                            SVB.makeIntVal(Val, CE->getCallReturnType(ACtx)));
694   }
695 
696   ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
697                                   SVal Val) {
698     return State->BindExpr(CE, C.getLocationContext(), Val);
699   }
700 
701   ProgramStateRef bindNullReturnValue(ProgramStateRef State,
702                                       CheckerContext &C) {
703     return State->BindExpr(CE, C.getLocationContext(),
704                            C.getSValBuilder().makeNullWithType(CE->getType()));
705   }
706 
707   ProgramStateRef assumeBinOpNN(ProgramStateRef State,
708                                 BinaryOperator::Opcode Op, NonLoc LHS,
709                                 NonLoc RHS) {
710     auto Cond = SVB.evalBinOpNN(State, Op, LHS, RHS, SVB.getConditionType())
711                     .getAs<DefinedOrUnknownSVal>();
712     if (!Cond)
713       return nullptr;
714     return State->assume(*Cond, true);
715   }
716 
717   ConstraintManager::ProgramStatePair
718   makeRetValAndAssumeDual(ProgramStateRef State, CheckerContext &C) {
719     DefinedSVal RetVal = makeRetVal(C, CE);
720     State = State->BindExpr(CE, C.getLocationContext(), RetVal);
721     return C.getConstraintManager().assumeDual(State, RetVal);
722   }
723 
724   const NoteTag *getFailureNoteTag(const StreamChecker *Ch, CheckerContext &C) {
725     bool SetFeof = NewES.FEof && !SS->ErrorState.FEof;
726     bool SetFerror = NewES.FError && !SS->ErrorState.FError;
727     if (SetFeof && !SetFerror)
728       return Ch->constructSetEofNoteTag(C, StreamSym);
729     if (!SetFeof && SetFerror)
730       return Ch->constructSetErrorNoteTag(C, StreamSym);
731     if (SetFeof && SetFerror)
732       return Ch->constructSetEofOrErrorNoteTag(C, StreamSym);
733     return nullptr;
734   }
735 };
736 
737 } // end anonymous namespace
738 
739 //===----------------------------------------------------------------------===//
740 // Definition of NoStreamStateChangeVisitor.
741 //===----------------------------------------------------------------------===//
742 
743 namespace {
744 class NoStreamStateChangeVisitor final : public NoOwnershipChangeVisitor {
745 protected:
746   /// Syntactically checks whether the callee is a closing function. Since
747   /// we have no path-sensitive information on this call (we would need a
748   /// CallEvent instead of a CallExpr for that), its possible that a
749   /// closing function was called indirectly through a function pointer,
750   /// but we are not able to tell, so this is a best effort analysis.
751   bool isClosingCallAsWritten(const CallExpr &Call) const {
752     const auto *StreamChk = static_cast<const StreamChecker *>(&Checker);
753     return StreamChk->FCloseDesc.matchesAsWritten(Call);
754   }
755 
756   bool doesFnIntendToHandleOwnership(const Decl *Callee,
757                                      ASTContext &ACtx) final {
758     using namespace clang::ast_matchers;
759     const FunctionDecl *FD = dyn_cast<FunctionDecl>(Callee);
760 
761     auto Matches =
762         match(findAll(callExpr().bind("call")), *FD->getBody(), ACtx);
763     for (BoundNodes Match : Matches) {
764       if (const auto *Call = Match.getNodeAs<CallExpr>("call"))
765         if (isClosingCallAsWritten(*Call))
766           return true;
767     }
768     // TODO: Ownership might change with an attempt to store stream object, not
769     // only through closing it. Check for attempted stores as well.
770     return false;
771   }
772 
773   bool hasResourceStateChanged(ProgramStateRef CallEnterState,
774                                ProgramStateRef CallExitEndState) final {
775     return CallEnterState->get<StreamMap>(Sym) !=
776            CallExitEndState->get<StreamMap>(Sym);
777   }
778 
779   PathDiagnosticPieceRef emitNote(const ExplodedNode *N) override {
780     PathDiagnosticLocation L = PathDiagnosticLocation::create(
781         N->getLocation(),
782         N->getState()->getStateManager().getContext().getSourceManager());
783     return std::make_shared<PathDiagnosticEventPiece>(
784         L, "Returning without closing stream object or storing it for later "
785            "release");
786   }
787 
788 public:
789   NoStreamStateChangeVisitor(SymbolRef Sym, const StreamChecker *Checker)
790       : NoOwnershipChangeVisitor(Sym, Checker) {}
791 };
792 
793 } // end anonymous namespace
794 
795 const ExplodedNode *StreamChecker::getAcquisitionSite(const ExplodedNode *N,
796                                                       SymbolRef StreamSym,
797                                                       CheckerContext &C) {
798   ProgramStateRef State = N->getState();
799   // When bug type is resource leak, exploded node N may not have state info
800   // for leaked file descriptor, but predecessor should have it.
801   if (!State->get<StreamMap>(StreamSym))
802     N = N->getFirstPred();
803 
804   const ExplodedNode *Pred = N;
805   while (N) {
806     State = N->getState();
807     if (!State->get<StreamMap>(StreamSym))
808       return Pred;
809     Pred = N;
810     N = N->getFirstPred();
811   }
812 
813   return nullptr;
814 }
815 
816 static std::optional<int64_t> getKnownValue(ProgramStateRef State, SVal V) {
817   SValBuilder &SVB = State->getStateManager().getSValBuilder();
818   if (const llvm::APSInt *Int = SVB.getKnownValue(State, V))
819     return Int->tryExtValue();
820   return std::nullopt;
821 }
822 
823 /// Invalidate only the requested elements instead of the whole buffer.
824 /// This is basically a refinement of the more generic 'escapeArgs' or
825 /// the plain old 'invalidateRegions'.
826 static ProgramStateRef
827 escapeByStartIndexAndCount(ProgramStateRef State, const CallEvent &Call,
828                            unsigned BlockCount, const SubRegion *Buffer,
829                            QualType ElemType, int64_t StartIndex,
830                            int64_t ElementCount) {
831   constexpr auto DoNotInvalidateSuperRegion =
832       RegionAndSymbolInvalidationTraits::InvalidationKinds::
833           TK_DoNotInvalidateSuperRegion;
834 
835   const LocationContext *LCtx = Call.getLocationContext();
836   const ASTContext &Ctx = State->getStateManager().getContext();
837   SValBuilder &SVB = State->getStateManager().getSValBuilder();
838   auto &RegionManager = Buffer->getMemRegionManager();
839 
840   SmallVector<SVal> EscapingVals;
841   EscapingVals.reserve(ElementCount);
842 
843   RegionAndSymbolInvalidationTraits ITraits;
844   for (auto Idx : llvm::seq(StartIndex, StartIndex + ElementCount)) {
845     NonLoc Index = SVB.makeArrayIndex(Idx);
846     const auto *Element =
847         RegionManager.getElementRegion(ElemType, Index, Buffer, Ctx);
848     EscapingVals.push_back(loc::MemRegionVal(Element));
849     ITraits.setTrait(Element, DoNotInvalidateSuperRegion);
850   }
851   return State->invalidateRegions(
852       EscapingVals, Call.getOriginExpr(), BlockCount, LCtx,
853       /*CausesPointerEscape=*/false,
854       /*InvalidatedSymbols=*/nullptr, &Call, &ITraits);
855 }
856 
857 static ProgramStateRef escapeArgs(ProgramStateRef State, CheckerContext &C,
858                                   const CallEvent &Call,
859                                   ArrayRef<unsigned int> EscapingArgs) {
860   auto GetArgSVal = [&Call](int Idx) { return Call.getArgSVal(Idx); };
861   auto EscapingVals = to_vector(map_range(EscapingArgs, GetArgSVal));
862   State = State->invalidateRegions(EscapingVals, Call.getOriginExpr(),
863                                    C.blockCount(), C.getLocationContext(),
864                                    /*CausesPointerEscape=*/false,
865                                    /*InvalidatedSymbols=*/nullptr);
866   return State;
867 }
868 
869 //===----------------------------------------------------------------------===//
870 // Methods of StreamChecker.
871 //===----------------------------------------------------------------------===//
872 
873 void StreamChecker::checkPreCall(const CallEvent &Call,
874                                  CheckerContext &C) const {
875   const FnDescription *Desc = lookupFn(Call);
876   if (!Desc || !Desc->PreFn)
877     return;
878 
879   Desc->PreFn(this, Desc, Call, C);
880 }
881 
882 bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
883   const FnDescription *Desc = lookupFn(Call);
884   if (!Desc && TestMode)
885     Desc = FnTestDescriptions.lookup(Call);
886   if (!Desc || !Desc->EvalFn)
887     return false;
888 
889   Desc->EvalFn(this, Desc, Call, C);
890 
891   return C.isDifferent();
892 }
893 
894 ProgramStateRef StreamChecker::assumeNoAliasingWithStdStreams(
895     ProgramStateRef State, DefinedSVal RetVal, CheckerContext &C) const {
896   auto assumeRetNE = [&C, RetVal](ProgramStateRef State,
897                                   const VarDecl *Var) -> ProgramStateRef {
898     if (!Var)
899       return State;
900     const auto *LCtx = C.getLocationContext();
901     auto &StoreMgr = C.getStoreManager();
902     auto &SVB = C.getSValBuilder();
903     SVal VarValue = State->getSVal(StoreMgr.getLValueVar(Var, LCtx));
904     auto NoAliasState =
905         SVB.evalBinOp(State, BO_NE, RetVal, VarValue, SVB.getConditionType())
906             .castAs<DefinedOrUnknownSVal>();
907     return State->assume(NoAliasState, true);
908   };
909 
910   assert(State);
911   State = assumeRetNE(State, StdinDecl);
912   State = assumeRetNE(State, StdoutDecl);
913   State = assumeRetNE(State, StderrDecl);
914   assert(State);
915   return State;
916 }
917 
918 void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call,
919                               CheckerContext &C) const {
920   ProgramStateRef State = C.getState();
921   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
922   if (!CE)
923     return;
924 
925   DefinedSVal RetVal = makeRetVal(C, CE);
926   SymbolRef RetSym = RetVal.getAsSymbol();
927   assert(RetSym && "RetVal must be a symbol here.");
928 
929   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
930 
931   // Bifurcate the state into two: one with a valid FILE* pointer, the other
932   // with a NULL.
933   ProgramStateRef StateNotNull, StateNull;
934   std::tie(StateNotNull, StateNull) =
935       C.getConstraintManager().assumeDual(State, RetVal);
936 
937   StateNotNull =
938       StateNotNull->set<StreamMap>(RetSym, StreamState::getOpened(Desc));
939   StateNull =
940       StateNull->set<StreamMap>(RetSym, StreamState::getOpenFailed(Desc));
941 
942   StateNotNull = assumeNoAliasingWithStdStreams(StateNotNull, RetVal, C);
943 
944   C.addTransition(StateNotNull,
945                   constructLeakNoteTag(C, RetSym, "Stream opened here"));
946   C.addTransition(StateNull);
947 }
948 
949 void StreamChecker::preFreopen(const FnDescription *Desc, const CallEvent &Call,
950                                CheckerContext &C) const {
951   // Do not allow NULL as passed stream pointer but allow a closed stream.
952   ProgramStateRef State = C.getState();
953   State = ensureStreamNonNull(getStreamArg(Desc, Call),
954                               Call.getArgExpr(Desc->StreamArgNo), C, State);
955   if (!State)
956     return;
957 
958   C.addTransition(State);
959 }
960 
961 void StreamChecker::evalFreopen(const FnDescription *Desc,
962                                 const CallEvent &Call,
963                                 CheckerContext &C) const {
964   ProgramStateRef State = C.getState();
965 
966   auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
967   if (!CE)
968     return;
969 
970   std::optional<DefinedSVal> StreamVal =
971       getStreamArg(Desc, Call).getAs<DefinedSVal>();
972   if (!StreamVal)
973     return;
974 
975   SymbolRef StreamSym = StreamVal->getAsSymbol();
976   // Do not care about concrete values for stream ("(FILE *)0x12345"?).
977   // FIXME: Can be stdin, stdout, stderr such values?
978   if (!StreamSym)
979     return;
980 
981   // Do not handle untracked stream. It is probably escaped.
982   if (!State->get<StreamMap>(StreamSym))
983     return;
984 
985   // Generate state for non-failed case.
986   // Return value is the passed stream pointer.
987   // According to the documentations, the stream is closed first
988   // but any close error is ignored. The state changes to (or remains) opened.
989   ProgramStateRef StateRetNotNull =
990       State->BindExpr(CE, C.getLocationContext(), *StreamVal);
991   // Generate state for NULL return value.
992   // Stream switches to OpenFailed state.
993   ProgramStateRef StateRetNull =
994       State->BindExpr(CE, C.getLocationContext(),
995                       C.getSValBuilder().makeNullWithType(CE->getType()));
996 
997   StateRetNotNull =
998       StateRetNotNull->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
999   StateRetNull =
1000       StateRetNull->set<StreamMap>(StreamSym, StreamState::getOpenFailed(Desc));
1001 
1002   C.addTransition(StateRetNotNull,
1003                   constructLeakNoteTag(C, StreamSym, "Stream reopened here"));
1004   C.addTransition(StateRetNull);
1005 }
1006 
1007 void StreamChecker::evalFclose(const FnDescription *Desc, const CallEvent &Call,
1008                                CheckerContext &C) const {
1009   ProgramStateRef State = C.getState();
1010   StreamOperationEvaluator E(C);
1011   if (!E.Init(Desc, Call, C, State))
1012     return;
1013 
1014   // Close the File Descriptor.
1015   // Regardless if the close fails or not, stream becomes "closed"
1016   // and can not be used any more.
1017   State = E.setStreamState(State, StreamState::getClosed(Desc));
1018 
1019   // Return 0 on success, EOF on failure.
1020   C.addTransition(E.bindReturnValue(State, C, 0));
1021   C.addTransition(E.bindReturnValue(State, C, *EofVal));
1022 }
1023 
1024 void StreamChecker::preRead(const FnDescription *Desc, const CallEvent &Call,
1025                             CheckerContext &C) const {
1026   ProgramStateRef State = C.getState();
1027   SVal StreamVal = getStreamArg(Desc, Call);
1028   State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
1029                               State);
1030   if (!State)
1031     return;
1032   State = ensureStreamOpened(StreamVal, C, State);
1033   if (!State)
1034     return;
1035   State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
1036   if (!State)
1037     return;
1038 
1039   SymbolRef Sym = StreamVal.getAsSymbol();
1040   if (Sym && State->get<StreamMap>(Sym)) {
1041     const StreamState *SS = State->get<StreamMap>(Sym);
1042     if (SS->ErrorState & ErrorFEof)
1043       reportFEofWarning(Sym, C, State);
1044   } else {
1045     C.addTransition(State);
1046   }
1047 }
1048 
1049 void StreamChecker::preWrite(const FnDescription *Desc, const CallEvent &Call,
1050                              CheckerContext &C) const {
1051   ProgramStateRef State = C.getState();
1052   SVal StreamVal = getStreamArg(Desc, Call);
1053   State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
1054                               State);
1055   if (!State)
1056     return;
1057   State = ensureStreamOpened(StreamVal, C, State);
1058   if (!State)
1059     return;
1060   State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
1061   if (!State)
1062     return;
1063 
1064   C.addTransition(State);
1065 }
1066 
1067 static QualType getPointeeType(const MemRegion *R) {
1068   if (!R)
1069     return {};
1070   if (const auto *ER = dyn_cast<ElementRegion>(R))
1071     return ER->getElementType();
1072   if (const auto *TR = dyn_cast<TypedValueRegion>(R))
1073     return TR->getValueType();
1074   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
1075     return SR->getPointeeStaticType();
1076   return {};
1077 }
1078 
1079 static std::optional<NonLoc> getStartIndex(SValBuilder &SVB,
1080                                            const MemRegion *R) {
1081   if (!R)
1082     return std::nullopt;
1083 
1084   auto Zero = [&SVB] {
1085     BasicValueFactory &BVF = SVB.getBasicValueFactory();
1086     return nonloc::ConcreteInt(BVF.getIntValue(0, /*isUnsigned=*/false));
1087   };
1088 
1089   if (const auto *ER = dyn_cast<ElementRegion>(R))
1090     return ER->getIndex();
1091   if (isa<TypedValueRegion>(R))
1092     return Zero();
1093   if (isa<SymbolicRegion>(R))
1094     return Zero();
1095   return std::nullopt;
1096 }
1097 
1098 static ProgramStateRef
1099 tryToInvalidateFReadBufferByElements(ProgramStateRef State, CheckerContext &C,
1100                                      const CallEvent &Call, NonLoc SizeVal,
1101                                      NonLoc NMembVal) {
1102   // Try to invalidate the individual elements.
1103   const auto *Buffer =
1104       dyn_cast_or_null<SubRegion>(Call.getArgSVal(0).getAsRegion());
1105 
1106   const ASTContext &Ctx = C.getASTContext();
1107   QualType ElemTy = getPointeeType(Buffer);
1108   std::optional<SVal> StartElementIndex =
1109       getStartIndex(C.getSValBuilder(), Buffer);
1110 
1111   // Drop the outermost ElementRegion to get the buffer.
1112   if (const auto *ER = dyn_cast_or_null<ElementRegion>(Buffer))
1113     Buffer = dyn_cast<SubRegion>(ER->getSuperRegion());
1114 
1115   std::optional<int64_t> CountVal = getKnownValue(State, NMembVal);
1116   std::optional<int64_t> Size = getKnownValue(State, SizeVal);
1117   std::optional<int64_t> StartIndexVal =
1118       getKnownValue(State, StartElementIndex.value_or(UnknownVal()));
1119 
1120   if (!ElemTy.isNull() && CountVal && Size && StartIndexVal) {
1121     int64_t NumBytesRead = Size.value() * CountVal.value();
1122     int64_t ElemSizeInChars = Ctx.getTypeSizeInChars(ElemTy).getQuantity();
1123     if (ElemSizeInChars == 0)
1124       return nullptr;
1125 
1126     bool IncompleteLastElement = (NumBytesRead % ElemSizeInChars) != 0;
1127     int64_t NumCompleteOrIncompleteElementsRead =
1128         NumBytesRead / ElemSizeInChars + IncompleteLastElement;
1129 
1130     constexpr int MaxInvalidatedElementsLimit = 64;
1131     if (NumCompleteOrIncompleteElementsRead <= MaxInvalidatedElementsLimit) {
1132       return escapeByStartIndexAndCount(State, Call, C.blockCount(), Buffer,
1133                                         ElemTy, *StartIndexVal,
1134                                         NumCompleteOrIncompleteElementsRead);
1135     }
1136   }
1137   return nullptr;
1138 }
1139 
1140 void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
1141                                     const CallEvent &Call, CheckerContext &C,
1142                                     bool IsFread) const {
1143   ProgramStateRef State = C.getState();
1144   StreamOperationEvaluator E(C);
1145   if (!E.Init(Desc, Call, C, State))
1146     return;
1147 
1148   std::optional<NonLoc> SizeVal = Call.getArgSVal(1).getAs<NonLoc>();
1149   if (!SizeVal)
1150     return;
1151   std::optional<NonLoc> NMembVal = Call.getArgSVal(2).getAs<NonLoc>();
1152   if (!NMembVal)
1153     return;
1154 
1155   // C'99 standard, §7.19.8.1.3, the return value of fread:
1156   // The fread function returns the number of elements successfully read, which
1157   // may be less than nmemb if a read error or end-of-file is encountered. If
1158   // size or nmemb is zero, fread returns zero and the contents of the array and
1159   // the state of the stream remain unchanged.
1160   if (State->isNull(*SizeVal).isConstrainedTrue() ||
1161       State->isNull(*NMembVal).isConstrainedTrue()) {
1162     // This is the "size or nmemb is zero" case.
1163     // Just return 0, do nothing more (not clear the error flags).
1164     C.addTransition(E.bindReturnValue(State, C, 0));
1165     return;
1166   }
1167 
1168   // At read, invalidate the buffer in any case of error or success,
1169   // except if EOF was already present.
1170   if (IsFread && !E.isStreamEof()) {
1171     // Try to invalidate the individual elements.
1172     // Otherwise just fall back to invalidating the whole buffer.
1173     ProgramStateRef InvalidatedState = tryToInvalidateFReadBufferByElements(
1174         State, C, Call, *SizeVal, *NMembVal);
1175     State =
1176         InvalidatedState ? InvalidatedState : escapeArgs(State, C, Call, {0});
1177   }
1178 
1179   // Generate a transition for the success state.
1180   // If we know the state to be FEOF at fread, do not add a success state.
1181   if (!IsFread || !E.isStreamEof()) {
1182     ProgramStateRef StateNotFailed =
1183         State->BindExpr(E.CE, C.getLocationContext(), *NMembVal);
1184     StateNotFailed =
1185         E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1186     C.addTransition(StateNotFailed);
1187   }
1188 
1189   // Add transition for the failed state.
1190   // At write, add failure case only if "pedantic mode" is on.
1191   if (!IsFread && !PedanticMode)
1192     return;
1193 
1194   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1195   ProgramStateRef StateFailed =
1196       State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1197   StateFailed = E.assumeBinOpNN(StateFailed, BO_LT, RetVal, *NMembVal);
1198   if (!StateFailed)
1199     return;
1200 
1201   StreamErrorState NewES;
1202   if (IsFread)
1203     NewES = E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
1204   else
1205     NewES = ErrorFError;
1206   // If a (non-EOF) error occurs, the resulting value of the file position
1207   // indicator for the stream is indeterminate.
1208   StateFailed = E.setStreamState(
1209       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1210   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1211 }
1212 
1213 void StreamChecker::evalFgetx(const FnDescription *Desc, const CallEvent &Call,
1214                               CheckerContext &C, bool SingleChar) const {
1215   // `fgetc` returns the read character on success, otherwise returns EOF.
1216   // `fgets` returns the read buffer address on success, otherwise returns NULL.
1217 
1218   ProgramStateRef State = C.getState();
1219   StreamOperationEvaluator E(C);
1220   if (!E.Init(Desc, Call, C, State))
1221     return;
1222 
1223   if (!E.isStreamEof()) {
1224     // If there was already EOF, assume that read buffer is not changed.
1225     // Otherwise it may change at success or failure.
1226     State = escapeArgs(State, C, Call, {0});
1227     if (SingleChar) {
1228       // Generate a transition for the success state of `fgetc`.
1229       NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1230       ProgramStateRef StateNotFailed =
1231           State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1232       // The returned 'unsigned char' of `fgetc` is converted to 'int',
1233       // so we need to check if it is in range [0, 255].
1234       StateNotFailed = StateNotFailed->assumeInclusiveRange(
1235           RetVal,
1236           E.SVB.getBasicValueFactory().getValue(0, E.ACtx.UnsignedCharTy),
1237           E.SVB.getBasicValueFactory().getMaxValue(E.ACtx.UnsignedCharTy),
1238           true);
1239       if (!StateNotFailed)
1240         return;
1241       C.addTransition(StateNotFailed);
1242     } else {
1243       // Generate a transition for the success state of `fgets`.
1244       std::optional<DefinedSVal> GetBuf =
1245           Call.getArgSVal(0).getAs<DefinedSVal>();
1246       if (!GetBuf)
1247         return;
1248       ProgramStateRef StateNotFailed =
1249           State->BindExpr(E.CE, C.getLocationContext(), *GetBuf);
1250       StateNotFailed =
1251           E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1252       C.addTransition(StateNotFailed);
1253     }
1254   }
1255 
1256   // Add transition for the failed state.
1257   ProgramStateRef StateFailed;
1258   if (SingleChar)
1259     StateFailed = E.bindReturnValue(State, C, *EofVal);
1260   else
1261     StateFailed = E.bindNullReturnValue(State, C);
1262 
1263   // If a (non-EOF) error occurs, the resulting value of the file position
1264   // indicator for the stream is indeterminate.
1265   StreamErrorState NewES =
1266       E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
1267   StateFailed = E.setStreamState(
1268       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1269   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1270 }
1271 
1272 void StreamChecker::evalFputx(const FnDescription *Desc, const CallEvent &Call,
1273                               CheckerContext &C, bool IsSingleChar) const {
1274   // `fputc` returns the written character on success, otherwise returns EOF.
1275   // `fputs` returns a nonnegative value on success, otherwise returns EOF.
1276 
1277   ProgramStateRef State = C.getState();
1278   StreamOperationEvaluator E(C);
1279   if (!E.Init(Desc, Call, C, State))
1280     return;
1281 
1282   if (IsSingleChar) {
1283     // Generate a transition for the success state of `fputc`.
1284     std::optional<NonLoc> PutVal = Call.getArgSVal(0).getAs<NonLoc>();
1285     if (!PutVal)
1286       return;
1287     ProgramStateRef StateNotFailed =
1288         State->BindExpr(E.CE, C.getLocationContext(), *PutVal);
1289     StateNotFailed =
1290         E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1291     C.addTransition(StateNotFailed);
1292   } else {
1293     // Generate a transition for the success state of `fputs`.
1294     NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1295     ProgramStateRef StateNotFailed =
1296         State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1297     StateNotFailed =
1298         E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
1299     if (!StateNotFailed)
1300       return;
1301     StateNotFailed =
1302         E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1303     C.addTransition(StateNotFailed);
1304   }
1305 
1306   if (!PedanticMode)
1307     return;
1308 
1309   // Add transition for the failed state. The resulting value of the file
1310   // position indicator for the stream is indeterminate.
1311   ProgramStateRef StateFailed = E.bindReturnValue(State, C, *EofVal);
1312   StateFailed = E.setStreamState(
1313       StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
1314   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1315 }
1316 
1317 void StreamChecker::evalFprintf(const FnDescription *Desc,
1318                                 const CallEvent &Call,
1319                                 CheckerContext &C) const {
1320   if (Call.getNumArgs() < 2)
1321     return;
1322 
1323   ProgramStateRef State = C.getState();
1324   StreamOperationEvaluator E(C);
1325   if (!E.Init(Desc, Call, C, State))
1326     return;
1327 
1328   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1329   State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1330   auto Cond =
1331       E.SVB
1332           .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
1333                      E.SVB.getConditionType())
1334           .getAs<DefinedOrUnknownSVal>();
1335   if (!Cond)
1336     return;
1337   ProgramStateRef StateNotFailed, StateFailed;
1338   std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
1339 
1340   StateNotFailed =
1341       E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1342   C.addTransition(StateNotFailed);
1343 
1344   if (!PedanticMode)
1345     return;
1346 
1347   // Add transition for the failed state. The resulting value of the file
1348   // position indicator for the stream is indeterminate.
1349   StateFailed = E.setStreamState(
1350       StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
1351   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1352 }
1353 
1354 void StreamChecker::evalFscanf(const FnDescription *Desc, const CallEvent &Call,
1355                                CheckerContext &C) const {
1356   if (Call.getNumArgs() < 2)
1357     return;
1358 
1359   ProgramStateRef State = C.getState();
1360   StreamOperationEvaluator E(C);
1361   if (!E.Init(Desc, Call, C, State))
1362     return;
1363 
1364   // Add the success state.
1365   // In this context "success" means there is not an EOF or other read error
1366   // before any item is matched in 'fscanf'. But there may be match failure,
1367   // therefore return value can be 0 or greater.
1368   // It is not specified what happens if some items (not all) are matched and
1369   // then EOF or read error happens. Now this case is handled like a "success"
1370   // case, and no error flags are set on the stream. This is probably not
1371   // accurate, and the POSIX documentation does not tell more.
1372   if (!E.isStreamEof()) {
1373     NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1374     ProgramStateRef StateNotFailed =
1375         State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1376     StateNotFailed =
1377         E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
1378     if (!StateNotFailed)
1379       return;
1380 
1381     if (auto const *Callee = Call.getCalleeIdentifier();
1382         !Callee || Callee->getName() != "vfscanf") {
1383       SmallVector<unsigned int> EscArgs;
1384       for (auto EscArg : llvm::seq(2u, Call.getNumArgs()))
1385         EscArgs.push_back(EscArg);
1386       StateNotFailed = escapeArgs(StateNotFailed, C, Call, EscArgs);
1387     }
1388 
1389     if (StateNotFailed)
1390       C.addTransition(StateNotFailed);
1391   }
1392 
1393   // Add transition for the failed state.
1394   // Error occurs if nothing is matched yet and reading the input fails.
1395   // Error can be EOF, or other error. At "other error" FERROR or 'errno' can
1396   // be set but it is not further specified if all are required to be set.
1397   // Documentation does not mention, but file position will be set to
1398   // indeterminate similarly as at 'fread'.
1399   ProgramStateRef StateFailed = E.bindReturnValue(State, C, *EofVal);
1400   StreamErrorState NewES =
1401       E.isStreamEof() ? ErrorFEof : ErrorNone | ErrorFEof | ErrorFError;
1402   StateFailed = E.setStreamState(
1403       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1404   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1405 }
1406 
1407 void StreamChecker::evalUngetc(const FnDescription *Desc, const CallEvent &Call,
1408                                CheckerContext &C) const {
1409   ProgramStateRef State = C.getState();
1410   StreamOperationEvaluator E(C);
1411   if (!E.Init(Desc, Call, C, State))
1412     return;
1413 
1414   // Generate a transition for the success state.
1415   std::optional<NonLoc> PutVal = Call.getArgSVal(0).getAs<NonLoc>();
1416   if (!PutVal)
1417     return;
1418   ProgramStateRef StateNotFailed = E.bindReturnValue(State, C, *PutVal);
1419   StateNotFailed =
1420       E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1421   C.addTransition(StateNotFailed);
1422 
1423   // Add transition for the failed state.
1424   // Failure of 'ungetc' does not result in feof or ferror state.
1425   // If the PutVal has value of EofVal the function should "fail", but this is
1426   // the same transition as the success state.
1427   // In this case only one state transition is added by the analyzer (the two
1428   // new states may be similar).
1429   ProgramStateRef StateFailed = E.bindReturnValue(State, C, *EofVal);
1430   StateFailed = E.setStreamState(StateFailed, StreamState::getOpened(Desc));
1431   C.addTransition(StateFailed);
1432 }
1433 
1434 void StreamChecker::evalGetdelim(const FnDescription *Desc,
1435                                  const CallEvent &Call,
1436                                  CheckerContext &C) const {
1437   ProgramStateRef State = C.getState();
1438   StreamOperationEvaluator E(C);
1439   if (!E.Init(Desc, Call, C, State))
1440     return;
1441 
1442   // Upon successful completion, the getline() and getdelim() functions shall
1443   // return the number of bytes written into the buffer.
1444   // If the end-of-file indicator for the stream is set, the function shall
1445   // return -1.
1446   // If an error occurs, the function shall return -1 and set 'errno'.
1447 
1448   if (!E.isStreamEof()) {
1449     // Escape buffer and size (may change by the call).
1450     // May happen even at error (partial read?).
1451     State = escapeArgs(State, C, Call, {0, 1});
1452 
1453     // Add transition for the successful state.
1454     NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1455     ProgramStateRef StateNotFailed = E.bindReturnValue(State, C, RetVal);
1456     StateNotFailed =
1457         E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
1458 
1459     // On success, a buffer is allocated.
1460     auto NewLinePtr = getPointeeVal(Call.getArgSVal(0), State);
1461     if (NewLinePtr && isa<DefinedOrUnknownSVal>(*NewLinePtr))
1462       StateNotFailed = StateNotFailed->assume(
1463           NewLinePtr->castAs<DefinedOrUnknownSVal>(), true);
1464 
1465     // The buffer size `*n` must be enough to hold the whole line, and
1466     // greater than the return value, since it has to account for '\0'.
1467     SVal SizePtrSval = Call.getArgSVal(1);
1468     auto NVal = getPointeeVal(SizePtrSval, State);
1469     if (NVal && isa<NonLoc>(*NVal)) {
1470       StateNotFailed = E.assumeBinOpNN(StateNotFailed, BO_GT,
1471                                        NVal->castAs<NonLoc>(), RetVal);
1472       StateNotFailed = E.bindReturnValue(StateNotFailed, C, RetVal);
1473     }
1474     if (!StateNotFailed)
1475       return;
1476     C.addTransition(StateNotFailed);
1477   }
1478 
1479   // Add transition for the failed state.
1480   // If a (non-EOF) error occurs, the resulting value of the file position
1481   // indicator for the stream is indeterminate.
1482   ProgramStateRef StateFailed = E.bindReturnValue(State, C, -1);
1483   StreamErrorState NewES =
1484       E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
1485   StateFailed = E.setStreamState(
1486       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1487   // On failure, the content of the buffer is undefined.
1488   if (auto NewLinePtr = getPointeeVal(Call.getArgSVal(0), State))
1489     StateFailed = StateFailed->bindLoc(*NewLinePtr, UndefinedVal(),
1490                                        C.getLocationContext());
1491   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1492 }
1493 
1494 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
1495                              CheckerContext &C) const {
1496   ProgramStateRef State = C.getState();
1497   SVal StreamVal = getStreamArg(Desc, Call);
1498   State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
1499                               State);
1500   if (!State)
1501     return;
1502   State = ensureStreamOpened(StreamVal, C, State);
1503   if (!State)
1504     return;
1505   State = ensureFseekWhenceCorrect(Call.getArgSVal(2), C, State);
1506   if (!State)
1507     return;
1508 
1509   C.addTransition(State);
1510 }
1511 
1512 void StreamChecker::evalFseek(const FnDescription *Desc, const CallEvent &Call,
1513                               CheckerContext &C) const {
1514   ProgramStateRef State = C.getState();
1515   StreamOperationEvaluator E(C);
1516   if (!E.Init(Desc, Call, C, State))
1517     return;
1518 
1519   // Add success state.
1520   ProgramStateRef StateNotFailed = E.bindReturnValue(State, C, 0);
1521   // No failure: Reset the state to opened with no error.
1522   StateNotFailed =
1523       E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1524   C.addTransition(StateNotFailed);
1525 
1526   if (!PedanticMode)
1527     return;
1528 
1529   // Add failure state.
1530   // At error it is possible that fseek fails but sets none of the error flags.
1531   // If fseek failed, assume that the file position becomes indeterminate in any
1532   // case.
1533   // It is allowed to set the position beyond the end of the file. EOF error
1534   // should not occur.
1535   ProgramStateRef StateFailed = E.bindReturnValue(State, C, -1);
1536   StateFailed = E.setStreamState(
1537       StateFailed, StreamState::getOpened(Desc, ErrorNone | ErrorFError, true));
1538   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1539 }
1540 
1541 void StreamChecker::evalFgetpos(const FnDescription *Desc,
1542                                 const CallEvent &Call,
1543                                 CheckerContext &C) const {
1544   ProgramStateRef State = C.getState();
1545   StreamOperationEvaluator E(C);
1546   if (!E.Init(Desc, Call, C, State))
1547     return;
1548 
1549   ProgramStateRef StateNotFailed, StateFailed;
1550   std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State, C);
1551   StateNotFailed = escapeArgs(StateNotFailed, C, Call, {1});
1552 
1553   // This function does not affect the stream state.
1554   // Still we add success and failure state with the appropriate return value.
1555   // StdLibraryFunctionsChecker can change these states (set the 'errno' state).
1556   C.addTransition(StateNotFailed);
1557   C.addTransition(StateFailed);
1558 }
1559 
1560 void StreamChecker::evalFsetpos(const FnDescription *Desc,
1561                                 const CallEvent &Call,
1562                                 CheckerContext &C) const {
1563   ProgramStateRef State = C.getState();
1564   StreamOperationEvaluator E(C);
1565   if (!E.Init(Desc, Call, C, State))
1566     return;
1567 
1568   ProgramStateRef StateNotFailed, StateFailed;
1569   std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State, C);
1570 
1571   StateNotFailed = E.setStreamState(
1572       StateNotFailed, StreamState::getOpened(Desc, ErrorNone, false));
1573   C.addTransition(StateNotFailed);
1574 
1575   if (!PedanticMode)
1576     return;
1577 
1578   // At failure ferror could be set.
1579   // The standards do not tell what happens with the file position at failure.
1580   // But we can assume that it is dangerous to make a next I/O operation after
1581   // the position was not set correctly (similar to 'fseek').
1582   StateFailed = E.setStreamState(
1583       StateFailed, StreamState::getOpened(Desc, ErrorNone | ErrorFError, true));
1584 
1585   C.addTransition(StateFailed, E.getFailureNoteTag(this, C));
1586 }
1587 
1588 void StreamChecker::evalFtell(const FnDescription *Desc, const CallEvent &Call,
1589                               CheckerContext &C) const {
1590   ProgramStateRef State = C.getState();
1591   StreamOperationEvaluator E(C);
1592   if (!E.Init(Desc, Call, C, State))
1593     return;
1594 
1595   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1596   ProgramStateRef StateNotFailed =
1597       State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1598   StateNotFailed =
1599       E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
1600   if (!StateNotFailed)
1601     return;
1602 
1603   ProgramStateRef StateFailed = E.bindReturnValue(State, C, -1);
1604 
1605   // This function does not affect the stream state.
1606   // Still we add success and failure state with the appropriate return value.
1607   // StdLibraryFunctionsChecker can change these states (set the 'errno' state).
1608   C.addTransition(StateNotFailed);
1609   C.addTransition(StateFailed);
1610 }
1611 
1612 void StreamChecker::evalRewind(const FnDescription *Desc, const CallEvent &Call,
1613                                CheckerContext &C) const {
1614   ProgramStateRef State = C.getState();
1615   StreamOperationEvaluator E(C);
1616   if (!E.Init(Desc, Call, C, State))
1617     return;
1618 
1619   State =
1620       E.setStreamState(State, StreamState::getOpened(Desc, ErrorNone, false));
1621   C.addTransition(State);
1622 }
1623 
1624 void StreamChecker::preFflush(const FnDescription *Desc, const CallEvent &Call,
1625                               CheckerContext &C) const {
1626   ProgramStateRef State = C.getState();
1627   SVal StreamVal = getStreamArg(Desc, Call);
1628   std::optional<DefinedSVal> Stream = StreamVal.getAs<DefinedSVal>();
1629   if (!Stream)
1630     return;
1631 
1632   ProgramStateRef StateNotNull, StateNull;
1633   std::tie(StateNotNull, StateNull) =
1634       C.getConstraintManager().assumeDual(State, *Stream);
1635   if (StateNotNull && !StateNull)
1636     ensureStreamOpened(StreamVal, C, StateNotNull);
1637 }
1638 
1639 void StreamChecker::evalFflush(const FnDescription *Desc, const CallEvent &Call,
1640                                CheckerContext &C) const {
1641   ProgramStateRef State = C.getState();
1642   SVal StreamVal = getStreamArg(Desc, Call);
1643   std::optional<DefinedSVal> Stream = StreamVal.getAs<DefinedSVal>();
1644   if (!Stream)
1645     return;
1646 
1647   // Skip if the stream can be both NULL and non-NULL.
1648   ProgramStateRef StateNotNull, StateNull;
1649   std::tie(StateNotNull, StateNull) =
1650       C.getConstraintManager().assumeDual(State, *Stream);
1651   if (StateNotNull && StateNull)
1652     return;
1653   if (StateNotNull && !StateNull)
1654     State = StateNotNull;
1655   else
1656     State = StateNull;
1657 
1658   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1659   if (!CE)
1660     return;
1661 
1662   // `fflush` returns EOF on failure, otherwise returns 0.
1663   ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
1664   ProgramStateRef StateNotFailed = bindInt(0, State, C, CE);
1665 
1666   // Clear error states if `fflush` returns 0, but retain their EOF flags.
1667   auto ClearErrorInNotFailed = [&StateNotFailed, Desc](SymbolRef Sym,
1668                                                        const StreamState *SS) {
1669     if (SS->ErrorState & ErrorFError) {
1670       StreamErrorState NewES =
1671           (SS->ErrorState & ErrorFEof) ? ErrorFEof : ErrorNone;
1672       StreamState NewSS = StreamState::getOpened(Desc, NewES, false);
1673       StateNotFailed = StateNotFailed->set<StreamMap>(Sym, NewSS);
1674     }
1675   };
1676 
1677   if (StateNotNull && !StateNull) {
1678     // Skip if the input stream's state is unknown, open-failed or closed.
1679     if (SymbolRef StreamSym = StreamVal.getAsSymbol()) {
1680       const StreamState *SS = State->get<StreamMap>(StreamSym);
1681       if (SS) {
1682         assert(SS->isOpened() && "Stream is expected to be opened");
1683         ClearErrorInNotFailed(StreamSym, SS);
1684       } else
1685         return;
1686     }
1687   } else {
1688     // Clear error states for all streams.
1689     const StreamMapTy &Map = StateNotFailed->get<StreamMap>();
1690     for (const auto &I : Map) {
1691       SymbolRef Sym = I.first;
1692       const StreamState &SS = I.second;
1693       if (SS.isOpened())
1694         ClearErrorInNotFailed(Sym, &SS);
1695     }
1696   }
1697 
1698   C.addTransition(StateNotFailed);
1699   C.addTransition(StateFailed);
1700 }
1701 
1702 void StreamChecker::evalClearerr(const FnDescription *Desc,
1703                                  const CallEvent &Call,
1704                                  CheckerContext &C) const {
1705   ProgramStateRef State = C.getState();
1706   StreamOperationEvaluator E(C);
1707   if (!E.Init(Desc, Call, C, State))
1708     return;
1709 
1710   // FilePositionIndeterminate is not cleared.
1711   State = E.setStreamState(
1712       State,
1713       StreamState::getOpened(Desc, ErrorNone, E.SS->FilePositionIndeterminate));
1714   C.addTransition(State);
1715 }
1716 
1717 void StreamChecker::evalFeofFerror(const FnDescription *Desc,
1718                                    const CallEvent &Call, CheckerContext &C,
1719                                    const StreamErrorState &ErrorKind) const {
1720   ProgramStateRef State = C.getState();
1721   StreamOperationEvaluator E(C);
1722   if (!E.Init(Desc, Call, C, State))
1723     return;
1724 
1725   if (E.SS->ErrorState & ErrorKind) {
1726     // Execution path with error of ErrorKind.
1727     // Function returns true.
1728     // From now on it is the only one error state.
1729     ProgramStateRef TrueState = bindAndAssumeTrue(State, C, E.CE);
1730     C.addTransition(E.setStreamState(
1731         TrueState, StreamState::getOpened(Desc, ErrorKind,
1732                                           E.SS->FilePositionIndeterminate &&
1733                                               !ErrorKind.isFEof())));
1734   }
1735   if (StreamErrorState NewES = E.SS->ErrorState & (~ErrorKind)) {
1736     // Execution path(s) with ErrorKind not set.
1737     // Function returns false.
1738     // New error state is everything before minus ErrorKind.
1739     ProgramStateRef FalseState = E.bindReturnValue(State, C, 0);
1740     C.addTransition(E.setStreamState(
1741         FalseState,
1742         StreamState::getOpened(
1743             Desc, NewES, E.SS->FilePositionIndeterminate && !NewES.isFEof())));
1744   }
1745 }
1746 
1747 void StreamChecker::evalFileno(const FnDescription *Desc, const CallEvent &Call,
1748                                CheckerContext &C) const {
1749   // Fileno should fail only if the passed pointer is invalid.
1750   // Some of the preconditions are checked already in preDefault.
1751   // Here we can assume that the operation does not fail, because if we
1752   // introduced a separate branch where fileno() returns -1, then it would cause
1753   // many unexpected and unwanted warnings in situations where fileno() is
1754   // called on valid streams.
1755   // The stream error states are not modified by 'fileno', and 'errno' is also
1756   // left unchanged (so this evalCall does not invalidate it, but we have a
1757   // custom evalCall instead of the default that would invalidate it).
1758   ProgramStateRef State = C.getState();
1759   StreamOperationEvaluator E(C);
1760   if (!E.Init(Desc, Call, C, State))
1761     return;
1762 
1763   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1764   State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1765   State = E.assumeBinOpNN(State, BO_GE, RetVal, E.getZeroVal(Call));
1766   if (!State)
1767     return;
1768 
1769   C.addTransition(State);
1770 }
1771 
1772 void StreamChecker::preDefault(const FnDescription *Desc, const CallEvent &Call,
1773                                CheckerContext &C) const {
1774   ProgramStateRef State = C.getState();
1775   SVal StreamVal = getStreamArg(Desc, Call);
1776   State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
1777                               State);
1778   if (!State)
1779     return;
1780   State = ensureStreamOpened(StreamVal, C, State);
1781   if (!State)
1782     return;
1783 
1784   C.addTransition(State);
1785 }
1786 
1787 void StreamChecker::evalSetFeofFerror(const FnDescription *Desc,
1788                                       const CallEvent &Call, CheckerContext &C,
1789                                       const StreamErrorState &ErrorKind,
1790                                       bool Indeterminate) const {
1791   ProgramStateRef State = C.getState();
1792   SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
1793   assert(StreamSym && "Operation not permitted on non-symbolic stream value.");
1794   const StreamState *SS = State->get<StreamMap>(StreamSym);
1795   assert(SS && "Stream should be tracked by the checker.");
1796   State = State->set<StreamMap>(
1797       StreamSym,
1798       StreamState::getOpened(SS->LastOperation, ErrorKind, Indeterminate));
1799   C.addTransition(State);
1800 }
1801 
1802 ProgramStateRef
1803 StreamChecker::ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
1804                                    CheckerContext &C,
1805                                    ProgramStateRef State) const {
1806   auto Stream = StreamVal.getAs<DefinedSVal>();
1807   if (!Stream)
1808     return State;
1809 
1810   ConstraintManager &CM = C.getConstraintManager();
1811 
1812   ProgramStateRef StateNotNull, StateNull;
1813   std::tie(StateNotNull, StateNull) = CM.assumeDual(State, *Stream);
1814 
1815   if (!StateNotNull && StateNull) {
1816     if (ExplodedNode *N = C.generateErrorNode(StateNull)) {
1817       auto R = std::make_unique<PathSensitiveBugReport>(
1818           BT_FileNull, "Stream pointer might be NULL.", N);
1819       if (StreamE)
1820         bugreporter::trackExpressionValue(N, StreamE, *R);
1821       C.emitReport(std::move(R));
1822     }
1823     return nullptr;
1824   }
1825 
1826   return StateNotNull;
1827 }
1828 
1829 ProgramStateRef StreamChecker::ensureStreamOpened(SVal StreamVal,
1830                                                   CheckerContext &C,
1831                                                   ProgramStateRef State) const {
1832   SymbolRef Sym = StreamVal.getAsSymbol();
1833   if (!Sym)
1834     return State;
1835 
1836   const StreamState *SS = State->get<StreamMap>(Sym);
1837   if (!SS)
1838     return State;
1839 
1840   if (SS->isClosed()) {
1841     // Using a stream pointer after 'fclose' causes undefined behavior
1842     // according to cppreference.com .
1843     ExplodedNode *N = C.generateErrorNode();
1844     if (N) {
1845       C.emitReport(std::make_unique<PathSensitiveBugReport>(
1846           BT_UseAfterClose,
1847           "Stream might be already closed. Causes undefined behaviour.", N));
1848       return nullptr;
1849     }
1850 
1851     return State;
1852   }
1853 
1854   if (SS->isOpenFailed()) {
1855     // Using a stream that has failed to open is likely to cause problems.
1856     // This should usually not occur because stream pointer is NULL.
1857     // But freopen can cause a state when stream pointer remains non-null but
1858     // failed to open.
1859     ExplodedNode *N = C.generateErrorNode();
1860     if (N) {
1861       C.emitReport(std::make_unique<PathSensitiveBugReport>(
1862           BT_UseAfterOpenFailed,
1863           "Stream might be invalid after "
1864           "(re-)opening it has failed. "
1865           "Can cause undefined behaviour.",
1866           N));
1867       return nullptr;
1868     }
1869   }
1870 
1871   return State;
1872 }
1873 
1874 ProgramStateRef StreamChecker::ensureNoFilePositionIndeterminate(
1875     SVal StreamVal, CheckerContext &C, ProgramStateRef State) const {
1876   static const char *BugMessage =
1877       "File position of the stream might be 'indeterminate' "
1878       "after a failed operation. "
1879       "Can cause undefined behavior.";
1880 
1881   SymbolRef Sym = StreamVal.getAsSymbol();
1882   if (!Sym)
1883     return State;
1884 
1885   const StreamState *SS = State->get<StreamMap>(Sym);
1886   if (!SS)
1887     return State;
1888 
1889   assert(SS->isOpened() && "First ensure that stream is opened.");
1890 
1891   if (SS->FilePositionIndeterminate) {
1892     if (SS->ErrorState & ErrorFEof) {
1893       // The error is unknown but may be FEOF.
1894       // Continue analysis with the FEOF error state.
1895       // Report warning because the other possible error states.
1896       ExplodedNode *N = C.generateNonFatalErrorNode(State);
1897       if (!N)
1898         return nullptr;
1899 
1900       auto R = std::make_unique<PathSensitiveBugReport>(
1901           BT_IndeterminatePosition, BugMessage, N);
1902       R->markInteresting(Sym);
1903       C.emitReport(std::move(R));
1904       return State->set<StreamMap>(
1905           Sym, StreamState::getOpened(SS->LastOperation, ErrorFEof, false));
1906     }
1907 
1908     // Known or unknown error state without FEOF possible.
1909     // Stop analysis, report error.
1910     if (ExplodedNode *N = C.generateErrorNode(State)) {
1911       auto R = std::make_unique<PathSensitiveBugReport>(
1912           BT_IndeterminatePosition, BugMessage, N);
1913       R->markInteresting(Sym);
1914       C.emitReport(std::move(R));
1915     }
1916 
1917     return nullptr;
1918   }
1919 
1920   return State;
1921 }
1922 
1923 ProgramStateRef
1924 StreamChecker::ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
1925                                         ProgramStateRef State) const {
1926   std::optional<nonloc::ConcreteInt> CI =
1927       WhenceVal.getAs<nonloc::ConcreteInt>();
1928   if (!CI)
1929     return State;
1930 
1931   int64_t X = CI->getValue().getSExtValue();
1932   if (X == SeekSetVal || X == SeekCurVal || X == SeekEndVal)
1933     return State;
1934 
1935   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
1936     C.emitReport(std::make_unique<PathSensitiveBugReport>(
1937         BT_IllegalWhence,
1938         "The whence argument to fseek() should be "
1939         "SEEK_SET, SEEK_END, or SEEK_CUR.",
1940         N));
1941     return nullptr;
1942   }
1943 
1944   return State;
1945 }
1946 
1947 void StreamChecker::reportFEofWarning(SymbolRef StreamSym, CheckerContext &C,
1948                                       ProgramStateRef State) const {
1949   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
1950     auto R = std::make_unique<PathSensitiveBugReport>(
1951         BT_StreamEof,
1952         "Read function called when stream is in EOF state. "
1953         "Function has no effect.",
1954         N);
1955     R->markInteresting(StreamSym);
1956     C.emitReport(std::move(R));
1957     return;
1958   }
1959   C.addTransition(State);
1960 }
1961 
1962 ExplodedNode *
1963 StreamChecker::reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
1964                            CheckerContext &C, ExplodedNode *Pred) const {
1965   ExplodedNode *Err = C.generateNonFatalErrorNode(C.getState(), Pred);
1966   if (!Err)
1967     return Pred;
1968 
1969   for (SymbolRef LeakSym : LeakedSyms) {
1970     // Resource leaks can result in multiple warning that describe the same kind
1971     // of programming error:
1972     //  void f() {
1973     //    FILE *F = fopen("a.txt");
1974     //    if (rand()) // state split
1975     //      return; // warning
1976     //  } // warning
1977     // While this isn't necessarily true (leaking the same stream could result
1978     // from a different kinds of errors), the reduction in redundant reports
1979     // makes this a worthwhile heuristic.
1980     // FIXME: Add a checker option to turn this uniqueing feature off.
1981     const ExplodedNode *StreamOpenNode = getAcquisitionSite(Err, LeakSym, C);
1982     assert(StreamOpenNode && "Could not find place of stream opening.");
1983 
1984     PathDiagnosticLocation LocUsedForUniqueing;
1985     if (const Stmt *StreamStmt = StreamOpenNode->getStmtForDiagnostics())
1986       LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
1987           StreamStmt, C.getSourceManager(),
1988           StreamOpenNode->getLocationContext());
1989 
1990     std::unique_ptr<PathSensitiveBugReport> R =
1991         std::make_unique<PathSensitiveBugReport>(
1992             BT_ResourceLeak,
1993             "Opened stream never closed. Potential resource leak.", Err,
1994             LocUsedForUniqueing,
1995             StreamOpenNode->getLocationContext()->getDecl());
1996     R->markInteresting(LeakSym);
1997     R->addVisitor<NoStreamStateChangeVisitor>(LeakSym, this);
1998     C.emitReport(std::move(R));
1999   }
2000 
2001   return Err;
2002 }
2003 
2004 void StreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2005                                      CheckerContext &C) const {
2006   ProgramStateRef State = C.getState();
2007 
2008   llvm::SmallVector<SymbolRef, 2> LeakedSyms;
2009 
2010   const StreamMapTy &Map = State->get<StreamMap>();
2011   for (const auto &I : Map) {
2012     SymbolRef Sym = I.first;
2013     const StreamState &SS = I.second;
2014     if (!SymReaper.isDead(Sym))
2015       continue;
2016     if (SS.isOpened())
2017       LeakedSyms.push_back(Sym);
2018     State = State->remove<StreamMap>(Sym);
2019   }
2020 
2021   ExplodedNode *N = C.getPredecessor();
2022   if (!LeakedSyms.empty())
2023     N = reportLeaks(LeakedSyms, C, N);
2024 
2025   C.addTransition(State, N);
2026 }
2027 
2028 ProgramStateRef StreamChecker::checkPointerEscape(
2029     ProgramStateRef State, const InvalidatedSymbols &Escaped,
2030     const CallEvent *Call, PointerEscapeKind Kind) const {
2031   // Check for file-handling system call that is not handled by the checker.
2032   // FIXME: The checker should be updated to handle all system calls that take
2033   // 'FILE*' argument. These are now ignored.
2034   if (Kind == PSK_DirectEscapeOnCall && Call->isInSystemHeader())
2035     return State;
2036 
2037   for (SymbolRef Sym : Escaped) {
2038     // The symbol escaped.
2039     // From now the stream can be manipulated in unknown way to the checker,
2040     // it is not possible to handle it any more.
2041     // Optimistically, assume that the corresponding file handle will be closed
2042     // somewhere else.
2043     // Remove symbol from state so the following stream calls on this symbol are
2044     // not handled by the checker.
2045     State = State->remove<StreamMap>(Sym);
2046   }
2047   return State;
2048 }
2049 
2050 static const VarDecl *
2051 getGlobalStreamPointerByName(const TranslationUnitDecl *TU, StringRef VarName) {
2052   ASTContext &Ctx = TU->getASTContext();
2053   const auto &SM = Ctx.getSourceManager();
2054   const QualType FileTy = Ctx.getFILEType();
2055 
2056   if (FileTy.isNull())
2057     return nullptr;
2058 
2059   const QualType FilePtrTy = Ctx.getPointerType(FileTy).getCanonicalType();
2060 
2061   auto LookupRes = TU->lookup(&Ctx.Idents.get(VarName));
2062   for (const Decl *D : LookupRes) {
2063     if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2064       if (SM.isInSystemHeader(VD->getLocation()) && VD->hasExternalStorage() &&
2065           VD->getType().getCanonicalType() == FilePtrTy) {
2066         return VD;
2067       }
2068     }
2069   }
2070   return nullptr;
2071 }
2072 
2073 void StreamChecker::checkASTDecl(const TranslationUnitDecl *TU,
2074                                  AnalysisManager &Mgr, BugReporter &) const {
2075   StdinDecl = getGlobalStreamPointerByName(TU, "stdin");
2076   StdoutDecl = getGlobalStreamPointerByName(TU, "stdout");
2077   StderrDecl = getGlobalStreamPointerByName(TU, "stderr");
2078   VaListType = TU->getASTContext().getBuiltinVaListType().getCanonicalType();
2079   initMacroValues(Mgr.getPreprocessor());
2080 }
2081 
2082 //===----------------------------------------------------------------------===//
2083 // Checker registration.
2084 //===----------------------------------------------------------------------===//
2085 
2086 void ento::registerStreamChecker(CheckerManager &Mgr) {
2087   auto *Checker = Mgr.registerChecker<StreamChecker>();
2088   Checker->PedanticMode =
2089       Mgr.getAnalyzerOptions().getCheckerBooleanOption(Checker, "Pedantic");
2090 }
2091 
2092 bool ento::shouldRegisterStreamChecker(const CheckerManager &Mgr) {
2093   return true;
2094 }
2095 
2096 void ento::registerStreamTesterChecker(CheckerManager &Mgr) {
2097   auto *Checker = Mgr.getChecker<StreamChecker>();
2098   Checker->TestMode = true;
2099 }
2100 
2101 bool ento::shouldRegisterStreamTesterChecker(const CheckerManager &Mgr) {
2102   return true;
2103 }
2104