27#include "llvm/ADT/Sequence.h"
33using namespace std::placeholders;
49struct StreamErrorState {
57 bool isNoError()
const {
return NoError && !FEof && !FError; }
58 bool isFEof()
const {
return !NoError && FEof && !FError; }
59 bool isFError()
const {
return !NoError && !FEof && FError; }
61 bool operator==(
const StreamErrorState &ES)
const {
62 return NoError == ES.NoError && FEof == ES.FEof && FError == ES.FError;
65 bool operator!=(
const StreamErrorState &ES)
const {
return !(*
this == ES); }
67 StreamErrorState
operator|(
const StreamErrorState &E)
const {
68 return {NoError || E.NoError, FEof || E.FEof, FError || E.FError};
71 StreamErrorState
operator&(
const StreamErrorState &E)
const {
72 return {NoError && E.NoError, FEof && E.FEof, FError && E.FError};
75 StreamErrorState
operator~()
const {
return {!NoError, !FEof, !FError}; }
78 operator bool()
const {
return NoError || FEof || FError; }
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;
86 void Profile(llvm::FoldingSetNodeID &ID)
const {
87 ID.AddBoolean(NoError);
89 ID.AddBoolean(FError);
93const StreamErrorState ErrorNone{
true,
false,
false};
94const StreamErrorState ErrorFEof{
false,
true,
false};
95const StreamErrorState ErrorFError{
false,
false,
true};
97enum class IODirection { Input, Output, Any };
103 const FnDescription *LastOperation;
112 StringRef getKindStr()
const {
121 llvm_unreachable(
"Unknown StreamState!");
126 StreamErrorState
const ErrorState;
136 bool const FilePositionIndeterminate =
false;
141 IODirection NextAllowedIODir;
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.");
154 bool isOpened()
const {
return State == Opened; }
155 bool isClosed()
const {
return State == Closed; }
156 bool isOpenFailed()
const {
return State == OpenFailed; }
161 return LastOperation ==
X.LastOperation && State ==
X.State &&
162 ErrorState ==
X.ErrorState &&
163 FilePositionIndeterminate ==
X.FilePositionIndeterminate &&
164 NextAllowedIODir ==
X.NextAllowedIODir;
167 static StreamState getOpened(
const FnDescription *L,
168 IODirection Dir = IODirection::Any) {
169 return StreamState{L, Opened, ErrorNone,
false, Dir};
171 static StreamState getOpened(
const FnDescription *L,
172 const StreamErrorState &ES,
173 bool IsFilePositionIndeterminate) {
174 return StreamState{L, Opened, ES, IsFilePositionIndeterminate,
177 static StreamState getOpened(
const FnDescription *L, IODirection Access,
178 const StreamErrorState &ES,
179 bool IsFilePositionIndeterminate) {
180 return StreamState{L, Opened, ES, IsFilePositionIndeterminate, Access};
182 static StreamState getClosed(
const FnDescription *L) {
183 return StreamState{L, Closed, {},
false, IODirection::Any};
185 static StreamState getOpenFailed(
const FnDescription *L) {
186 return StreamState{L, OpenFailed, {},
false, IODirection::Any};
189 LLVM_DUMP_METHOD
void dump()
const { dumpToStream(llvm::errs()); }
190 LLVM_DUMP_METHOD
void dumpToStream(llvm::raw_ostream &os)
const;
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);
215using FnCheck =
std::function<void(
const StreamChecker *,
const FnDescription *,
218using ArgNoTy =
unsigned int;
219static const ArgNoTy ArgNone = std::numeric_limits<ArgNoTy>::max();
221const char *FeofNote =
"Assuming stream reaches end-of-file here";
222const char *FerrorNote =
"Assuming this stream operation fails";
224struct FnDescription {
230LLVM_DUMP_METHOD
void StreamState::dumpToStream(llvm::raw_ostream &os)
const {
231 os <<
"{Kind: " << getKindStr() <<
", Last operation: " << LastOperation
233 ErrorState.dumpToStream(os);
234 os <<
", FilePos: " << (FilePositionIndeterminate ?
"Indeterminate" :
"OK")
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);
248 return C.getSValBuilder()
249 .conjureSymbolVal(
nullptr, Elem,
C.getStackFrame(),
251 .castAs<DefinedSVal>();
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.");
264 CheckerContext &
C,
const CallExpr *CE) {
265 State = State->BindExpr(CE,
C.getStackFrame(),
270inline void assertStreamStateOpened(
const StreamState *SS) {
271 assert(SS->isOpened() &&
"Stream is expected to be opened");
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",
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;
297 const CallEvent *
Call,
301 void checkASTDecl(
const TranslationUnitDecl *TU, AnalysisManager &,
302 BugReporter &)
const;
304 const BugType *getBT_StreamEof()
const {
return &BT_StreamEof; }
305 const BugType *getBT_IndeterminatePosition()
const {
306 return &BT_IndeterminatePosition;
313 CheckerContext &
C)
const;
315 const NoteTag *constructSetEofNoteTag(CheckerContext &
C,
317 return C.getNoteTag([
this, StreamSym](PathSensitiveBugReport &BR) {
328 const NoteTag *constructSetErrorNoteTag(CheckerContext &
C,
330 return C.getNoteTag([
this, StreamSym](PathSensitiveBugReport &BR) {
332 &BR.
getBugType() != this->getBT_IndeterminatePosition())
341 const NoteTag *constructSetEofOrErrorNoteTag(CheckerContext &
C,
343 return C.getNoteTag([
this, StreamSym](PathSensitiveBugReport &BR) {
347 if (&BR.
getBugType() == this->getBT_StreamEof()) {
351 if (&BR.
getBugType() == this->getBT_IndeterminatePosition()) {
361 bool TestMode =
false;
364 bool PedanticMode =
false;
366 const CallDescription FCloseDesc = {CDM::CLibrary, {
"fclose"}, 1};
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),
446 {{CDM::CLibrary, {
"ferror"}, 1},
447 {&StreamChecker::preDefault,
448 std::bind(&StreamChecker::evalFeofFerror, _1,
_2, _3, _4, ErrorFError),
450 {{CDM::CLibrary, {
"fileno"}, 1},
451 {&StreamChecker::preDefault, &StreamChecker::evalFileno, 0}},
454 CallDescriptionMap<FnDescription> FnTestDescriptions = {
455 {{CDM::SimpleFunc, {
"StreamTesterChecker_make_feof_stream"}, 1},
457 std::bind(&StreamChecker::evalSetFeofFerror, _1,
_2, _3, _4, ErrorFEof,
460 {{CDM::SimpleFunc, {
"StreamTesterChecker_make_ferror_stream"}, 1},
462 std::bind(&StreamChecker::evalSetFeofFerror, _1,
_2, _3, _4,
466 {
"StreamTesterChecker_make_ferror_indeterminate_stream"},
469 std::bind(&StreamChecker::evalSetFeofFerror, _1,
_2, _3, _4,
475 mutable std::optional<int> EofVal;
477 mutable int SeekSetVal = 0;
479 mutable int SeekCurVal = 1;
481 mutable int SeekEndVal = 2;
483 mutable QualType VaListType;
485 mutable const VarDecl *StdinDecl =
nullptr;
486 mutable const VarDecl *StdoutDecl =
nullptr;
487 mutable const VarDecl *StderrDecl =
nullptr;
489 void evalFopen(
const FnDescription *Desc,
const CallEvent &
Call,
490 CheckerContext &
C)
const;
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;
497 void evalFclose(
const FnDescription *Desc,
const CallEvent &
Call,
498 CheckerContext &
C)
const;
500 void preRead(
const FnDescription *Desc,
const CallEvent &
Call,
501 CheckerContext &
C)
const;
503 void preWrite(
const FnDescription *Desc,
const CallEvent &
Call,
504 CheckerContext &
C)
const;
506 void preGetpos(
const FnDescription *Desc,
const CallEvent &
Call,
507 CheckerContext &
C)
const;
509 void evalFreadFwrite(
const FnDescription *Desc,
const CallEvent &
Call,
510 CheckerContext &
C,
bool IsFread)
const;
512 void evalFgetx(
const FnDescription *Desc,
const CallEvent &
Call,
513 CheckerContext &
C,
bool SingleChar)
const;
515 void evalFputx(
const FnDescription *Desc,
const CallEvent &
Call,
516 CheckerContext &
C,
bool IsSingleChar)
const;
518 void evalFprintf(
const FnDescription *Desc,
const CallEvent &
Call,
519 CheckerContext &
C)
const;
521 void evalFscanf(
const FnDescription *Desc,
const CallEvent &
Call,
522 CheckerContext &
C)
const;
524 void evalUngetc(
const FnDescription *Desc,
const CallEvent &
Call,
525 CheckerContext &
C)
const;
527 void evalGetdelim(
const FnDescription *Desc,
const CallEvent &
Call,
528 CheckerContext &
C)
const;
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;
535 void evalFgetpos(
const FnDescription *Desc,
const CallEvent &
Call,
536 CheckerContext &
C)
const;
538 void evalFsetpos(
const FnDescription *Desc,
const CallEvent &
Call,
539 CheckerContext &
C)
const;
541 void evalFtell(
const FnDescription *Desc,
const CallEvent &
Call,
542 CheckerContext &
C)
const;
544 void evalRewind(
const FnDescription *Desc,
const CallEvent &
Call,
545 CheckerContext &
C)
const;
547 void preDefault(
const FnDescription *Desc,
const CallEvent &
Call,
548 CheckerContext &
C)
const;
550 void evalClearerr(
const FnDescription *Desc,
const CallEvent &
Call,
551 CheckerContext &
C)
const;
553 void evalFeofFerror(
const FnDescription *Desc,
const CallEvent &
Call,
555 const StreamErrorState &ErrorKind)
const;
557 void evalSetFeofFerror(
const FnDescription *Desc,
const CallEvent &
Call,
558 CheckerContext &
C,
const StreamErrorState &ErrorKind,
559 bool Indeterminate)
const;
561 void preFflush(
const FnDescription *Desc,
const CallEvent &
Call,
562 CheckerContext &
C)
const;
564 void evalFflush(
const FnDescription *Desc,
const CallEvent &
Call,
565 CheckerContext &
C)
const;
567 void evalFileno(
const FnDescription *Desc,
const CallEvent &
Call,
568 CheckerContext &
C)
const;
574 ProgramStateRef ensureStreamNonNull(SVal StreamVal,
const Expr *StreamE,
591 ensureNoFilePositionIndeterminate(SVal StreamVal, CheckerContext &
C,
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;
610 void reportFEofWarning(
SymbolRef StreamSym, CheckerContext &
C,
617 void reportAlternatingAccessWarning(
SymbolRef StreamSym,
618 IODirection NextAllowedIODir,
625 ExplodedNode *reportLeaks(
const SmallVector<SymbolRef, 2> &LeakedSyms,
626 CheckerContext &
C)
const;
630 const FnDescription *lookupFn(
const CallEvent &
Call)
const {
633 for (
auto *P :
Call.parameters()) {
634 QualType T = P->getType();
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 {
655 void initMacroValues(
const Preprocessor &PP)
const {
664 SeekSetVal = *OptInt;
666 SeekEndVal = *OptInt;
668 SeekCurVal = *OptInt;
673 static const ExplodedNode *getAcquisitionSite(
const ExplodedNode *N,
678struct StreamOperationEvaluator {
680 const ASTContext &ACtx;
683 const StreamState *SS =
nullptr;
684 const CallExpr *CE =
nullptr;
685 std::optional<ConstCFGElementRef> Elem;
686 StreamErrorState NewES;
688 StreamOperationEvaluator(CheckerContext &
C)
689 : SVB(
C.getSValBuilder()), ACtx(
C.getASTContext()) {
693 bool Init(
const FnDescription *Desc,
const CallEvent &
Call, CheckerContext &
C,
695 StreamSym = getStreamArg(Desc,
Call).getAsSymbol();
698 SS = State->get<StreamMap>(StreamSym);
701 NewES = SS->ErrorState;
702 CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
705 Elem =
Call.getCFGElementRef();
707 assertStreamStateOpened(SS);
712 bool isStreamEof()
const {
return SS->ErrorState == ErrorFEof; }
714 NonLoc getZeroVal(
const CallEvent &
Call) {
719 const StreamState &NewSS) {
720 NewES = NewSS.ErrorState;
721 return State->set<StreamMap>(StreamSym, NewSS);
725 NonLoc RetVal = makeRetVal(
C, Elem.value()).
castAs<NonLoc>();
726 return State->BindExpr(CE,
C.getStackFrame(), RetVal);
731 return State->BindExpr(CE,
C.getStackFrame(),
737 return State->BindExpr(CE,
C.getStackFrame(), Val);
742 return State->BindExpr(CE,
C.getStackFrame(),
743 C.getSValBuilder().makeNullWithType(CE->
getType()));
750 .
getAs<DefinedOrUnknownSVal>();
753 return State->assume(*Cond,
true);
758 DefinedSVal RetVal = makeRetVal(
C, Elem.value());
759 State = State->BindExpr(CE,
C.getStackFrame(), RetVal);
760 return C.getConstraintManager().assumeDual(State, RetVal);
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);
783class NoStreamStateChangeVisitor final :
public NoOwnershipChangeVisitor {
790 bool isClosingCallAsWritten(
const CallExpr &
Call)
const {
791 const auto *StreamChk =
static_cast<const StreamChecker *
>(&Checker);
795 bool doesFnIntendToHandleOwnership(
const Decl *Callee,
796 ASTContext &ACtx)
final {
797 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Callee);
812 using namespace clang::ast_matchers;
815 auto IsClosingCallAsWritten = [
this](
const BoundNodes &
Match) {
816 const auto *
Call =
Match.getNodeAs<CallExpr>(
"call");
817 return Call && isClosingCallAsWritten(*
Call);
821 return llvm::any_of(Matches, IsClosingCallAsWritten);
826 return CallEnterState->get<StreamMap>(Sym) !=
827 CallExitEndState->get<StreamMap>(Sym);
833 N->
getState()->getStateManager().getContext().getSourceManager());
834 return std::make_shared<PathDiagnosticEventPiece>(
835 L,
"Returning without closing stream object or storing it for later "
840 NoStreamStateChangeVisitor(
SymbolRef Sym,
const StreamChecker *Checker)
841 : NoOwnershipChangeVisitor(Sym, Checker) {}
846const ExplodedNode *StreamChecker::getAcquisitionSite(
const ExplodedNode *N,
852 if (!State->get<StreamMap>(StreamSym))
855 const ExplodedNode *Pred = N;
858 if (!State->get<StreamMap>(StreamSym))
870 return Int->tryExtValue();
879 unsigned BlockCount,
const SubRegion *Buffer,
882 constexpr auto DoNotInvalidateSuperRegion =
883 RegionAndSymbolInvalidationTraits::InvalidationKinds::
884 TK_DoNotInvalidateSuperRegion;
887 const ASTContext &Ctx = State->getStateManager().getContext();
892 EscapingVals.reserve(ElementCount);
895 for (
auto Idx : llvm::seq(StartIndex, StartIndex + ElementCount)) {
897 const auto *Element =
898 RegionManager.getElementRegion(ElemType, Index, Buffer, Ctx);
900 ITraits.
setTrait(Element, DoNotInvalidateSuperRegion);
902 return State->invalidateRegions(
903 EscapingVals,
Call.getCFGElementRef(), BlockCount, SF,
905 nullptr, &
Call, &ITraits);
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(),
924void StreamChecker::checkPreCall(
const CallEvent &
Call,
925 CheckerContext &
C)
const {
926 const FnDescription *Desc = lookupFn(
Call);
927 if (!Desc || !Desc->PreFn)
930 Desc->PreFn(
this, Desc,
Call,
C);
933bool StreamChecker::evalCall(
const CallEvent &
Call, CheckerContext &
C)
const {
934 const FnDescription *Desc = lookupFn(
Call);
935 if (!Desc && TestMode)
937 if (!Desc || !Desc->EvalFn)
940 Desc->EvalFn(
this, Desc,
Call,
C);
942 return C.isDifferent();
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));
957 .
castAs<DefinedOrUnknownSVal>();
958 return State->assume(NoAliasState,
true);
962 State = assumeRetNE(State, StdinDecl);
963 State = assumeRetNE(State, StdoutDecl);
964 State = assumeRetNE(State, StderrDecl);
969void StreamChecker::evalFopen(
const FnDescription *Desc,
const CallEvent &
Call,
970 CheckerContext &
C)
const {
972 const CallExpr *CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
976 DefinedSVal RetVal = makeRetVal(
C,
Call.getCFGElementRef());
978 assert(RetSym &&
"RetVal must be a symbol here.");
980 State = State->BindExpr(CE,
C.getStackFrame(), RetVal);
985 std::tie(StateNotNull, StateNull) =
986 C.getConstraintManager().assumeDual(State, RetVal);
989 StateNotNull->set<StreamMap>(RetSym, StreamState::getOpened(Desc));
991 StateNull->set<StreamMap>(RetSym, StreamState::getOpenFailed(Desc));
993 StateNotNull = assumeNoAliasingWithStdStreams(StateNotNull, RetVal,
C);
995 C.addTransition(StateNotNull,
996 constructLeakNoteTag(
C, RetSym,
"Stream opened here"));
997 C.addTransition(StateNull);
1000void StreamChecker::preFreopen(
const FnDescription *Desc,
const CallEvent &
Call,
1001 CheckerContext &
C)
const {
1003 auto [State, _] = checkCommonPreconditions(
1004 Desc,
Call,
C,
false,
1009 C.addTransition(State);
1012void StreamChecker::evalFreopen(
const FnDescription *Desc,
1013 const CallEvent &
Call,
1014 CheckerContext &
C)
const {
1017 auto *CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
1021 std::optional<DefinedSVal> StreamVal =
1022 getStreamArg(Desc,
Call).getAs<DefinedSVal>();
1026 SymbolRef StreamSym = StreamVal->getAsSymbol();
1033 if (!State->get<StreamMap>(StreamSym))
1041 State->BindExpr(CE,
C.getStackFrame(), *StreamVal);
1045 State->BindExpr(CE,
C.getStackFrame(),
1046 C.getSValBuilder().makeNullWithType(CE->
getType()));
1049 StateRetNotNull->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
1051 StateRetNull->set<StreamMap>(StreamSym, StreamState::getOpenFailed(Desc));
1053 C.addTransition(StateRetNotNull,
1054 constructLeakNoteTag(
C, StreamSym,
"Stream reopened here"));
1055 C.addTransition(StateRetNull);
1058void StreamChecker::evalFclose(
const FnDescription *Desc,
const CallEvent &
Call,
1059 CheckerContext &
C)
const {
1061 StreamOperationEvaluator E(
C);
1062 if (!E.Init(Desc,
Call,
C, State))
1068 State = E.setStreamState(State, StreamState::getClosed(Desc));
1071 C.addTransition(E.bindReturnValue(State,
C, 0));
1072 C.addTransition(E.bindReturnValue(State,
C, *EofVal));
1075void StreamChecker::preRead(
const FnDescription *Desc,
const CallEvent &
Call,
1076 CheckerContext &
C)
const {
1077 auto [State, StreamVal] = checkCommonPreconditions(Desc,
Call,
C);
1081 SymbolRef Sym = StreamVal.getAsSymbol();
1082 if (
const StreamState *SS = State->get<StreamMap>(Sym)) {
1083 if (SS->ErrorState & ErrorFEof) {
1084 reportFEofWarning(Sym,
C, State);
1087 if (SS->NextAllowedIODir == IODirection::Output) {
1088 reportAlternatingAccessWarning(Sym, IODirection::Output,
C, State);
1092 C.addTransition(State);
1095void StreamChecker::preWrite(
const FnDescription *Desc,
const CallEvent &
Call,
1096 CheckerContext &
C)
const {
1097 auto [State, StreamVal] = checkCommonPreconditions(Desc,
Call,
C);
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);
1108 C.addTransition(State);
1111void StreamChecker::preGetpos(
const FnDescription *Desc,
const CallEvent &
Call,
1112 CheckerContext &
C)
const {
1113 auto [State, _] = checkCommonPreconditions(Desc,
Call,
C);
1117 C.addTransition(State);
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();
1135 return std::nullopt;
1137 auto Zero = [&SVB] {
1142 if (
const auto *ER = dyn_cast<ElementRegion>(R))
1143 return ER->getIndex();
1148 return std::nullopt;
1156 const auto *Buffer =
1157 dyn_cast_or_null<SubRegion>(
Call.getArgSVal(0).getAsRegion());
1161 std::optional<SVal> StartElementIndex =
1165 if (
const auto *ER = dyn_cast_or_null<ElementRegion>(Buffer))
1166 Buffer = dyn_cast<SubRegion>(ER->getSuperRegion());
1168 std::optional<int64_t> CountVal =
getKnownValue(State, NMembVal);
1169 std::optional<int64_t> Size =
getKnownValue(State, SizeVal);
1170 std::optional<int64_t> StartIndexVal =
1173 if (!ElemTy.
isNull() && CountVal && Size && StartIndexVal) {
1174 int64_t NumBytesRead = Size.value() * CountVal.value();
1176 if (ElemSizeInChars == 0 || NumBytesRead < 0)
1179 bool IncompleteLastElement = (NumBytesRead % ElemSizeInChars) != 0;
1180 int64_t NumCompleteOrIncompleteElementsRead =
1181 NumBytesRead / ElemSizeInChars + IncompleteLastElement;
1183 constexpr int MaxInvalidatedElementsLimit = 64;
1184 if (NumCompleteOrIncompleteElementsRead <= MaxInvalidatedElementsLimit) {
1186 ElemTy, *StartIndexVal,
1187 NumCompleteOrIncompleteElementsRead);
1193void StreamChecker::evalFreadFwrite(
const FnDescription *Desc,
1194 const CallEvent &
Call, CheckerContext &
C,
1195 bool IsFread)
const {
1197 StreamOperationEvaluator E(
C);
1198 if (!E.Init(Desc,
Call,
C, State))
1201 std::optional<NonLoc> SizeVal =
Call.getArgSVal(1).getAs<NonLoc>();
1204 std::optional<NonLoc> NMembVal =
Call.getArgSVal(2).getAs<NonLoc>();
1213 if (State->isNull(*SizeVal).isConstrainedTrue() ||
1214 State->isNull(*NMembVal).isConstrainedTrue()) {
1217 C.addTransition(E.bindReturnValue(State,
C, 0));
1223 if (IsFread && !E.isStreamEof()) {
1227 State,
C,
Call, *SizeVal, *NMembVal);
1229 InvalidatedState ? InvalidatedState :
escapeArgs(State,
C,
Call, {0});
1234 if (!IsFread || !E.isStreamEof()) {
1236 State->BindExpr(E.CE,
C.getStackFrame(), *NMembVal);
1237 StateNotFailed = E.setStreamState(
1239 StreamState::getOpened(Desc, IsFread ? IODirection::Input
1240 : IODirection::Output));
1241 C.addTransition(StateNotFailed);
1246 if (!IsFread && !PedanticMode)
1249 NonLoc RetVal = makeRetVal(
C, E.Elem.value()).
castAs<NonLoc>();
1251 State->BindExpr(E.CE,
C.getStackFrame(), RetVal);
1252 StateFailed = E.assumeBinOpNN(StateFailed, BO_LT, RetVal, *NMembVal);
1256 StreamErrorState NewES;
1258 NewES = E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
1260 NewES = ErrorFError;
1263 StateFailed = E.setStreamState(
1264 StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1265 C.addTransition(StateFailed, E.getFailureNoteTag(
this,
C));
1268void StreamChecker::evalFgetx(
const FnDescription *Desc,
const CallEvent &
Call,
1269 CheckerContext &
C,
bool SingleChar)
const {
1274 StreamOperationEvaluator E(
C);
1275 if (!E.Init(Desc,
Call,
C, State))
1278 if (!E.isStreamEof()) {
1284 NonLoc RetVal = makeRetVal(
C, E.Elem.value()).
castAs<NonLoc>();
1286 State->BindExpr(E.CE,
C.getStackFrame(), RetVal);
1289 StateNotFailed = StateNotFailed->assumeInclusiveRange(
1291 E.SVB.getBasicValueFactory().getValue(0, E.ACtx.UnsignedCharTy),
1292 E.SVB.getBasicValueFactory().getMaxValue(E.ACtx.UnsignedCharTy),
1294 if (!StateNotFailed)
1296 StateNotFailed = E.setStreamState(
1297 StateNotFailed, StreamState::getOpened(Desc, IODirection::Input));
1298 C.addTransition(StateNotFailed);
1301 std::optional<DefinedSVal> GetBuf =
1302 Call.getArgSVal(0).getAs<DefinedSVal>();
1306 State->BindExpr(E.CE,
C.getStackFrame(), *GetBuf);
1307 StateNotFailed = E.setStreamState(
1308 StateNotFailed, StreamState::getOpened(Desc, IODirection::Input));
1309 C.addTransition(StateNotFailed);
1316 StateFailed = E.bindReturnValue(State,
C, *EofVal);
1318 StateFailed = E.bindNullReturnValue(State,
C);
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));
1329void StreamChecker::evalFputx(
const FnDescription *Desc,
const CallEvent &
Call,
1330 CheckerContext &
C,
bool IsSingleChar)
const {
1335 StreamOperationEvaluator E(
C);
1336 if (!E.Init(Desc,
Call,
C, State))
1341 std::optional<NonLoc> PutVal =
Call.getArgSVal(0).getAs<NonLoc>();
1345 State->BindExpr(E.CE,
C.getStackFrame(), *PutVal);
1346 StateNotFailed = E.setStreamState(
1347 StateNotFailed, StreamState::getOpened(Desc, IODirection::Output));
1348 C.addTransition(StateNotFailed);
1351 NonLoc RetVal = makeRetVal(
C, E.Elem.value()).
castAs<NonLoc>();
1353 State->BindExpr(E.CE,
C.getStackFrame(), RetVal);
1355 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(
Call));
1356 if (!StateNotFailed)
1358 StateNotFailed = E.setStreamState(
1359 StateNotFailed, StreamState::getOpened(Desc, IODirection::Output));
1360 C.addTransition(StateNotFailed);
1369 StateFailed = E.setStreamState(
1370 StateFailed, StreamState::getOpened(Desc, ErrorFError,
true));
1371 C.addTransition(StateFailed, E.getFailureNoteTag(
this,
C));
1374void StreamChecker::evalFprintf(
const FnDescription *Desc,
1375 const CallEvent &
Call,
1376 CheckerContext &
C)
const {
1377 if (
Call.getNumArgs() < 2)
1381 StreamOperationEvaluator E(
C);
1382 if (!E.Init(Desc,
Call,
C, State))
1385 NonLoc RetVal = makeRetVal(
C, E.Elem.value()).
castAs<NonLoc>();
1386 State = State->BindExpr(E.CE,
C.getStackFrame(), RetVal);
1389 .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
1390 E.SVB.getConditionType())
1391 .
getAs<DefinedOrUnknownSVal>();
1395 std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
1397 StateNotFailed = E.setStreamState(
1398 StateNotFailed, StreamState::getOpened(Desc, IODirection::Output));
1399 C.addTransition(StateNotFailed);
1406 StateFailed = E.setStreamState(
1407 StateFailed, StreamState::getOpened(Desc, ErrorFError,
true));
1408 C.addTransition(StateFailed, E.getFailureNoteTag(
this,
C));
1411void StreamChecker::evalFscanf(
const FnDescription *Desc,
const CallEvent &
Call,
1412 CheckerContext &
C)
const {
1413 if (
Call.getNumArgs() < 2)
1417 StreamOperationEvaluator E(
C);
1418 if (!E.Init(Desc,
Call,
C, State))
1429 if (!E.isStreamEof()) {
1430 NonLoc RetVal = makeRetVal(
C, E.Elem.value()).
castAs<NonLoc>();
1432 State->BindExpr(E.CE,
C.getStackFrame(), RetVal);
1433 StateNotFailed = E.setStreamState(
1434 StateNotFailed, StreamState::getOpened(Desc, IODirection::Input));
1436 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(
Call));
1437 if (!StateNotFailed)
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);
1449 C.addTransition(StateNotFailed);
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));
1466void StreamChecker::evalUngetc(
const FnDescription *Desc,
const CallEvent &
Call,
1467 CheckerContext &
C)
const {
1469 StreamOperationEvaluator E(
C);
1470 if (!E.Init(Desc,
Call,
C, State))
1474 std::optional<NonLoc> PutVal =
Call.getArgSVal(0).getAs<NonLoc>();
1478 StateNotFailed = E.setStreamState(
1480 StreamState::getOpened(Desc, E.SS->NextAllowedIODir, E.SS->ErrorState,
1481 E.SS->FilePositionIndeterminate));
1482 C.addTransition(StateNotFailed);
1491 StateFailed = E.setStreamState(
1493 StreamState::getOpened(Desc, E.SS->NextAllowedIODir, E.SS->ErrorState,
1494 E.SS->FilePositionIndeterminate));
1495 C.addTransition(StateFailed);
1498void StreamChecker::evalGetdelim(
const FnDescription *Desc,
1499 const CallEvent &
Call,
1500 CheckerContext &
C)
const {
1502 StreamOperationEvaluator E(
C);
1503 if (!E.Init(Desc,
Call,
C, State))
1512 if (!E.isStreamEof()) {
1518 NonLoc RetVal = makeRetVal(
C, E.Elem.value()).
castAs<NonLoc>();
1520 StateNotFailed = E.setStreamState(
1521 StateNotFailed, StreamState::getOpened(Desc, IODirection::Input));
1523 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(
Call));
1528 StateNotFailed = StateNotFailed->assume(
1529 NewLinePtr->castAs<DefinedOrUnknownSVal>(),
true);
1533 SVal SizePtrSval =
Call.getArgSVal(1);
1536 StateNotFailed = E.assumeBinOpNN(StateNotFailed, BO_GT,
1537 NVal->castAs<NonLoc>(), RetVal);
1538 StateNotFailed = E.bindReturnValue(StateNotFailed,
C, RetVal);
1540 if (!StateNotFailed)
1542 C.addTransition(StateNotFailed);
1549 StreamErrorState NewES =
1550 E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
1551 StateFailed = E.setStreamState(
1552 StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
1556 StateFailed->bindLoc(*NewLinePtr, UndefinedVal(),
C.getStackFrame());
1557 C.addTransition(StateFailed, E.getFailureNoteTag(
this,
C));
1560void StreamChecker::preFseek(
const FnDescription *Desc,
const CallEvent &
Call,
1561 CheckerContext &
C)
const {
1562 auto [State, _] = checkCommonPreconditions(
1563 Desc,
Call,
C,
false);
1566 State = ensureFseekWhenceCorrect(
Call.getArgSVal(2),
C, State);
1570 C.addTransition(State);
1573void StreamChecker::evalFseek(
const FnDescription *Desc,
const CallEvent &
Call,
1574 CheckerContext &
C)
const {
1576 StreamOperationEvaluator E(
C);
1577 if (!E.Init(Desc,
Call,
C, State))
1584 E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
1585 C.addTransition(StateNotFailed);
1597 StateFailed = E.setStreamState(
1598 StateFailed, StreamState::getOpened(Desc, ErrorNone | ErrorFError,
true));
1599 C.addTransition(StateFailed, E.getFailureNoteTag(
this,
C));
1602void StreamChecker::evalFgetpos(
const FnDescription *Desc,
1603 const CallEvent &
Call,
1604 CheckerContext &
C)
const {
1606 StreamOperationEvaluator E(
C);
1607 if (!E.Init(Desc,
Call,
C, State))
1611 std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State,
C);
1617 C.addTransition(StateNotFailed);
1618 C.addTransition(StateFailed);
1621void StreamChecker::evalFsetpos(
const FnDescription *Desc,
1622 const CallEvent &
Call,
1623 CheckerContext &
C)
const {
1625 StreamOperationEvaluator E(
C);
1626 if (!E.Init(Desc,
Call,
C, State))
1630 std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State,
C);
1632 StateNotFailed = E.setStreamState(
1633 StateNotFailed, StreamState::getOpened(Desc, IODirection::Any));
1634 C.addTransition(StateNotFailed);
1643 StateFailed = E.setStreamState(
1644 StateFailed, StreamState::getOpened(Desc, ErrorNone | ErrorFError,
true));
1646 C.addTransition(StateFailed, E.getFailureNoteTag(
this,
C));
1649void StreamChecker::evalFtell(
const FnDescription *Desc,
const CallEvent &
Call,
1650 CheckerContext &
C)
const {
1652 StreamOperationEvaluator E(
C);
1653 if (!E.Init(Desc,
Call,
C, State))
1656 NonLoc RetVal = makeRetVal(
C, E.Elem.value()).castAs<NonLoc>();
1658 State->BindExpr(E.CE,
C.getStackFrame(), RetVal);
1660 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(
Call));
1661 if (!StateNotFailed)
1669 C.addTransition(StateNotFailed);
1670 C.addTransition(StateFailed);
1673void StreamChecker::evalRewind(
const FnDescription *Desc,
const CallEvent &
Call,
1674 CheckerContext &
C)
const {
1676 StreamOperationEvaluator E(
C);
1677 if (!E.Init(Desc,
Call,
C, State))
1681 E.setStreamState(State, StreamState::getOpened(Desc, IODirection::Any));
1682 C.addTransition(State);
1685void StreamChecker::preFflush(
const FnDescription *Desc,
const CallEvent &
Call,
1686 CheckerContext &
C)
const {
1688 SVal StreamVal = getStreamArg(Desc,
Call);
1689 std::optional<DefinedSVal> Stream = StreamVal.
getAs<DefinedSVal>();
1694 std::tie(StateNotNull, StateNull) =
1695 C.getConstraintManager().assumeDual(State, *Stream);
1696 if (StateNotNull && !StateNull)
1697 ensureStreamOpened(StreamVal,
C, StateNotNull);
1700void StreamChecker::evalFflush(
const FnDescription *Desc,
const CallEvent &
Call,
1701 CheckerContext &
C)
const {
1703 SVal StreamVal = getStreamArg(Desc,
Call);
1704 std::optional<DefinedSVal> Stream = StreamVal.
getAs<DefinedSVal>();
1710 std::tie(StateNotNull, StateNull) =
1711 C.getConstraintManager().assumeDual(State, *Stream);
1712 if (StateNotNull && StateNull)
1714 if (StateNotNull && !StateNull)
1715 State = StateNotNull;
1719 const CallExpr *CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
1727 auto SetNotFailedStreamState =
1728 [Desc, &StateNotFailed](
SymbolRef Sym,
const StreamState *SS) {
1731 StreamErrorState NewES = SS->ErrorState & (~ErrorFError);
1734 StateNotFailed = StateNotFailed->set<StreamMap>(
1735 Sym, StreamState::getOpened(Desc, NewES,
false));
1738 if (StateNotNull && !StateNull) {
1741 const StreamState *SS = State->get<StreamMap>(StreamSym);
1743 assert(SS->isOpened() &&
"Stream is expected to be opened");
1744 SetNotFailedStreamState(StreamSym, SS);
1750 const StreamMapTy &Map = StateNotFailed->get<StreamMap>();
1751 for (
const auto &I : Map) {
1753 const StreamState &SS = I.second;
1755 SetNotFailedStreamState(Sym, &SS);
1761 C.addTransition(StateNotFailed);
1762 C.addTransition(StateFailed);
1765void StreamChecker::evalClearerr(
const FnDescription *Desc,
1766 const CallEvent &
Call,
1767 CheckerContext &
C)
const {
1769 StreamOperationEvaluator E(
C);
1770 if (!E.Init(Desc,
Call,
C, State))
1774 State = E.setStreamState(
1775 State, StreamState::getOpened(Desc, E.SS->NextAllowedIODir, ErrorNone,
1776 E.SS->FilePositionIndeterminate));
1777 C.addTransition(State);
1780void StreamChecker::evalFeofFerror(
const FnDescription *Desc,
1781 const CallEvent &
Call, CheckerContext &
C,
1782 const StreamErrorState &ErrorKind)
const {
1784 StreamOperationEvaluator E(
C);
1785 if (!E.Init(Desc,
Call,
C, State))
1788 if (E.SS->ErrorState & ErrorKind) {
1793 bindAndAssumeTrue(State,
C, E.CE, E.Elem.value());
1794 C.addTransition(E.setStreamState(
1796 StreamState::getOpened(Desc, E.SS->NextAllowedIODir, ErrorKind,
1797 E.SS->FilePositionIndeterminate &&
1798 !ErrorKind.isFEof())));
1800 if (StreamErrorState NewES = E.SS->ErrorState & (~ErrorKind)) {
1805 C.addTransition(E.setStreamState(
1806 FalseState, StreamState::getOpened(Desc, E.SS->NextAllowedIODir, NewES,
1807 E.SS->FilePositionIndeterminate &&
1812void StreamChecker::evalFileno(
const FnDescription *Desc,
const CallEvent &
Call,
1813 CheckerContext &
C)
const {
1824 StreamOperationEvaluator E(
C);
1825 if (!E.Init(Desc,
Call,
C, State))
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));
1834 C.addTransition(State);
1837void StreamChecker::preDefault(
const FnDescription *Desc,
const CallEvent &
Call,
1838 CheckerContext &
C)
const {
1839 auto [State, _] = checkCommonPreconditions(
1840 Desc,
Call,
C,
false);
1844 C.addTransition(State);
1847void StreamChecker::evalSetFeofFerror(
const FnDescription *Desc,
1848 const CallEvent &
Call, CheckerContext &
C,
1849 const StreamErrorState &ErrorKind,
1850 bool Indeterminate)
const {
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);
1863StreamChecker::ensureStreamNonNull(SVal StreamVal,
const Expr *StreamE,
1866 auto Stream = StreamVal.
getAs<DefinedSVal>();
1870 ConstraintManager &CM =
C.getConstraintManager();
1873 std::tie(StateNotNull, StateNull) = CM.
assumeDual(State, *Stream);
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);
1881 C.emitReport(std::move(R));
1886 return StateNotNull;
1890class StreamClosedVisitor final :
public BugReporterVisitor {
1892 bool Satisfied =
false;
1895 explicit StreamClosedVisitor(
SymbolRef StreamSym) : StreamSym(StreamSym) {}
1897 static void *getTag() {
1902 void Profile(llvm::FoldingSetNodeID &ID)
const override {
1903 ID.AddPointer(getTag());
1904 ID.AddPointer(StreamSym);
1908 BugReporterContext &BRC,
1909 PathSensitiveBugReport &BR)
override {
1912 const StreamState *PredSS =
1914 if (PredSS && PredSS->isClosed())
1922 llvm::StringLiteral Msg =
"Stream is closed here";
1923 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg);
1935 const StreamState *SS = State->get<StreamMap>(Sym);
1939 if (SS->isClosed()) {
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));
1953 if (SS->isOpenFailed()) {
1958 ExplodedNode *N =
C.addSink();
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",
1975 static const char *BugMessage =
1976 "File position of the stream might be 'indeterminate' "
1977 "after a failed operation; "
1978 "can cause undefined behavior";
1984 const StreamState *SS = State->get<StreamMap>(Sym);
1988 assert(SS->isOpened() &&
"First ensure that stream is opened.");
1990 if (SS->FilePositionIndeterminate) {
1991 if (SS->ErrorState & ErrorFEof) {
1995 ExplodedNode *N =
C.generateNonFatalErrorNode(State);
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));
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));
2023StreamChecker::ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &
C,
2025 std::optional<nonloc::ConcreteInt> CI =
2026 WhenceVal.
getAs<nonloc::ConcreteInt>();
2030 int64_t X = CI->getValue()->getSExtValue();
2031 if (
X == SeekSetVal ||
X == SeekCurVal ||
X == SeekEndVal)
2034 if (ExplodedNode *N =
C.generateNonFatalErrorNode(State)) {
2035 C.emitReport(std::make_unique<PathSensitiveBugReport>(
2037 "The whence argument to fseek() should be "
2038 "SEEK_SET, SEEK_END, or SEEK_CUR.",
2046std::tuple<ProgramStateRef, SVal> StreamChecker::checkCommonPreconditions(
2047 const FnDescription *Desc,
const CallEvent &
Call, CheckerContext &
C,
2048 bool EnsureNoFilePositionIndeterminate,
bool EnsureStreamOpened,
2049 bool EnsureStreamNonNull)
const {
2051 SVal StreamVal = getStreamArg(Desc,
Call);
2053 if (EnsureStreamNonNull)
2054 State = ensureStreamNonNull(StreamVal,
Call.getArgExpr(Desc->StreamArgNo),
2056 if (State && EnsureStreamOpened)
2057 State = ensureStreamOpened(StreamVal,
C, State);
2058 if (State && EnsureNoFilePositionIndeterminate)
2059 State = ensureNoFilePositionIndeterminate(StreamVal,
C, State);
2061 return std::make_tuple(State, StreamVal);
2064void StreamChecker::reportFEofWarning(
SymbolRef StreamSym, CheckerContext &
C,
2066 if (ExplodedNode *N =
C.generateNonFatalErrorNode(State)) {
2067 auto R = std::make_unique<PathSensitiveBugReport>(
2069 "Read function called when stream is in EOF state; "
2070 "function has no effect",
2072 R->markInteresting(StreamSym);
2073 C.emitReport(std::move(R));
2078void StreamChecker::reportAlternatingAccessWarning(
2079 SymbolRef StreamSym, IODirection NextAllowedIODir, CheckerContext &
C,
2081 if (ExplodedNode *N =
C.generateNonFatalErrorNode(State)) {
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 "
2089 auto R = std::make_unique<PathSensitiveBugReport>(BT_AlternateReadWrite,
2091 R->markInteresting(StreamSym);
2092 C.emitReport(std::move(R));
2098StreamChecker::reportLeaks(
const SmallVector<SymbolRef, 2> &LeakedSyms,
2099 CheckerContext &
C)
const {
2100 if (LeakedSyms.empty())
2101 return C.getPredecessor();
2102 ExplodedNode *Err =
C.generateNonFatalErrorNode();
2104 return C.getPredecessor();
2118 const ExplodedNode *StreamOpenNode = getAcquisitionSite(Err, LeakSym,
C);
2119 assert(StreamOpenNode &&
"Could not find place of stream opening.");
2121 PathDiagnosticLocation LocUsedForUniqueing;
2124 StreamStmt,
C.getSourceManager(), StreamOpenNode->
getStackFrame());
2126 std::unique_ptr<PathSensitiveBugReport>
R =
2127 std::make_unique<PathSensitiveBugReport>(
2129 "Opened stream never closed; potential resource leak", Err,
2131 R->markInteresting(LeakSym);
2132 R->addVisitor<NoStreamStateChangeVisitor>(LeakSym,
this);
2133 C.emitReport(std::move(R));
2139void StreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2140 CheckerContext &
C)
const {
2143 llvm::SmallVector<SymbolRef, 2> LeakedSyms;
2145 const StreamMapTy &Map = State->get<StreamMap>();
2146 for (
const auto &I : Map) {
2148 const StreamState &SS = I.second;
2149 if (!SymReaper.
isDead(Sym))
2152 LeakedSyms.push_back(Sym);
2153 State = State->remove<StreamMap>(Sym);
2156 C.addTransition(State, reportLeaks(LeakedSyms,
C));
2176 State = State->remove<StreamMap>(Sym);
2181static const VarDecl *
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) {
2204void StreamChecker::checkASTDecl(
const TranslationUnitDecl *TU,
2205 AnalysisManager &Mgr, BugReporter &)
const {
2217void ento::registerStreamChecker(CheckerManager &Mgr) {
2219 Checker->PedanticMode =
2223bool ento::shouldRegisterStreamChecker(
const CheckerManager &Mgr) {
2227void ento::registerStreamTesterChecker(CheckerManager &Mgr) {
2228 auto *Checker = Mgr.
getChecker<StreamChecker>();
2229 Checker->TestMode =
true;
2232bool ento::shouldRegisterStreamTesterChecker(
const CheckerManager &Mgr) {
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
#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 ...
SourceManager & getSourceManager()
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.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
BinaryOperatorKind Opcode
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
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.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
QualType getCanonicalType() const
It represents a stack frame of the call stack.
const Decl * getDecl() const
The top declaration context.
ASTContext & getASTContext() const
bool isPointerType() const
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
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.
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.
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.
void markNotInteresting(SymbolRef sym)
bool isInteresting(SymbolRef sym) const
SValBuilder & getSValBuilder()
Information about invalidation for a particular region/symbol.
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.
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
SubRegion - A region that subsets another larger region.
MemRegionManager & getMemRegionManager() const override
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
Value representing integer constant.
__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
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
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.
bool isa(CodeGen::Address addr)
CFGBlock::ConstCFGElementRef ConstCFGElementRef
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
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
__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