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