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