xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (revision 5ca877591e65acf18b5a8d3234ff88b215b4f369)
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 "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
15 #include "clang/StaticAnalyzer/Core/Checker.h"
16 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
24 #include "llvm/ADT/Sequence.h"
25 #include <functional>
26 #include <optional>
27 
28 using namespace clang;
29 using namespace ento;
30 using namespace std::placeholders;
31 
32 //===----------------------------------------------------------------------===//
33 // Definition of state data structures.
34 //===----------------------------------------------------------------------===//
35 
36 namespace {
37 
38 struct FnDescription;
39 
40 /// State of the stream error flags.
41 /// Sometimes it is not known to the checker what error flags are set.
42 /// This is indicated by setting more than one flag to true.
43 /// This is an optimization to avoid state splits.
44 /// A stream can either be in FEOF or FERROR but not both at the same time.
45 /// Multiple flags are set to handle the corresponding states together.
46 struct StreamErrorState {
47   /// The stream can be in state where none of the error flags set.
48   bool NoError = true;
49   /// The stream can be in state where the EOF indicator is set.
50   bool FEof = false;
51   /// The stream can be in state where the error indicator is set.
52   bool FError = false;
53 
54   bool isNoError() const { return NoError && !FEof && !FError; }
55   bool isFEof() const { return !NoError && FEof && !FError; }
56   bool isFError() const { return !NoError && !FEof && FError; }
57 
58   bool operator==(const StreamErrorState &ES) const {
59     return NoError == ES.NoError && FEof == ES.FEof && FError == ES.FError;
60   }
61 
62   bool operator!=(const StreamErrorState &ES) const { return !(*this == ES); }
63 
64   StreamErrorState operator|(const StreamErrorState &E) const {
65     return {NoError || E.NoError, FEof || E.FEof, FError || E.FError};
66   }
67 
68   StreamErrorState operator&(const StreamErrorState &E) const {
69     return {NoError && E.NoError, FEof && E.FEof, FError && E.FError};
70   }
71 
72   StreamErrorState operator~() const { return {!NoError, !FEof, !FError}; }
73 
74   /// Returns if the StreamErrorState is a valid object.
75   operator bool() const { return NoError || FEof || FError; }
76 
77   void Profile(llvm::FoldingSetNodeID &ID) const {
78     ID.AddBoolean(NoError);
79     ID.AddBoolean(FEof);
80     ID.AddBoolean(FError);
81   }
82 };
83 
84 const StreamErrorState ErrorNone{true, false, false};
85 const StreamErrorState ErrorFEof{false, true, false};
86 const StreamErrorState ErrorFError{false, false, true};
87 
88 /// Full state information about a stream pointer.
89 struct StreamState {
90   /// The last file operation called in the stream.
91   /// Can be nullptr.
92   const FnDescription *LastOperation;
93 
94   /// State of a stream symbol.
95   enum KindTy {
96     Opened, /// Stream is opened.
97     Closed, /// Closed stream (an invalid stream pointer after it was closed).
98     OpenFailed /// The last open operation has failed.
99   } State;
100 
101   /// State of the error flags.
102   /// Ignored in non-opened stream state but must be NoError.
103   StreamErrorState const ErrorState;
104 
105   /// Indicate if the file has an "indeterminate file position indicator".
106   /// This can be set at a failing read or write or seek operation.
107   /// If it is set no more read or write is allowed.
108   /// This value is not dependent on the stream error flags:
109   /// The error flag may be cleared with `clearerr` but the file position
110   /// remains still indeterminate.
111   /// This value applies to all error states in ErrorState except FEOF.
112   /// An EOF+indeterminate state is the same as EOF state.
113   bool const FilePositionIndeterminate = false;
114 
115   StreamState(const FnDescription *L, KindTy S, const StreamErrorState &ES,
116               bool IsFilePositionIndeterminate)
117       : LastOperation(L), State(S), ErrorState(ES),
118         FilePositionIndeterminate(IsFilePositionIndeterminate) {
119     assert((!ES.isFEof() || !IsFilePositionIndeterminate) &&
120            "FilePositionIndeterminate should be false in FEof case.");
121     assert((State == Opened || ErrorState.isNoError()) &&
122            "ErrorState should be None in non-opened stream state.");
123   }
124 
125   bool isOpened() const { return State == Opened; }
126   bool isClosed() const { return State == Closed; }
127   bool isOpenFailed() const { return State == OpenFailed; }
128 
129   bool operator==(const StreamState &X) const {
130     // In not opened state error state should always NoError, so comparison
131     // here is no problem.
132     return LastOperation == X.LastOperation && State == X.State &&
133            ErrorState == X.ErrorState &&
134            FilePositionIndeterminate == X.FilePositionIndeterminate;
135   }
136 
137   static StreamState getOpened(const FnDescription *L,
138                                const StreamErrorState &ES = ErrorNone,
139                                bool IsFilePositionIndeterminate = false) {
140     return StreamState{L, Opened, ES, IsFilePositionIndeterminate};
141   }
142   static StreamState getClosed(const FnDescription *L) {
143     return StreamState{L, Closed, {}, false};
144   }
145   static StreamState getOpenFailed(const FnDescription *L) {
146     return StreamState{L, OpenFailed, {}, false};
147   }
148 
149   void Profile(llvm::FoldingSetNodeID &ID) const {
150     ID.AddPointer(LastOperation);
151     ID.AddInteger(State);
152     ErrorState.Profile(ID);
153     ID.AddBoolean(FilePositionIndeterminate);
154   }
155 };
156 
157 } // namespace
158 
159 // This map holds the state of a stream.
160 // The stream is identified with a SymbolRef that is created when a stream
161 // opening function is modeled by the checker.
162 REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
163 
164 //===----------------------------------------------------------------------===//
165 // StreamChecker class and utility functions.
166 //===----------------------------------------------------------------------===//
167 
168 namespace {
169 
170 class StreamChecker;
171 using FnCheck = std::function<void(const StreamChecker *, const FnDescription *,
172                                    const CallEvent &, CheckerContext &)>;
173 
174 using ArgNoTy = unsigned int;
175 static const ArgNoTy ArgNone = std::numeric_limits<ArgNoTy>::max();
176 
177 struct FnDescription {
178   FnCheck PreFn;
179   FnCheck EvalFn;
180   ArgNoTy StreamArgNo;
181 };
182 
183 /// Get the value of the stream argument out of the passed call event.
184 /// The call should contain a function that is described by Desc.
185 SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
186   assert(Desc && Desc->StreamArgNo != ArgNone &&
187          "Try to get a non-existing stream argument.");
188   return Call.getArgSVal(Desc->StreamArgNo);
189 }
190 
191 /// Create a conjured symbol return value for a call expression.
192 DefinedSVal makeRetVal(CheckerContext &C, const CallExpr *CE) {
193   assert(CE && "Expecting a call expression.");
194 
195   const LocationContext *LCtx = C.getLocationContext();
196   return C.getSValBuilder()
197       .conjureSymbolVal(nullptr, CE, LCtx, C.blockCount())
198       .castAs<DefinedSVal>();
199 }
200 
201 ProgramStateRef bindAndAssumeTrue(ProgramStateRef State, CheckerContext &C,
202                                   const CallExpr *CE) {
203   DefinedSVal RetVal = makeRetVal(C, CE);
204   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
205   State = State->assume(RetVal, true);
206   assert(State && "Assumption on new value should not fail.");
207   return State;
208 }
209 
210 ProgramStateRef bindInt(uint64_t Value, ProgramStateRef State,
211                         CheckerContext &C, const CallExpr *CE) {
212   State = State->BindExpr(CE, C.getLocationContext(),
213                           C.getSValBuilder().makeIntVal(Value, CE->getType()));
214   return State;
215 }
216 
217 inline void assertStreamStateOpened(const StreamState *SS) {
218   assert(SS->isOpened() && "Stream is expected to be opened");
219 }
220 
221 struct StreamOperationEvaluator {
222   SValBuilder &SVB;
223   const ASTContext &ACtx;
224 
225   SymbolRef StreamSym;
226   const StreamState *SS = nullptr;
227   const CallExpr *CE = nullptr;
228 
229   StreamOperationEvaluator(CheckerContext &C)
230       : SVB(C.getSValBuilder()), ACtx(C.getASTContext()) {
231     ;
232   }
233 
234   bool Init(const FnDescription *Desc, const CallEvent &Call, CheckerContext &C,
235             ProgramStateRef State) {
236     StreamSym = getStreamArg(Desc, Call).getAsSymbol();
237     if (!StreamSym)
238       return false;
239     SS = State->get<StreamMap>(StreamSym);
240     if (!SS)
241       return false;
242     CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
243     if (!CE)
244       return false;
245 
246     assertStreamStateOpened(SS);
247 
248     return true;
249   }
250 
251   bool isStreamEof() const { return SS->ErrorState == ErrorFEof; }
252 
253   NonLoc getZeroVal(const CallEvent &Call) {
254     return *SVB.makeZeroVal(Call.getResultType()).getAs<NonLoc>();
255   }
256 
257   ProgramStateRef setStreamState(ProgramStateRef State,
258                                  const StreamState &NewSS) {
259     return State->set<StreamMap>(StreamSym, NewSS);
260   }
261 
262   ProgramStateRef makeAndBindRetVal(ProgramStateRef State, CheckerContext &C) {
263     NonLoc RetVal = makeRetVal(C, CE).castAs<NonLoc>();
264     return State->BindExpr(CE, C.getLocationContext(), RetVal);
265   }
266 
267   ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
268                                   uint64_t Val) {
269     return State->BindExpr(CE, C.getLocationContext(),
270                            SVB.makeIntVal(Val, CE->getCallReturnType(ACtx)));
271   }
272 
273   ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
274                                   SVal Val) {
275     return State->BindExpr(CE, C.getLocationContext(), Val);
276   }
277 
278   ProgramStateRef bindNullReturnValue(ProgramStateRef State,
279                                       CheckerContext &C) {
280     return State->BindExpr(CE, C.getLocationContext(),
281                            C.getSValBuilder().makeNullWithType(CE->getType()));
282   }
283 
284   ProgramStateRef assumeBinOpNN(ProgramStateRef State,
285                                 BinaryOperator::Opcode Op, NonLoc LHS,
286                                 NonLoc RHS) {
287     auto Cond = SVB.evalBinOpNN(State, Op, LHS, RHS, SVB.getConditionType())
288                     .getAs<DefinedOrUnknownSVal>();
289     if (!Cond)
290       return nullptr;
291     return State->assume(*Cond, true);
292   }
293 
294   ConstraintManager::ProgramStatePair
295   makeRetValAndAssumeDual(ProgramStateRef State, CheckerContext &C) {
296     DefinedSVal RetVal = makeRetVal(C, CE);
297     State = State->BindExpr(CE, C.getLocationContext(), RetVal);
298     return C.getConstraintManager().assumeDual(State, RetVal);
299   }
300 };
301 
302 class StreamChecker : public Checker<check::PreCall, eval::Call,
303                                      check::DeadSymbols, check::PointerEscape> {
304   BugType BT_FileNull{this, "NULL stream pointer", "Stream handling error"};
305   BugType BT_UseAfterClose{this, "Closed stream", "Stream handling error"};
306   BugType BT_UseAfterOpenFailed{this, "Invalid stream",
307                                 "Stream handling error"};
308   BugType BT_IndeterminatePosition{this, "Invalid stream state",
309                                    "Stream handling error"};
310   BugType BT_IllegalWhence{this, "Illegal whence argument",
311                            "Stream handling error"};
312   BugType BT_StreamEof{this, "Stream already in EOF", "Stream handling error"};
313   BugType BT_ResourceLeak{this, "Resource leak", "Stream handling error",
314                           /*SuppressOnSink =*/true};
315 
316 public:
317   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
318   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
319   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
320   ProgramStateRef checkPointerEscape(ProgramStateRef State,
321                                      const InvalidatedSymbols &Escaped,
322                                      const CallEvent *Call,
323                                      PointerEscapeKind Kind) const;
324 
325   /// If true, evaluate special testing stream functions.
326   bool TestMode = false;
327 
328   const BugType *getBT_StreamEof() const { return &BT_StreamEof; }
329 
330 private:
331   CallDescriptionMap<FnDescription> FnDescriptions = {
332       {{{"fopen"}, 2}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
333       {{{"fdopen"}, 2}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
334       {{{"freopen"}, 3},
335        {&StreamChecker::preFreopen, &StreamChecker::evalFreopen, 2}},
336       {{{"tmpfile"}, 0}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
337       {{{"fclose"}, 1},
338        {&StreamChecker::preDefault, &StreamChecker::evalFclose, 0}},
339       {{{"fread"}, 4},
340        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, true),
341         std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, true), 3}},
342       {{{"fwrite"}, 4},
343        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, false),
344         std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, false), 3}},
345       {{{"fgetc"}, 1},
346        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, true),
347         std::bind(&StreamChecker::evalFgetx, _1, _2, _3, _4, true), 0}},
348       {{{"fgets"}, 3},
349        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, true),
350         std::bind(&StreamChecker::evalFgetx, _1, _2, _3, _4, false), 2}},
351       {{{"fputc"}, 2},
352        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, false),
353         std::bind(&StreamChecker::evalFputx, _1, _2, _3, _4, true), 1}},
354       {{{"fputs"}, 2},
355        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, false),
356         std::bind(&StreamChecker::evalFputx, _1, _2, _3, _4, false), 1}},
357       {{{"fprintf"}},
358        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, false),
359         std::bind(&StreamChecker::evalFprintf, _1, _2, _3, _4), 0}},
360       {{{"fscanf"}},
361        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, true),
362         std::bind(&StreamChecker::evalFscanf, _1, _2, _3, _4), 0}},
363       {{{"ungetc"}, 2},
364        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, false),
365         std::bind(&StreamChecker::evalUngetc, _1, _2, _3, _4), 1}},
366       {{{"getdelim"}, 4},
367        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, true),
368         std::bind(&StreamChecker::evalGetdelim, _1, _2, _3, _4), 3}},
369       {{{"getline"}, 3},
370        {std::bind(&StreamChecker::preReadWrite, _1, _2, _3, _4, true),
371         std::bind(&StreamChecker::evalGetdelim, _1, _2, _3, _4), 2}},
372       {{{"fseek"}, 3},
373        {&StreamChecker::preFseek, &StreamChecker::evalFseek, 0}},
374       {{{"fseeko"}, 3},
375        {&StreamChecker::preFseek, &StreamChecker::evalFseek, 0}},
376       {{{"ftell"}, 1},
377        {&StreamChecker::preDefault, &StreamChecker::evalFtell, 0}},
378       {{{"ftello"}, 1},
379        {&StreamChecker::preDefault, &StreamChecker::evalFtell, 0}},
380       {{{"fflush"}, 1},
381        {&StreamChecker::preFflush, &StreamChecker::evalFflush, 0}},
382       {{{"rewind"}, 1},
383        {&StreamChecker::preDefault, &StreamChecker::evalRewind, 0}},
384       {{{"fgetpos"}, 2},
385        {&StreamChecker::preDefault, &StreamChecker::evalFgetpos, 0}},
386       {{{"fsetpos"}, 2},
387        {&StreamChecker::preDefault, &StreamChecker::evalFsetpos, 0}},
388       {{{"clearerr"}, 1},
389        {&StreamChecker::preDefault, &StreamChecker::evalClearerr, 0}},
390       {{{"feof"}, 1},
391        {&StreamChecker::preDefault,
392         std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFEof),
393         0}},
394       {{{"ferror"}, 1},
395        {&StreamChecker::preDefault,
396         std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFError),
397         0}},
398       {{{"fileno"}, 1},
399        {&StreamChecker::preDefault, &StreamChecker::evalFileno, 0}},
400   };
401 
402   CallDescriptionMap<FnDescription> FnTestDescriptions = {
403       {{{"StreamTesterChecker_make_feof_stream"}, 1},
404        {nullptr,
405         std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4, ErrorFEof),
406         0}},
407       {{{"StreamTesterChecker_make_ferror_stream"}, 1},
408        {nullptr,
409         std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4,
410                   ErrorFError),
411         0}},
412   };
413 
414   /// Expanded value of EOF, empty before initialization.
415   mutable std::optional<int> EofVal;
416   /// Expanded value of SEEK_SET, 0 if not found.
417   mutable int SeekSetVal = 0;
418   /// Expanded value of SEEK_CUR, 1 if not found.
419   mutable int SeekCurVal = 1;
420   /// Expanded value of SEEK_END, 2 if not found.
421   mutable int SeekEndVal = 2;
422 
423   void evalFopen(const FnDescription *Desc, const CallEvent &Call,
424                  CheckerContext &C) const;
425 
426   void preFreopen(const FnDescription *Desc, const CallEvent &Call,
427                   CheckerContext &C) const;
428   void evalFreopen(const FnDescription *Desc, const CallEvent &Call,
429                    CheckerContext &C) const;
430 
431   void evalFclose(const FnDescription *Desc, const CallEvent &Call,
432                   CheckerContext &C) const;
433 
434   void preReadWrite(const FnDescription *Desc, const CallEvent &Call,
435                     CheckerContext &C, bool IsRead) const;
436 
437   void evalFreadFwrite(const FnDescription *Desc, const CallEvent &Call,
438                        CheckerContext &C, bool IsFread) const;
439 
440   void evalFgetx(const FnDescription *Desc, const CallEvent &Call,
441                  CheckerContext &C, bool SingleChar) const;
442 
443   void evalFputx(const FnDescription *Desc, const CallEvent &Call,
444                  CheckerContext &C, bool IsSingleChar) const;
445 
446   void evalFprintf(const FnDescription *Desc, const CallEvent &Call,
447                    CheckerContext &C) const;
448 
449   void evalFscanf(const FnDescription *Desc, const CallEvent &Call,
450                   CheckerContext &C) const;
451 
452   void evalUngetc(const FnDescription *Desc, const CallEvent &Call,
453                   CheckerContext &C) const;
454 
455   void evalGetdelim(const FnDescription *Desc, const CallEvent &Call,
456                     CheckerContext &C) const;
457 
458   void preFseek(const FnDescription *Desc, const CallEvent &Call,
459                 CheckerContext &C) const;
460   void evalFseek(const FnDescription *Desc, const CallEvent &Call,
461                  CheckerContext &C) const;
462 
463   void evalFgetpos(const FnDescription *Desc, const CallEvent &Call,
464                    CheckerContext &C) const;
465 
466   void evalFsetpos(const FnDescription *Desc, const CallEvent &Call,
467                    CheckerContext &C) const;
468 
469   void evalFtell(const FnDescription *Desc, const CallEvent &Call,
470                  CheckerContext &C) const;
471 
472   void evalRewind(const FnDescription *Desc, const CallEvent &Call,
473                   CheckerContext &C) const;
474 
475   void preDefault(const FnDescription *Desc, const CallEvent &Call,
476                   CheckerContext &C) const;
477 
478   void evalClearerr(const FnDescription *Desc, const CallEvent &Call,
479                     CheckerContext &C) const;
480 
481   void evalFeofFerror(const FnDescription *Desc, const CallEvent &Call,
482                       CheckerContext &C,
483                       const StreamErrorState &ErrorKind) const;
484 
485   void evalSetFeofFerror(const FnDescription *Desc, const CallEvent &Call,
486                          CheckerContext &C,
487                          const StreamErrorState &ErrorKind) const;
488 
489   void preFflush(const FnDescription *Desc, const CallEvent &Call,
490                  CheckerContext &C) const;
491 
492   void evalFflush(const FnDescription *Desc, const CallEvent &Call,
493                   CheckerContext &C) const;
494 
495   void evalFileno(const FnDescription *Desc, const CallEvent &Call,
496                   CheckerContext &C) const;
497 
498   /// Check that the stream (in StreamVal) is not NULL.
499   /// If it can only be NULL a fatal error is emitted and nullptr returned.
500   /// Otherwise the return value is a new state where the stream is constrained
501   /// to be non-null.
502   ProgramStateRef ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
503                                       CheckerContext &C,
504                                       ProgramStateRef State) const;
505 
506   /// Check that the stream is the opened state.
507   /// If the stream is known to be not opened an error is generated
508   /// and nullptr returned, otherwise the original state is returned.
509   ProgramStateRef ensureStreamOpened(SVal StreamVal, CheckerContext &C,
510                                      ProgramStateRef State) const;
511 
512   /// Check that the stream has not an invalid ("indeterminate") file position,
513   /// generate warning for it.
514   /// (EOF is not an invalid position.)
515   /// The returned state can be nullptr if a fatal error was generated.
516   /// It can return non-null state if the stream has not an invalid position or
517   /// there is execution path with non-invalid position.
518   ProgramStateRef
519   ensureNoFilePositionIndeterminate(SVal StreamVal, CheckerContext &C,
520                                     ProgramStateRef State) const;
521 
522   /// Check the legality of the 'whence' argument of 'fseek'.
523   /// Generate error and return nullptr if it is found to be illegal.
524   /// Otherwise returns the state.
525   /// (State is not changed here because the "whence" value is already known.)
526   ProgramStateRef ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
527                                            ProgramStateRef State) const;
528 
529   /// Generate warning about stream in EOF state.
530   /// There will be always a state transition into the passed State,
531   /// by the new non-fatal error node or (if failed) a normal transition,
532   /// to ensure uniform handling.
533   void reportFEofWarning(SymbolRef StreamSym, CheckerContext &C,
534                          ProgramStateRef State) const;
535 
536   /// Emit resource leak warnings for the given symbols.
537   /// Createn a non-fatal error node for these, and returns it (if any warnings
538   /// were generated). Return value is non-null.
539   ExplodedNode *reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
540                             CheckerContext &C, ExplodedNode *Pred) const;
541 
542   /// Find the description data of the function called by a call event.
543   /// Returns nullptr if no function is recognized.
544   const FnDescription *lookupFn(const CallEvent &Call) const {
545     // Recognize "global C functions" with only integral or pointer arguments
546     // (and matching name) as stream functions.
547     if (!Call.isGlobalCFunction())
548       return nullptr;
549     for (auto *P : Call.parameters()) {
550       QualType T = P->getType();
551       if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
552         return nullptr;
553     }
554 
555     return FnDescriptions.lookup(Call);
556   }
557 
558   /// Generate a message for BugReporterVisitor if the stored symbol is
559   /// marked as interesting by the actual bug report.
560   const NoteTag *constructNoteTag(CheckerContext &C, SymbolRef StreamSym,
561                                   const std::string &Message) const {
562     return C.getNoteTag([this, StreamSym,
563                          Message](PathSensitiveBugReport &BR) -> std::string {
564       if (BR.isInteresting(StreamSym) && &BR.getBugType() == &BT_ResourceLeak)
565         return Message;
566       return "";
567     });
568   }
569 
570   const NoteTag *constructSetEofNoteTag(CheckerContext &C,
571                                         SymbolRef StreamSym) const {
572     return C.getNoteTag([this, StreamSym](PathSensitiveBugReport &BR) {
573       if (!BR.isInteresting(StreamSym) ||
574           &BR.getBugType() != this->getBT_StreamEof())
575         return "";
576 
577       BR.markNotInteresting(StreamSym);
578 
579       return "Assuming stream reaches end-of-file here";
580     });
581   }
582 
583   void initMacroValues(CheckerContext &C) const {
584     if (EofVal)
585       return;
586 
587     if (const std::optional<int> OptInt =
588             tryExpandAsInteger("EOF", C.getPreprocessor()))
589       EofVal = *OptInt;
590     else
591       EofVal = -1;
592     if (const std::optional<int> OptInt =
593             tryExpandAsInteger("SEEK_SET", C.getPreprocessor()))
594       SeekSetVal = *OptInt;
595     if (const std::optional<int> OptInt =
596             tryExpandAsInteger("SEEK_END", C.getPreprocessor()))
597       SeekEndVal = *OptInt;
598     if (const std::optional<int> OptInt =
599             tryExpandAsInteger("SEEK_CUR", C.getPreprocessor()))
600       SeekCurVal = *OptInt;
601   }
602 
603   /// Searches for the ExplodedNode where the file descriptor was acquired for
604   /// StreamSym.
605   static const ExplodedNode *getAcquisitionSite(const ExplodedNode *N,
606                                                 SymbolRef StreamSym,
607                                                 CheckerContext &C);
608 };
609 
610 } // end anonymous namespace
611 
612 const ExplodedNode *StreamChecker::getAcquisitionSite(const ExplodedNode *N,
613                                                       SymbolRef StreamSym,
614                                                       CheckerContext &C) {
615   ProgramStateRef State = N->getState();
616   // When bug type is resource leak, exploded node N may not have state info
617   // for leaked file descriptor, but predecessor should have it.
618   if (!State->get<StreamMap>(StreamSym))
619     N = N->getFirstPred();
620 
621   const ExplodedNode *Pred = N;
622   while (N) {
623     State = N->getState();
624     if (!State->get<StreamMap>(StreamSym))
625       return Pred;
626     Pred = N;
627     N = N->getFirstPred();
628   }
629 
630   return nullptr;
631 }
632 
633 static ProgramStateRef escapeArgs(ProgramStateRef State, CheckerContext &C,
634                                   const CallEvent &Call,
635                                   ArrayRef<unsigned int> EscapingArgs) {
636   const auto *CE = Call.getOriginExpr();
637 
638   SmallVector<SVal> EscapingVals;
639   EscapingVals.reserve(EscapingArgs.size());
640   for (auto EscArgIdx : EscapingArgs)
641     EscapingVals.push_back(Call.getArgSVal(EscArgIdx));
642   State = State->invalidateRegions(EscapingVals, CE, C.blockCount(),
643                                    C.getLocationContext(),
644                                    /*CausesPointerEscape=*/false);
645   return State;
646 }
647 
648 //===----------------------------------------------------------------------===//
649 // Methods of StreamChecker.
650 //===----------------------------------------------------------------------===//
651 
652 void StreamChecker::checkPreCall(const CallEvent &Call,
653                                  CheckerContext &C) const {
654   initMacroValues(C);
655 
656   const FnDescription *Desc = lookupFn(Call);
657   if (!Desc || !Desc->PreFn)
658     return;
659 
660   Desc->PreFn(this, Desc, Call, C);
661 }
662 
663 bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
664   const FnDescription *Desc = lookupFn(Call);
665   if (!Desc && TestMode)
666     Desc = FnTestDescriptions.lookup(Call);
667   if (!Desc || !Desc->EvalFn)
668     return false;
669 
670   Desc->EvalFn(this, Desc, Call, C);
671 
672   return C.isDifferent();
673 }
674 
675 void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call,
676                               CheckerContext &C) const {
677   ProgramStateRef State = C.getState();
678   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
679   if (!CE)
680     return;
681 
682   DefinedSVal RetVal = makeRetVal(C, CE);
683   SymbolRef RetSym = RetVal.getAsSymbol();
684   assert(RetSym && "RetVal must be a symbol here.");
685 
686   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
687 
688   // Bifurcate the state into two: one with a valid FILE* pointer, the other
689   // with a NULL.
690   ProgramStateRef StateNotNull, StateNull;
691   std::tie(StateNotNull, StateNull) =
692       C.getConstraintManager().assumeDual(State, RetVal);
693 
694   StateNotNull =
695       StateNotNull->set<StreamMap>(RetSym, StreamState::getOpened(Desc));
696   StateNull =
697       StateNull->set<StreamMap>(RetSym, StreamState::getOpenFailed(Desc));
698 
699   C.addTransition(StateNotNull,
700                   constructNoteTag(C, RetSym, "Stream opened here"));
701   C.addTransition(StateNull);
702 }
703 
704 void StreamChecker::preFreopen(const FnDescription *Desc, const CallEvent &Call,
705                                CheckerContext &C) const {
706   // Do not allow NULL as passed stream pointer but allow a closed stream.
707   ProgramStateRef State = C.getState();
708   State = ensureStreamNonNull(getStreamArg(Desc, Call),
709                               Call.getArgExpr(Desc->StreamArgNo), C, State);
710   if (!State)
711     return;
712 
713   C.addTransition(State);
714 }
715 
716 void StreamChecker::evalFreopen(const FnDescription *Desc,
717                                 const CallEvent &Call,
718                                 CheckerContext &C) const {
719   ProgramStateRef State = C.getState();
720 
721   auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
722   if (!CE)
723     return;
724 
725   std::optional<DefinedSVal> StreamVal =
726       getStreamArg(Desc, Call).getAs<DefinedSVal>();
727   if (!StreamVal)
728     return;
729 
730   SymbolRef StreamSym = StreamVal->getAsSymbol();
731   // Do not care about concrete values for stream ("(FILE *)0x12345"?).
732   // FIXME: Can be stdin, stdout, stderr such values?
733   if (!StreamSym)
734     return;
735 
736   // Do not handle untracked stream. It is probably escaped.
737   if (!State->get<StreamMap>(StreamSym))
738     return;
739 
740   // Generate state for non-failed case.
741   // Return value is the passed stream pointer.
742   // According to the documentations, the stream is closed first
743   // but any close error is ignored. The state changes to (or remains) opened.
744   ProgramStateRef StateRetNotNull =
745       State->BindExpr(CE, C.getLocationContext(), *StreamVal);
746   // Generate state for NULL return value.
747   // Stream switches to OpenFailed state.
748   ProgramStateRef StateRetNull =
749       State->BindExpr(CE, C.getLocationContext(),
750                       C.getSValBuilder().makeNullWithType(CE->getType()));
751 
752   StateRetNotNull =
753       StateRetNotNull->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
754   StateRetNull =
755       StateRetNull->set<StreamMap>(StreamSym, StreamState::getOpenFailed(Desc));
756 
757   C.addTransition(StateRetNotNull,
758                   constructNoteTag(C, StreamSym, "Stream reopened here"));
759   C.addTransition(StateRetNull);
760 }
761 
762 void StreamChecker::evalFclose(const FnDescription *Desc, const CallEvent &Call,
763                                CheckerContext &C) const {
764   ProgramStateRef State = C.getState();
765   StreamOperationEvaluator E(C);
766   if (!E.Init(Desc, Call, C, State))
767     return;
768 
769   // Close the File Descriptor.
770   // Regardless if the close fails or not, stream becomes "closed"
771   // and can not be used any more.
772   State = E.setStreamState(State, StreamState::getClosed(Desc));
773 
774   // Return 0 on success, EOF on failure.
775   C.addTransition(E.bindReturnValue(State, C, 0));
776   C.addTransition(E.bindReturnValue(State, C, *EofVal));
777 }
778 
779 void StreamChecker::preReadWrite(const FnDescription *Desc,
780                                  const CallEvent &Call, CheckerContext &C,
781                                  bool IsRead) const {
782   ProgramStateRef State = C.getState();
783   SVal StreamVal = getStreamArg(Desc, Call);
784   State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
785                               State);
786   if (!State)
787     return;
788   State = ensureStreamOpened(StreamVal, C, State);
789   if (!State)
790     return;
791   State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
792   if (!State)
793     return;
794 
795   if (!IsRead) {
796     C.addTransition(State);
797     return;
798   }
799 
800   SymbolRef Sym = StreamVal.getAsSymbol();
801   if (Sym && State->get<StreamMap>(Sym)) {
802     const StreamState *SS = State->get<StreamMap>(Sym);
803     if (SS->ErrorState & ErrorFEof)
804       reportFEofWarning(Sym, C, State);
805   } else {
806     C.addTransition(State);
807   }
808 }
809 
810 void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
811                                     const CallEvent &Call, CheckerContext &C,
812                                     bool IsFread) const {
813   ProgramStateRef State = C.getState();
814   StreamOperationEvaluator E(C);
815   if (!E.Init(Desc, Call, C, State))
816     return;
817 
818   std::optional<NonLoc> SizeVal = Call.getArgSVal(1).getAs<NonLoc>();
819   if (!SizeVal)
820     return;
821   std::optional<NonLoc> NMembVal = Call.getArgSVal(2).getAs<NonLoc>();
822   if (!NMembVal)
823     return;
824 
825   // C'99 standard, §7.19.8.1.3, the return value of fread:
826   // The fread function returns the number of elements successfully read, which
827   // may be less than nmemb if a read error or end-of-file is encountered. If
828   // size or nmemb is zero, fread returns zero and the contents of the array and
829   // the state of the stream remain unchanged.
830   if (State->isNull(*SizeVal).isConstrainedTrue() ||
831       State->isNull(*NMembVal).isConstrainedTrue()) {
832     // This is the "size or nmemb is zero" case.
833     // Just return 0, do nothing more (not clear the error flags).
834     C.addTransition(E.bindReturnValue(State, C, 0));
835     return;
836   }
837 
838   // At read, invalidate the buffer in any case of error or success,
839   // except if EOF was already present.
840   if (IsFread && !E.isStreamEof())
841     State = escapeArgs(State, C, Call, {0});
842 
843   // Generate a transition for the success state.
844   // If we know the state to be FEOF at fread, do not add a success state.
845   if (!IsFread || !E.isStreamEof()) {
846     ProgramStateRef StateNotFailed =
847         State->BindExpr(E.CE, C.getLocationContext(), *NMembVal);
848     StateNotFailed =
849         E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
850     C.addTransition(StateNotFailed);
851   }
852 
853   // Add transition for the failed state.
854   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
855   ProgramStateRef StateFailed =
856       State->BindExpr(E.CE, C.getLocationContext(), RetVal);
857   StateFailed = E.assumeBinOpNN(StateFailed, BO_LT, RetVal, *NMembVal);
858   if (!StateFailed)
859     return;
860 
861   StreamErrorState NewES;
862   if (IsFread)
863     NewES = E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
864   else
865     NewES = ErrorFError;
866   // If a (non-EOF) error occurs, the resulting value of the file position
867   // indicator for the stream is indeterminate.
868   StateFailed = E.setStreamState(
869       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
870   if (IsFread && !E.isStreamEof())
871     C.addTransition(StateFailed, constructSetEofNoteTag(C, E.StreamSym));
872   else
873     C.addTransition(StateFailed);
874 }
875 
876 void StreamChecker::evalFgetx(const FnDescription *Desc, const CallEvent &Call,
877                               CheckerContext &C, bool SingleChar) const {
878   // `fgetc` returns the read character on success, otherwise returns EOF.
879   // `fgets` returns the read buffer address on success, otherwise returns NULL.
880 
881   ProgramStateRef State = C.getState();
882   StreamOperationEvaluator E(C);
883   if (!E.Init(Desc, Call, C, State))
884     return;
885 
886   if (!E.isStreamEof()) {
887     // If there was already EOF, assume that read buffer is not changed.
888     // Otherwise it may change at success or failure.
889     State = escapeArgs(State, C, Call, {0});
890     if (SingleChar) {
891       // Generate a transition for the success state of `fgetc`.
892       NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
893       ProgramStateRef StateNotFailed =
894           State->BindExpr(E.CE, C.getLocationContext(), RetVal);
895       // The returned 'unsigned char' of `fgetc` is converted to 'int',
896       // so we need to check if it is in range [0, 255].
897       StateNotFailed = StateNotFailed->assumeInclusiveRange(
898           RetVal,
899           E.SVB.getBasicValueFactory().getValue(0, E.ACtx.UnsignedCharTy),
900           E.SVB.getBasicValueFactory().getMaxValue(E.ACtx.UnsignedCharTy),
901           true);
902       if (!StateNotFailed)
903         return;
904       C.addTransition(StateNotFailed);
905     } else {
906       // Generate a transition for the success state of `fgets`.
907       std::optional<DefinedSVal> GetBuf =
908           Call.getArgSVal(0).getAs<DefinedSVal>();
909       if (!GetBuf)
910         return;
911       ProgramStateRef StateNotFailed =
912           State->BindExpr(E.CE, C.getLocationContext(), *GetBuf);
913       StateNotFailed =
914           E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
915       C.addTransition(StateNotFailed);
916     }
917   }
918 
919   // Add transition for the failed state.
920   ProgramStateRef StateFailed;
921   if (SingleChar)
922     StateFailed = E.bindReturnValue(State, C, *EofVal);
923   else
924     StateFailed = E.bindNullReturnValue(State, C);
925 
926   // If a (non-EOF) error occurs, the resulting value of the file position
927   // indicator for the stream is indeterminate.
928   StreamErrorState NewES =
929       E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
930   StateFailed = E.setStreamState(
931       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
932   if (!E.isStreamEof())
933     C.addTransition(StateFailed, constructSetEofNoteTag(C, E.StreamSym));
934   else
935     C.addTransition(StateFailed);
936 }
937 
938 void StreamChecker::evalFputx(const FnDescription *Desc, const CallEvent &Call,
939                               CheckerContext &C, bool IsSingleChar) const {
940   // `fputc` returns the written character on success, otherwise returns EOF.
941   // `fputs` returns a nonnegative value on success, otherwise returns EOF.
942 
943   ProgramStateRef State = C.getState();
944   StreamOperationEvaluator E(C);
945   if (!E.Init(Desc, Call, C, State))
946     return;
947 
948   if (IsSingleChar) {
949     // Generate a transition for the success state of `fputc`.
950     std::optional<NonLoc> PutVal = Call.getArgSVal(0).getAs<NonLoc>();
951     if (!PutVal)
952       return;
953     ProgramStateRef StateNotFailed =
954         State->BindExpr(E.CE, C.getLocationContext(), *PutVal);
955     StateNotFailed =
956         E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
957     C.addTransition(StateNotFailed);
958   } else {
959     // Generate a transition for the success state of `fputs`.
960     NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
961     ProgramStateRef StateNotFailed =
962         State->BindExpr(E.CE, C.getLocationContext(), RetVal);
963     StateNotFailed =
964         E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
965     if (!StateNotFailed)
966       return;
967     StateNotFailed =
968         E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
969     C.addTransition(StateNotFailed);
970   }
971 
972   // Add transition for the failed state. The resulting value of the file
973   // position indicator for the stream is indeterminate.
974   ProgramStateRef StateFailed = E.bindReturnValue(State, C, *EofVal);
975   StateFailed = E.setStreamState(
976       StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
977   C.addTransition(StateFailed);
978 }
979 
980 void StreamChecker::evalFprintf(const FnDescription *Desc,
981                                 const CallEvent &Call,
982                                 CheckerContext &C) const {
983   if (Call.getNumArgs() < 2)
984     return;
985 
986   ProgramStateRef State = C.getState();
987   StreamOperationEvaluator E(C);
988   if (!E.Init(Desc, Call, C, State))
989     return;
990 
991   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
992   State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
993   auto Cond =
994       E.SVB
995           .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
996                      E.SVB.getConditionType())
997           .getAs<DefinedOrUnknownSVal>();
998   if (!Cond)
999     return;
1000   ProgramStateRef StateNotFailed, StateFailed;
1001   std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
1002 
1003   StateNotFailed =
1004       E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1005   C.addTransition(StateNotFailed);
1006 
1007   // Add transition for the failed state. The resulting value of the file
1008   // position indicator for the stream is indeterminate.
1009   StateFailed = E.setStreamState(
1010       StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
1011   C.addTransition(StateFailed);
1012 }
1013 
1014 void StreamChecker::evalFscanf(const FnDescription *Desc, const CallEvent &Call,
1015                                CheckerContext &C) const {
1016   if (Call.getNumArgs() < 2)
1017     return;
1018 
1019   ProgramStateRef State = C.getState();
1020   StreamOperationEvaluator E(C);
1021   if (!E.Init(Desc, Call, C, State))
1022     return;
1023 
1024   // Add the success state.
1025   // In this context "success" means there is not an EOF or other read error
1026   // before any item is matched in 'fscanf'. But there may be match failure,
1027   // therefore return value can be 0 or greater.
1028   // It is not specified what happens if some items (not all) are matched and
1029   // then EOF or read error happens. Now this case is handled like a "success"
1030   // case, and no error flags are set on the stream. This is probably not
1031   // accurate, and the POSIX documentation does not tell more.
1032   if (!E.isStreamEof()) {
1033     NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1034     ProgramStateRef StateNotFailed =
1035         State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1036     StateNotFailed =
1037         E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
1038     if (!StateNotFailed)
1039       return;
1040 
1041     SmallVector<unsigned int> EscArgs;
1042     for (auto EscArg : llvm::seq(2u, Call.getNumArgs()))
1043       EscArgs.push_back(EscArg);
1044     StateNotFailed = escapeArgs(StateNotFailed, C, Call, EscArgs);
1045 
1046     if (StateNotFailed)
1047       C.addTransition(StateNotFailed);
1048   }
1049 
1050   // Add transition for the failed state.
1051   // Error occurs if nothing is matched yet and reading the input fails.
1052   // Error can be EOF, or other error. At "other error" FERROR or 'errno' can
1053   // be set but it is not further specified if all are required to be set.
1054   // Documentation does not mention, but file position will be set to
1055   // indeterminate similarly as at 'fread'.
1056   ProgramStateRef StateFailed = E.bindReturnValue(State, C, *EofVal);
1057   StreamErrorState NewES =
1058       E.isStreamEof() ? ErrorFEof : ErrorNone | ErrorFEof | ErrorFError;
1059   StateFailed = E.setStreamState(
1060       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1061   if (!E.isStreamEof())
1062     C.addTransition(StateFailed, constructSetEofNoteTag(C, E.StreamSym));
1063   else
1064     C.addTransition(StateFailed);
1065 }
1066 
1067 void StreamChecker::evalUngetc(const FnDescription *Desc, const CallEvent &Call,
1068                                CheckerContext &C) const {
1069   ProgramStateRef State = C.getState();
1070   StreamOperationEvaluator E(C);
1071   if (!E.Init(Desc, Call, C, State))
1072     return;
1073 
1074   // Generate a transition for the success state.
1075   std::optional<NonLoc> PutVal = Call.getArgSVal(0).getAs<NonLoc>();
1076   if (!PutVal)
1077     return;
1078   ProgramStateRef StateNotFailed = E.bindReturnValue(State, C, *PutVal);
1079   StateNotFailed =
1080       E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1081   C.addTransition(StateNotFailed);
1082 
1083   // Add transition for the failed state.
1084   // Failure of 'ungetc' does not result in feof or ferror state.
1085   // If the PutVal has value of EofVal the function should "fail", but this is
1086   // the same transition as the success state.
1087   // In this case only one state transition is added by the analyzer (the two
1088   // new states may be similar).
1089   ProgramStateRef StateFailed = E.bindReturnValue(State, C, *EofVal);
1090   StateFailed = E.setStreamState(StateFailed, StreamState::getOpened(Desc));
1091   C.addTransition(StateFailed);
1092 }
1093 
1094 void StreamChecker::evalGetdelim(const FnDescription *Desc,
1095                                  const CallEvent &Call,
1096                                  CheckerContext &C) const {
1097   ProgramStateRef State = C.getState();
1098   StreamOperationEvaluator E(C);
1099   if (!E.Init(Desc, Call, C, State))
1100     return;
1101 
1102   // Upon successful completion, the getline() and getdelim() functions shall
1103   // return the number of bytes written into the buffer.
1104   // If the end-of-file indicator for the stream is set, the function shall
1105   // return -1.
1106   // If an error occurs, the function shall return -1 and set 'errno'.
1107 
1108   if (!E.isStreamEof()) {
1109     // Escape buffer and size (may change by the call).
1110     // May happen even at error (partial read?).
1111     State = escapeArgs(State, C, Call, {0, 1});
1112 
1113     // Add transition for the successful state.
1114     NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1115     ProgramStateRef StateNotFailed =
1116         State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1117     StateNotFailed =
1118         E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
1119     if (!StateNotFailed)
1120       return;
1121     C.addTransition(StateNotFailed);
1122   }
1123 
1124   // Add transition for the failed state.
1125   // If a (non-EOF) error occurs, the resulting value of the file position
1126   // indicator for the stream is indeterminate.
1127   ProgramStateRef StateFailed = E.bindReturnValue(State, C, -1);
1128   StreamErrorState NewES =
1129       E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
1130   StateFailed = E.setStreamState(
1131       StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1132   if (E.isStreamEof())
1133     C.addTransition(StateFailed, constructSetEofNoteTag(C, E.StreamSym));
1134   else
1135     C.addTransition(StateFailed);
1136 }
1137 
1138 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
1139                              CheckerContext &C) const {
1140   ProgramStateRef State = C.getState();
1141   SVal StreamVal = getStreamArg(Desc, Call);
1142   State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
1143                               State);
1144   if (!State)
1145     return;
1146   State = ensureStreamOpened(StreamVal, C, State);
1147   if (!State)
1148     return;
1149   State = ensureFseekWhenceCorrect(Call.getArgSVal(2), C, State);
1150   if (!State)
1151     return;
1152 
1153   C.addTransition(State);
1154 }
1155 
1156 void StreamChecker::evalFseek(const FnDescription *Desc, const CallEvent &Call,
1157                               CheckerContext &C) const {
1158   ProgramStateRef State = C.getState();
1159   StreamOperationEvaluator E(C);
1160   if (!E.Init(Desc, Call, C, State))
1161     return;
1162 
1163   const llvm::APSInt *PosV =
1164       C.getSValBuilder().getKnownValue(State, Call.getArgSVal(1));
1165   const llvm::APSInt *WhenceV =
1166       C.getSValBuilder().getKnownValue(State, Call.getArgSVal(2));
1167 
1168   // Bifurcate the state into failed and non-failed.
1169   // Return zero on success, nonzero on error.
1170   ProgramStateRef StateNotFailed, StateFailed;
1171   std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State, C);
1172 
1173   // No failure: Reset the state to opened with no error.
1174   StateNotFailed =
1175       E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1176   C.addTransition(StateNotFailed);
1177 
1178   // At error it is possible that fseek fails but sets none of the error flags.
1179   // If fseek failed, assume that the file position becomes indeterminate in any
1180   // case.
1181   StreamErrorState NewErrS = ErrorNone | ErrorFError;
1182   // Setting the position to start of file never produces EOF error.
1183   if (!(PosV && *PosV == 0 && WhenceV && *WhenceV == SeekSetVal))
1184     NewErrS = NewErrS | ErrorFEof;
1185   StateFailed = E.setStreamState(StateFailed,
1186                                  StreamState::getOpened(Desc, NewErrS, true));
1187   C.addTransition(StateFailed, constructSetEofNoteTag(C, E.StreamSym));
1188 }
1189 
1190 void StreamChecker::evalFgetpos(const FnDescription *Desc,
1191                                 const CallEvent &Call,
1192                                 CheckerContext &C) const {
1193   ProgramStateRef State = C.getState();
1194   StreamOperationEvaluator E(C);
1195   if (!E.Init(Desc, Call, C, State))
1196     return;
1197 
1198   ProgramStateRef StateNotFailed, StateFailed;
1199   std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State, C);
1200   StateNotFailed = escapeArgs(StateNotFailed, C, Call, {1});
1201 
1202   // This function does not affect the stream state.
1203   // Still we add success and failure state with the appropriate return value.
1204   // StdLibraryFunctionsChecker can change these states (set the 'errno' state).
1205   C.addTransition(StateNotFailed);
1206   C.addTransition(StateFailed);
1207 }
1208 
1209 void StreamChecker::evalFsetpos(const FnDescription *Desc,
1210                                 const CallEvent &Call,
1211                                 CheckerContext &C) const {
1212   ProgramStateRef State = C.getState();
1213   StreamOperationEvaluator E(C);
1214   if (!E.Init(Desc, Call, C, State))
1215     return;
1216 
1217   ProgramStateRef StateNotFailed, StateFailed;
1218   std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State, C);
1219 
1220   StateNotFailed = E.setStreamState(
1221       StateNotFailed, StreamState::getOpened(Desc, ErrorNone, false));
1222 
1223   // At failure ferror could be set.
1224   // The standards do not tell what happens with the file position at failure.
1225   // But we can assume that it is dangerous to make a next I/O operation after
1226   // the position was not set correctly (similar to 'fseek').
1227   StateFailed = E.setStreamState(
1228       StateFailed, StreamState::getOpened(Desc, ErrorNone | ErrorFError, true));
1229 
1230   C.addTransition(StateNotFailed);
1231   C.addTransition(StateFailed);
1232 }
1233 
1234 void StreamChecker::evalFtell(const FnDescription *Desc, const CallEvent &Call,
1235                               CheckerContext &C) const {
1236   ProgramStateRef State = C.getState();
1237   StreamOperationEvaluator E(C);
1238   if (!E.Init(Desc, Call, C, State))
1239     return;
1240 
1241   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1242   ProgramStateRef StateNotFailed =
1243       State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1244   StateNotFailed =
1245       E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
1246   if (!StateNotFailed)
1247     return;
1248 
1249   ProgramStateRef StateFailed = E.bindReturnValue(State, C, -1);
1250 
1251   // This function does not affect the stream state.
1252   // Still we add success and failure state with the appropriate return value.
1253   // StdLibraryFunctionsChecker can change these states (set the 'errno' state).
1254   C.addTransition(StateNotFailed);
1255   C.addTransition(StateFailed);
1256 }
1257 
1258 void StreamChecker::evalRewind(const FnDescription *Desc, const CallEvent &Call,
1259                                CheckerContext &C) const {
1260   ProgramStateRef State = C.getState();
1261   StreamOperationEvaluator E(C);
1262   if (!E.Init(Desc, Call, C, State))
1263     return;
1264 
1265   State =
1266       E.setStreamState(State, StreamState::getOpened(Desc, ErrorNone, false));
1267   C.addTransition(State);
1268 }
1269 
1270 void StreamChecker::preFflush(const FnDescription *Desc, const CallEvent &Call,
1271                               CheckerContext &C) const {
1272   ProgramStateRef State = C.getState();
1273   SVal StreamVal = getStreamArg(Desc, Call);
1274   std::optional<DefinedSVal> Stream = StreamVal.getAs<DefinedSVal>();
1275   if (!Stream)
1276     return;
1277 
1278   ProgramStateRef StateNotNull, StateNull;
1279   std::tie(StateNotNull, StateNull) =
1280       C.getConstraintManager().assumeDual(State, *Stream);
1281   if (StateNotNull && !StateNull)
1282     ensureStreamOpened(StreamVal, C, StateNotNull);
1283 }
1284 
1285 void StreamChecker::evalFflush(const FnDescription *Desc, const CallEvent &Call,
1286                                CheckerContext &C) const {
1287   ProgramStateRef State = C.getState();
1288   SVal StreamVal = getStreamArg(Desc, Call);
1289   std::optional<DefinedSVal> Stream = StreamVal.getAs<DefinedSVal>();
1290   if (!Stream)
1291     return;
1292 
1293   // Skip if the stream can be both NULL and non-NULL.
1294   ProgramStateRef StateNotNull, StateNull;
1295   std::tie(StateNotNull, StateNull) =
1296       C.getConstraintManager().assumeDual(State, *Stream);
1297   if (StateNotNull && StateNull)
1298     return;
1299   if (StateNotNull && !StateNull)
1300     State = StateNotNull;
1301   else
1302     State = StateNull;
1303 
1304   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1305   if (!CE)
1306     return;
1307 
1308   // `fflush` returns EOF on failure, otherwise returns 0.
1309   ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
1310   ProgramStateRef StateNotFailed = bindInt(0, State, C, CE);
1311 
1312   // Clear error states if `fflush` returns 0, but retain their EOF flags.
1313   auto ClearErrorInNotFailed = [&StateNotFailed, Desc](SymbolRef Sym,
1314                                                        const StreamState *SS) {
1315     if (SS->ErrorState & ErrorFError) {
1316       StreamErrorState NewES =
1317           (SS->ErrorState & ErrorFEof) ? ErrorFEof : ErrorNone;
1318       StreamState NewSS = StreamState::getOpened(Desc, NewES, false);
1319       StateNotFailed = StateNotFailed->set<StreamMap>(Sym, NewSS);
1320     }
1321   };
1322 
1323   if (StateNotNull && !StateNull) {
1324     // Skip if the input stream's state is unknown, open-failed or closed.
1325     if (SymbolRef StreamSym = StreamVal.getAsSymbol()) {
1326       const StreamState *SS = State->get<StreamMap>(StreamSym);
1327       if (SS) {
1328         assert(SS->isOpened() && "Stream is expected to be opened");
1329         ClearErrorInNotFailed(StreamSym, SS);
1330       } else
1331         return;
1332     }
1333   } else {
1334     // Clear error states for all streams.
1335     const StreamMapTy &Map = StateNotFailed->get<StreamMap>();
1336     for (const auto &I : Map) {
1337       SymbolRef Sym = I.first;
1338       const StreamState &SS = I.second;
1339       if (SS.isOpened())
1340         ClearErrorInNotFailed(Sym, &SS);
1341     }
1342   }
1343 
1344   C.addTransition(StateNotFailed);
1345   C.addTransition(StateFailed);
1346 }
1347 
1348 void StreamChecker::evalClearerr(const FnDescription *Desc,
1349                                  const CallEvent &Call,
1350                                  CheckerContext &C) const {
1351   ProgramStateRef State = C.getState();
1352   StreamOperationEvaluator E(C);
1353   if (!E.Init(Desc, Call, C, State))
1354     return;
1355 
1356   // FilePositionIndeterminate is not cleared.
1357   State = E.setStreamState(
1358       State,
1359       StreamState::getOpened(Desc, ErrorNone, E.SS->FilePositionIndeterminate));
1360   C.addTransition(State);
1361 }
1362 
1363 void StreamChecker::evalFeofFerror(const FnDescription *Desc,
1364                                    const CallEvent &Call, CheckerContext &C,
1365                                    const StreamErrorState &ErrorKind) const {
1366   ProgramStateRef State = C.getState();
1367   StreamOperationEvaluator E(C);
1368   if (!E.Init(Desc, Call, C, State))
1369     return;
1370 
1371   if (E.SS->ErrorState & ErrorKind) {
1372     // Execution path with error of ErrorKind.
1373     // Function returns true.
1374     // From now on it is the only one error state.
1375     ProgramStateRef TrueState = bindAndAssumeTrue(State, C, E.CE);
1376     C.addTransition(E.setStreamState(
1377         TrueState, StreamState::getOpened(Desc, ErrorKind,
1378                                           E.SS->FilePositionIndeterminate &&
1379                                               !ErrorKind.isFEof())));
1380   }
1381   if (StreamErrorState NewES = E.SS->ErrorState & (~ErrorKind)) {
1382     // Execution path(s) with ErrorKind not set.
1383     // Function returns false.
1384     // New error state is everything before minus ErrorKind.
1385     ProgramStateRef FalseState = E.bindReturnValue(State, C, 0);
1386     C.addTransition(E.setStreamState(
1387         FalseState,
1388         StreamState::getOpened(
1389             Desc, NewES, E.SS->FilePositionIndeterminate && !NewES.isFEof())));
1390   }
1391 }
1392 
1393 void StreamChecker::evalFileno(const FnDescription *Desc, const CallEvent &Call,
1394                                CheckerContext &C) const {
1395   // Fileno should fail only if the passed pointer is invalid.
1396   // Some of the preconditions are checked already in preDefault.
1397   // Here we can assume that the operation does not fail, because if we
1398   // introduced a separate branch where fileno() returns -1, then it would cause
1399   // many unexpected and unwanted warnings in situations where fileno() is
1400   // called on valid streams.
1401   // The stream error states are not modified by 'fileno', and 'errno' is also
1402   // left unchanged (so this evalCall does not invalidate it, but we have a
1403   // custom evalCall instead of the default that would invalidate it).
1404   ProgramStateRef State = C.getState();
1405   StreamOperationEvaluator E(C);
1406   if (!E.Init(Desc, Call, C, State))
1407     return;
1408 
1409   NonLoc RetVal = makeRetVal(C, E.CE).castAs<NonLoc>();
1410   State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
1411   State = E.assumeBinOpNN(State, BO_GE, RetVal, E.getZeroVal(Call));
1412   if (!State)
1413     return;
1414 
1415   C.addTransition(State);
1416 }
1417 
1418 void StreamChecker::preDefault(const FnDescription *Desc, const CallEvent &Call,
1419                                CheckerContext &C) const {
1420   ProgramStateRef State = C.getState();
1421   SVal StreamVal = getStreamArg(Desc, Call);
1422   State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
1423                               State);
1424   if (!State)
1425     return;
1426   State = ensureStreamOpened(StreamVal, C, State);
1427   if (!State)
1428     return;
1429 
1430   C.addTransition(State);
1431 }
1432 
1433 void StreamChecker::evalSetFeofFerror(const FnDescription *Desc,
1434                                       const CallEvent &Call, CheckerContext &C,
1435                                       const StreamErrorState &ErrorKind) const {
1436   ProgramStateRef State = C.getState();
1437   SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
1438   assert(StreamSym && "Operation not permitted on non-symbolic stream value.");
1439   const StreamState *SS = State->get<StreamMap>(StreamSym);
1440   assert(SS && "Stream should be tracked by the checker.");
1441   State = State->set<StreamMap>(
1442       StreamSym, StreamState::getOpened(SS->LastOperation, ErrorKind));
1443   C.addTransition(State);
1444 }
1445 
1446 ProgramStateRef
1447 StreamChecker::ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
1448                                    CheckerContext &C,
1449                                    ProgramStateRef State) const {
1450   auto Stream = StreamVal.getAs<DefinedSVal>();
1451   if (!Stream)
1452     return State;
1453 
1454   ConstraintManager &CM = C.getConstraintManager();
1455 
1456   ProgramStateRef StateNotNull, StateNull;
1457   std::tie(StateNotNull, StateNull) = CM.assumeDual(State, *Stream);
1458 
1459   if (!StateNotNull && StateNull) {
1460     if (ExplodedNode *N = C.generateErrorNode(StateNull)) {
1461       auto R = std::make_unique<PathSensitiveBugReport>(
1462           BT_FileNull, "Stream pointer might be NULL.", N);
1463       if (StreamE)
1464         bugreporter::trackExpressionValue(N, StreamE, *R);
1465       C.emitReport(std::move(R));
1466     }
1467     return nullptr;
1468   }
1469 
1470   return StateNotNull;
1471 }
1472 
1473 ProgramStateRef StreamChecker::ensureStreamOpened(SVal StreamVal,
1474                                                   CheckerContext &C,
1475                                                   ProgramStateRef State) const {
1476   SymbolRef Sym = StreamVal.getAsSymbol();
1477   if (!Sym)
1478     return State;
1479 
1480   const StreamState *SS = State->get<StreamMap>(Sym);
1481   if (!SS)
1482     return State;
1483 
1484   if (SS->isClosed()) {
1485     // Using a stream pointer after 'fclose' causes undefined behavior
1486     // according to cppreference.com .
1487     ExplodedNode *N = C.generateErrorNode();
1488     if (N) {
1489       C.emitReport(std::make_unique<PathSensitiveBugReport>(
1490           BT_UseAfterClose,
1491           "Stream might be already closed. Causes undefined behaviour.", N));
1492       return nullptr;
1493     }
1494 
1495     return State;
1496   }
1497 
1498   if (SS->isOpenFailed()) {
1499     // Using a stream that has failed to open is likely to cause problems.
1500     // This should usually not occur because stream pointer is NULL.
1501     // But freopen can cause a state when stream pointer remains non-null but
1502     // failed to open.
1503     ExplodedNode *N = C.generateErrorNode();
1504     if (N) {
1505       C.emitReport(std::make_unique<PathSensitiveBugReport>(
1506           BT_UseAfterOpenFailed,
1507           "Stream might be invalid after "
1508           "(re-)opening it has failed. "
1509           "Can cause undefined behaviour.",
1510           N));
1511       return nullptr;
1512     }
1513   }
1514 
1515   return State;
1516 }
1517 
1518 ProgramStateRef StreamChecker::ensureNoFilePositionIndeterminate(
1519     SVal StreamVal, CheckerContext &C, ProgramStateRef State) const {
1520   static const char *BugMessage =
1521       "File position of the stream might be 'indeterminate' "
1522       "after a failed operation. "
1523       "Can cause undefined behavior.";
1524 
1525   SymbolRef Sym = StreamVal.getAsSymbol();
1526   if (!Sym)
1527     return State;
1528 
1529   const StreamState *SS = State->get<StreamMap>(Sym);
1530   if (!SS)
1531     return State;
1532 
1533   assert(SS->isOpened() && "First ensure that stream is opened.");
1534 
1535   if (SS->FilePositionIndeterminate) {
1536     if (SS->ErrorState & ErrorFEof) {
1537       // The error is unknown but may be FEOF.
1538       // Continue analysis with the FEOF error state.
1539       // Report warning because the other possible error states.
1540       ExplodedNode *N = C.generateNonFatalErrorNode(State);
1541       if (!N)
1542         return nullptr;
1543 
1544       C.emitReport(std::make_unique<PathSensitiveBugReport>(
1545           BT_IndeterminatePosition, BugMessage, N));
1546       return State->set<StreamMap>(
1547           Sym, StreamState::getOpened(SS->LastOperation, ErrorFEof, false));
1548     }
1549 
1550     // Known or unknown error state without FEOF possible.
1551     // Stop analysis, report error.
1552     ExplodedNode *N = C.generateErrorNode(State);
1553     if (N)
1554       C.emitReport(std::make_unique<PathSensitiveBugReport>(
1555           BT_IndeterminatePosition, BugMessage, N));
1556 
1557     return nullptr;
1558   }
1559 
1560   return State;
1561 }
1562 
1563 ProgramStateRef
1564 StreamChecker::ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
1565                                         ProgramStateRef State) const {
1566   std::optional<nonloc::ConcreteInt> CI =
1567       WhenceVal.getAs<nonloc::ConcreteInt>();
1568   if (!CI)
1569     return State;
1570 
1571   int64_t X = CI->getValue().getSExtValue();
1572   if (X == SeekSetVal || X == SeekCurVal || X == SeekEndVal)
1573     return State;
1574 
1575   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
1576     C.emitReport(std::make_unique<PathSensitiveBugReport>(
1577         BT_IllegalWhence,
1578         "The whence argument to fseek() should be "
1579         "SEEK_SET, SEEK_END, or SEEK_CUR.",
1580         N));
1581     return nullptr;
1582   }
1583 
1584   return State;
1585 }
1586 
1587 void StreamChecker::reportFEofWarning(SymbolRef StreamSym, CheckerContext &C,
1588                                       ProgramStateRef State) const {
1589   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
1590     auto R = std::make_unique<PathSensitiveBugReport>(
1591         BT_StreamEof,
1592         "Read function called when stream is in EOF state. "
1593         "Function has no effect.",
1594         N);
1595     R->markInteresting(StreamSym);
1596     C.emitReport(std::move(R));
1597     return;
1598   }
1599   C.addTransition(State);
1600 }
1601 
1602 ExplodedNode *
1603 StreamChecker::reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
1604                            CheckerContext &C, ExplodedNode *Pred) const {
1605   ExplodedNode *Err = C.generateNonFatalErrorNode(C.getState(), Pred);
1606   if (!Err)
1607     return Pred;
1608 
1609   for (SymbolRef LeakSym : LeakedSyms) {
1610     // Resource leaks can result in multiple warning that describe the same kind
1611     // of programming error:
1612     //  void f() {
1613     //    FILE *F = fopen("a.txt");
1614     //    if (rand()) // state split
1615     //      return; // warning
1616     //  } // warning
1617     // While this isn't necessarily true (leaking the same stream could result
1618     // from a different kinds of errors), the reduction in redundant reports
1619     // makes this a worthwhile heuristic.
1620     // FIXME: Add a checker option to turn this uniqueing feature off.
1621     const ExplodedNode *StreamOpenNode = getAcquisitionSite(Err, LeakSym, C);
1622     assert(StreamOpenNode && "Could not find place of stream opening.");
1623 
1624     PathDiagnosticLocation LocUsedForUniqueing;
1625     if (const Stmt *StreamStmt = StreamOpenNode->getStmtForDiagnostics())
1626       LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
1627           StreamStmt, C.getSourceManager(),
1628           StreamOpenNode->getLocationContext());
1629 
1630     std::unique_ptr<PathSensitiveBugReport> R =
1631         std::make_unique<PathSensitiveBugReport>(
1632             BT_ResourceLeak,
1633             "Opened stream never closed. Potential resource leak.", Err,
1634             LocUsedForUniqueing,
1635             StreamOpenNode->getLocationContext()->getDecl());
1636     R->markInteresting(LeakSym);
1637     C.emitReport(std::move(R));
1638   }
1639 
1640   return Err;
1641 }
1642 
1643 void StreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1644                                      CheckerContext &C) const {
1645   ProgramStateRef State = C.getState();
1646 
1647   llvm::SmallVector<SymbolRef, 2> LeakedSyms;
1648 
1649   const StreamMapTy &Map = State->get<StreamMap>();
1650   for (const auto &I : Map) {
1651     SymbolRef Sym = I.first;
1652     const StreamState &SS = I.second;
1653     if (!SymReaper.isDead(Sym))
1654       continue;
1655     if (SS.isOpened())
1656       LeakedSyms.push_back(Sym);
1657     State = State->remove<StreamMap>(Sym);
1658   }
1659 
1660   ExplodedNode *N = C.getPredecessor();
1661   if (!LeakedSyms.empty())
1662     N = reportLeaks(LeakedSyms, C, N);
1663 
1664   C.addTransition(State, N);
1665 }
1666 
1667 ProgramStateRef StreamChecker::checkPointerEscape(
1668     ProgramStateRef State, const InvalidatedSymbols &Escaped,
1669     const CallEvent *Call, PointerEscapeKind Kind) const {
1670   // Check for file-handling system call that is not handled by the checker.
1671   // FIXME: The checker should be updated to handle all system calls that take
1672   // 'FILE*' argument. These are now ignored.
1673   if (Kind == PSK_DirectEscapeOnCall && Call->isInSystemHeader())
1674     return State;
1675 
1676   for (SymbolRef Sym : Escaped) {
1677     // The symbol escaped.
1678     // From now the stream can be manipulated in unknown way to the checker,
1679     // it is not possible to handle it any more.
1680     // Optimistically, assume that the corresponding file handle will be closed
1681     // somewhere else.
1682     // Remove symbol from state so the following stream calls on this symbol are
1683     // not handled by the checker.
1684     State = State->remove<StreamMap>(Sym);
1685   }
1686   return State;
1687 }
1688 
1689 //===----------------------------------------------------------------------===//
1690 // Checker registration.
1691 //===----------------------------------------------------------------------===//
1692 
1693 void ento::registerStreamChecker(CheckerManager &Mgr) {
1694   Mgr.registerChecker<StreamChecker>();
1695 }
1696 
1697 bool ento::shouldRegisterStreamChecker(const CheckerManager &Mgr) {
1698   return true;
1699 }
1700 
1701 void ento::registerStreamTesterChecker(CheckerManager &Mgr) {
1702   auto *Checker = Mgr.getChecker<StreamChecker>();
1703   Checker->TestMode = true;
1704 }
1705 
1706 bool ento::shouldRegisterStreamTesterChecker(const CheckerManager &Mgr) {
1707   return true;
1708 }
1709