#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
#include <functional>
using namespace clang;
using namespace ento;
using namespace std::placeholders;
namespace {
struct FnDescription;
struct StreamErrorState {
bool NoError = true;
bool FEof = false;
bool FError = false;
bool isNoError() const { return NoError && !FEof && !FError; }
bool isFEof() const { return !NoError && FEof && !FError; }
bool isFError() const { return !NoError && !FEof && FError; }
bool operator==(const StreamErrorState &ES) const {
return NoError == ES.NoError && FEof == ES.FEof && FError == ES.FError;
}
bool operator!=(const StreamErrorState &ES) const { return !(*this == ES); }
StreamErrorState operator|(const StreamErrorState &E) const {
return {NoError || E.NoError, FEof || E.FEof, FError || E.FError};
}
StreamErrorState operator&(const StreamErrorState &E) const {
return {NoError && E.NoError, FEof && E.FEof, FError && E.FError};
}
StreamErrorState operator~() const { return {!NoError, !FEof, !FError}; }
operator bool() const { return NoError || FEof || FError; }
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddBoolean(NoError);
ID.AddBoolean(FEof);
ID.AddBoolean(FError);
}
};
const StreamErrorState ErrorNone{true, false, false};
const StreamErrorState ErrorFEof{false, true, false};
const StreamErrorState ErrorFError{false, false, true};
struct StreamState {
const FnDescription *LastOperation;
enum KindTy {
Opened, Closed, OpenFailed } State;
StreamErrorState const ErrorState;
bool const FilePositionIndeterminate = false;
StreamState(const FnDescription *L, KindTy S, const StreamErrorState &ES,
bool IsFilePositionIndeterminate)
: LastOperation(L), State(S), ErrorState(ES),
FilePositionIndeterminate(IsFilePositionIndeterminate) {
assert((!ES.isFEof() || !IsFilePositionIndeterminate) &&
"FilePositionIndeterminate should be false in FEof case.");
assert((State == Opened || ErrorState.isNoError()) &&
"ErrorState should be None in non-opened stream state.");
}
bool isOpened() const { return State == Opened; }
bool isClosed() const { return State == Closed; }
bool isOpenFailed() const { return State == OpenFailed; }
bool operator==(const StreamState &X) const {
return LastOperation == X.LastOperation && State == X.State &&
ErrorState == X.ErrorState &&
FilePositionIndeterminate == X.FilePositionIndeterminate;
}
static StreamState getOpened(const FnDescription *L,
const StreamErrorState &ES = ErrorNone,
bool IsFilePositionIndeterminate = false) {
return StreamState{L, Opened, ES, IsFilePositionIndeterminate};
}
static StreamState getClosed(const FnDescription *L) {
return StreamState{L, Closed, {}, false};
}
static StreamState getOpenFailed(const FnDescription *L) {
return StreamState{L, OpenFailed, {}, false};
}
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddPointer(LastOperation);
ID.AddInteger(State);
ErrorState.Profile(ID);
ID.AddBoolean(FilePositionIndeterminate);
}
};
}
namespace {
class StreamChecker;
using FnCheck = std::function<void(const StreamChecker *, const FnDescription *,
const CallEvent &, CheckerContext &)>;
using ArgNoTy = unsigned int;
static const ArgNoTy ArgNone = std::numeric_limits<ArgNoTy>::max();
struct FnDescription {
FnCheck PreFn;
FnCheck EvalFn;
ArgNoTy StreamArgNo;
};
SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
assert(Desc && Desc->StreamArgNo != ArgNone &&
"Try to get a non-existing stream argument.");
return Call.getArgSVal(Desc->StreamArgNo);
}
DefinedSVal makeRetVal(CheckerContext &C, const CallExpr *CE) {
assert(CE && "Expecting a call expression.");
const LocationContext *LCtx = C.getLocationContext();
return C.getSValBuilder()
.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount())
.castAs<DefinedSVal>();
}
ProgramStateRef bindAndAssumeTrue(ProgramStateRef State, CheckerContext &C,
const CallExpr *CE) {
DefinedSVal RetVal = makeRetVal(C, CE);
State = State->BindExpr(CE, C.getLocationContext(), RetVal);
State = State->assume(RetVal, true);
assert(State && "Assumption on new value should not fail.");
return State;
}
ProgramStateRef bindInt(uint64_t Value, ProgramStateRef State,
CheckerContext &C, const CallExpr *CE) {
State = State->BindExpr(CE, C.getLocationContext(),
C.getSValBuilder().makeIntVal(Value, false));
return State;
}
class StreamChecker : public Checker<check::PreCall, eval::Call,
check::DeadSymbols, check::PointerEscape> {
BugType BT_FileNull{this, "NULL stream pointer", "Stream handling error"};
BugType BT_UseAfterClose{this, "Closed stream", "Stream handling error"};
BugType BT_UseAfterOpenFailed{this, "Invalid stream",
"Stream handling error"};
BugType BT_IndeterminatePosition{this, "Invalid stream state",
"Stream handling error"};
BugType BT_IllegalWhence{this, "Illegal whence argument",
"Stream handling error"};
BugType BT_StreamEof{this, "Stream already in EOF", "Stream handling error"};
BugType BT_ResourceLeak{this, "Resource leak", "Stream handling error",
true};
public:
void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
bool evalCall(const CallEvent &Call, CheckerContext &C) const;
void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
ProgramStateRef checkPointerEscape(ProgramStateRef State,
const InvalidatedSymbols &Escaped,
const CallEvent *Call,
PointerEscapeKind Kind) const;
bool TestMode = false;
const BugType *getBT_StreamEof() const { return &BT_StreamEof; }
private:
CallDescriptionMap<FnDescription> FnDescriptions = {
{{"fopen"}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
{{"freopen", 3},
{&StreamChecker::preFreopen, &StreamChecker::evalFreopen, 2}},
{{"tmpfile"}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
{{"fclose", 1},
{&StreamChecker::preDefault, &StreamChecker::evalFclose, 0}},
{{"fread", 4},
{&StreamChecker::preFread,
std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, true), 3}},
{{"fwrite", 4},
{&StreamChecker::preFwrite,
std::bind(&StreamChecker::evalFreadFwrite, _1, _2, _3, _4, false), 3}},
{{"fseek", 3}, {&StreamChecker::preFseek, &StreamChecker::evalFseek, 0}},
{{"ftell", 1}, {&StreamChecker::preDefault, nullptr, 0}},
{{"rewind", 1}, {&StreamChecker::preDefault, nullptr, 0}},
{{"fgetpos", 2}, {&StreamChecker::preDefault, nullptr, 0}},
{{"fsetpos", 2}, {&StreamChecker::preDefault, nullptr, 0}},
{{"clearerr", 1},
{&StreamChecker::preDefault, &StreamChecker::evalClearerr, 0}},
{{"feof", 1},
{&StreamChecker::preDefault,
std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFEof),
0}},
{{"ferror", 1},
{&StreamChecker::preDefault,
std::bind(&StreamChecker::evalFeofFerror, _1, _2, _3, _4, ErrorFError),
0}},
{{"fileno", 1}, {&StreamChecker::preDefault, nullptr, 0}},
};
CallDescriptionMap<FnDescription> FnTestDescriptions = {
{{"StreamTesterChecker_make_feof_stream", 1},
{nullptr,
std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4, ErrorFEof),
0}},
{{"StreamTesterChecker_make_ferror_stream", 1},
{nullptr,
std::bind(&StreamChecker::evalSetFeofFerror, _1, _2, _3, _4,
ErrorFError),
0}},
};
void evalFopen(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void preFreopen(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void evalFreopen(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void evalFclose(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void preFread(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void preFwrite(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void evalFreadFwrite(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C, bool IsFread) const;
void preFseek(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void evalFseek(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void preDefault(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void evalClearerr(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const;
void evalFeofFerror(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C,
const StreamErrorState &ErrorKind) const;
void evalSetFeofFerror(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C,
const StreamErrorState &ErrorKind) const;
ProgramStateRef ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
CheckerContext &C,
ProgramStateRef State) const;
ProgramStateRef ensureStreamOpened(SVal StreamVal, CheckerContext &C,
ProgramStateRef State) const;
ProgramStateRef
ensureNoFilePositionIndeterminate(SVal StreamVal, CheckerContext &C,
ProgramStateRef State) const;
ProgramStateRef ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
ProgramStateRef State) const;
void reportFEofWarning(SymbolRef StreamSym, CheckerContext &C,
ProgramStateRef State) const;
ExplodedNode *reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
CheckerContext &C, ExplodedNode *Pred) const;
const FnDescription *lookupFn(const CallEvent &Call) const {
if (!Call.isGlobalCFunction())
return nullptr;
for (auto P : Call.parameters()) {
QualType T = P->getType();
if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
return nullptr;
}
return FnDescriptions.lookup(Call);
}
struct NoteFn {
const BugType *BT_ResourceLeak;
SymbolRef StreamSym;
std::string Message;
std::string operator()(PathSensitiveBugReport &BR) const {
if (BR.isInteresting(StreamSym) && &BR.getBugType() == BT_ResourceLeak)
return Message;
return "";
}
};
const NoteTag *constructNoteTag(CheckerContext &C, SymbolRef StreamSym,
const std::string &Message) const {
return C.getNoteTag(NoteFn{&BT_ResourceLeak, StreamSym, Message});
}
const NoteTag *constructSetEofNoteTag(CheckerContext &C,
SymbolRef StreamSym) const {
return C.getNoteTag([this, StreamSym](PathSensitiveBugReport &BR) {
if (!BR.isInteresting(StreamSym) ||
&BR.getBugType() != this->getBT_StreamEof())
return "";
BR.markNotInteresting(StreamSym);
return "Assuming stream reaches end-of-file here";
});
}
static const ExplodedNode *getAcquisitionSite(const ExplodedNode *N,
SymbolRef StreamSym,
CheckerContext &C);
};
}
REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
inline void assertStreamStateOpened(const StreamState *SS) {
assert(SS->isOpened() &&
"Previous create of error node for non-opened stream failed?");
}
const ExplodedNode *StreamChecker::getAcquisitionSite(const ExplodedNode *N,
SymbolRef StreamSym,
CheckerContext &C) {
ProgramStateRef State = N->getState();
if (!State->get<StreamMap>(StreamSym))
N = N->getFirstPred();
const ExplodedNode *Pred = N;
while (N) {
State = N->getState();
if (!State->get<StreamMap>(StreamSym))
return Pred;
Pred = N;
N = N->getFirstPred();
}
return nullptr;
}
void StreamChecker::checkPreCall(const CallEvent &Call,
CheckerContext &C) const {
const FnDescription *Desc = lookupFn(Call);
if (!Desc || !Desc->PreFn)
return;
Desc->PreFn(this, Desc, Call, C);
}
bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
const FnDescription *Desc = lookupFn(Call);
if (!Desc && TestMode)
Desc = FnTestDescriptions.lookup(Call);
if (!Desc || !Desc->EvalFn)
return false;
Desc->EvalFn(this, Desc, Call, C);
return C.isDifferent();
}
void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
if (!CE)
return;
DefinedSVal RetVal = makeRetVal(C, CE);
SymbolRef RetSym = RetVal.getAsSymbol();
assert(RetSym && "RetVal must be a symbol here.");
State = State->BindExpr(CE, C.getLocationContext(), RetVal);
ProgramStateRef StateNotNull, StateNull;
std::tie(StateNotNull, StateNull) =
C.getConstraintManager().assumeDual(State, RetVal);
StateNotNull =
StateNotNull->set<StreamMap>(RetSym, StreamState::getOpened(Desc));
StateNull =
StateNull->set<StreamMap>(RetSym, StreamState::getOpenFailed(Desc));
C.addTransition(StateNotNull,
constructNoteTag(C, RetSym, "Stream opened here"));
C.addTransition(StateNull);
}
void StreamChecker::preFreopen(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
State = ensureStreamNonNull(getStreamArg(Desc, Call),
Call.getArgExpr(Desc->StreamArgNo), C, State);
if (!State)
return;
C.addTransition(State);
}
void StreamChecker::evalFreopen(const FnDescription *Desc,
const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
if (!CE)
return;
Optional<DefinedSVal> StreamVal =
getStreamArg(Desc, Call).getAs<DefinedSVal>();
if (!StreamVal)
return;
SymbolRef StreamSym = StreamVal->getAsSymbol();
if (!StreamSym)
return;
if (!State->get<StreamMap>(StreamSym))
return;
ProgramStateRef StateRetNotNull =
State->BindExpr(CE, C.getLocationContext(), *StreamVal);
ProgramStateRef StateRetNull =
State->BindExpr(CE, C.getLocationContext(),
C.getSValBuilder().makeNullWithType(CE->getType()));
StateRetNotNull =
StateRetNotNull->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
StateRetNull =
StateRetNull->set<StreamMap>(StreamSym, StreamState::getOpenFailed(Desc));
C.addTransition(StateRetNotNull,
constructNoteTag(C, StreamSym, "Stream reopened here"));
C.addTransition(StateRetNull);
}
void StreamChecker::evalFclose(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SymbolRef Sym = getStreamArg(Desc, Call).getAsSymbol();
if (!Sym)
return;
const StreamState *SS = State->get<StreamMap>(Sym);
if (!SS)
return;
assertStreamStateOpened(SS);
State = State->set<StreamMap>(Sym, StreamState::getClosed(Desc));
C.addTransition(State);
}
void StreamChecker::preFread(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SVal StreamVal = getStreamArg(Desc, Call);
State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
State);
if (!State)
return;
State = ensureStreamOpened(StreamVal, C, State);
if (!State)
return;
State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
if (!State)
return;
SymbolRef Sym = StreamVal.getAsSymbol();
if (Sym && State->get<StreamMap>(Sym)) {
const StreamState *SS = State->get<StreamMap>(Sym);
if (SS->ErrorState & ErrorFEof)
reportFEofWarning(Sym, C, State);
} else {
C.addTransition(State);
}
}
void StreamChecker::preFwrite(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SVal StreamVal = getStreamArg(Desc, Call);
State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
State);
if (!State)
return;
State = ensureStreamOpened(StreamVal, C, State);
if (!State)
return;
State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
if (!State)
return;
C.addTransition(State);
}
void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
const CallEvent &Call, CheckerContext &C,
bool IsFread) const {
ProgramStateRef State = C.getState();
SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
if (!StreamSym)
return;
const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
if (!CE)
return;
Optional<NonLoc> SizeVal = Call.getArgSVal(1).getAs<NonLoc>();
if (!SizeVal)
return;
Optional<NonLoc> NMembVal = Call.getArgSVal(2).getAs<NonLoc>();
if (!NMembVal)
return;
const StreamState *OldSS = State->get<StreamMap>(StreamSym);
if (!OldSS)
return;
assertStreamStateOpened(OldSS);
if (State->isNull(*SizeVal).isConstrainedTrue() ||
State->isNull(*NMembVal).isConstrainedTrue()) {
State = bindInt(0, State, C, CE);
C.addTransition(State);
return;
}
if (!IsFread || (OldSS->ErrorState != ErrorFEof)) {
ProgramStateRef StateNotFailed =
State->BindExpr(CE, C.getLocationContext(), *NMembVal);
StateNotFailed =
StateNotFailed->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
C.addTransition(StateNotFailed);
}
NonLoc RetVal = makeRetVal(C, CE).castAs<NonLoc>();
ProgramStateRef StateFailed =
State->BindExpr(CE, C.getLocationContext(), RetVal);
auto Cond =
C.getSValBuilder()
.evalBinOpNN(State, BO_LT, RetVal, *NMembVal, C.getASTContext().IntTy)
.getAs<DefinedOrUnknownSVal>();
if (!Cond)
return;
StateFailed = StateFailed->assume(*Cond, true);
if (!StateFailed)
return;
StreamErrorState NewES;
if (IsFread)
NewES =
(OldSS->ErrorState == ErrorFEof) ? ErrorFEof : ErrorFEof | ErrorFError;
else
NewES = ErrorFError;
StreamState NewSS = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
StateFailed = StateFailed->set<StreamMap>(StreamSym, NewSS);
if (IsFread && OldSS->ErrorState != ErrorFEof)
C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
else
C.addTransition(StateFailed);
}
void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SVal StreamVal = getStreamArg(Desc, Call);
State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
State);
if (!State)
return;
State = ensureStreamOpened(StreamVal, C, State);
if (!State)
return;
State = ensureFseekWhenceCorrect(Call.getArgSVal(2), C, State);
if (!State)
return;
C.addTransition(State);
}
void StreamChecker::evalFseek(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
if (!StreamSym)
return;
const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
if (!CE)
return;
if (!State->get<StreamMap>(StreamSym))
return;
DefinedSVal RetVal = makeRetVal(C, CE);
State = State->BindExpr(CE, C.getLocationContext(), RetVal);
ProgramStateRef StateNotFailed, StateFailed;
std::tie(StateFailed, StateNotFailed) =
C.getConstraintManager().assumeDual(State, RetVal);
StateNotFailed =
StateNotFailed->set<StreamMap>(StreamSym, StreamState::getOpened(Desc));
StateFailed = StateFailed->set<StreamMap>(
StreamSym,
StreamState::getOpened(Desc, ErrorNone | ErrorFEof | ErrorFError, true));
C.addTransition(StateNotFailed);
C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
}
void StreamChecker::evalClearerr(const FnDescription *Desc,
const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
if (!StreamSym)
return;
const StreamState *SS = State->get<StreamMap>(StreamSym);
if (!SS)
return;
assertStreamStateOpened(SS);
State = State->set<StreamMap>(
StreamSym,
StreamState::getOpened(Desc, ErrorNone, SS->FilePositionIndeterminate));
C.addTransition(State);
}
void StreamChecker::evalFeofFerror(const FnDescription *Desc,
const CallEvent &Call, CheckerContext &C,
const StreamErrorState &ErrorKind) const {
ProgramStateRef State = C.getState();
SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
if (!StreamSym)
return;
const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
if (!CE)
return;
const StreamState *SS = State->get<StreamMap>(StreamSym);
if (!SS)
return;
assertStreamStateOpened(SS);
if (SS->ErrorState & ErrorKind) {
ProgramStateRef TrueState = bindAndAssumeTrue(State, C, CE);
C.addTransition(TrueState->set<StreamMap>(
StreamSym, StreamState::getOpened(Desc, ErrorKind,
SS->FilePositionIndeterminate &&
!ErrorKind.isFEof())));
}
if (StreamErrorState NewES = SS->ErrorState & (~ErrorKind)) {
ProgramStateRef FalseState = bindInt(0, State, C, CE);
C.addTransition(FalseState->set<StreamMap>(
StreamSym,
StreamState::getOpened(
Desc, NewES, SS->FilePositionIndeterminate && !NewES.isFEof())));
}
}
void StreamChecker::preDefault(const FnDescription *Desc, const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SVal StreamVal = getStreamArg(Desc, Call);
State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
State);
if (!State)
return;
State = ensureStreamOpened(StreamVal, C, State);
if (!State)
return;
C.addTransition(State);
}
void StreamChecker::evalSetFeofFerror(const FnDescription *Desc,
const CallEvent &Call, CheckerContext &C,
const StreamErrorState &ErrorKind) const {
ProgramStateRef State = C.getState();
SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
assert(StreamSym && "Operation not permitted on non-symbolic stream value.");
const StreamState *SS = State->get<StreamMap>(StreamSym);
assert(SS && "Stream should be tracked by the checker.");
State = State->set<StreamMap>(
StreamSym, StreamState::getOpened(SS->LastOperation, ErrorKind));
C.addTransition(State);
}
ProgramStateRef
StreamChecker::ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
CheckerContext &C,
ProgramStateRef State) const {
auto Stream = StreamVal.getAs<DefinedSVal>();
if (!Stream)
return State;
ConstraintManager &CM = C.getConstraintManager();
ProgramStateRef StateNotNull, StateNull;
std::tie(StateNotNull, StateNull) = CM.assumeDual(C.getState(), *Stream);
if (!StateNotNull && StateNull) {
if (ExplodedNode *N = C.generateErrorNode(StateNull)) {
auto R = std::make_unique<PathSensitiveBugReport>(
BT_FileNull, "Stream pointer might be NULL.", N);
if (StreamE)
bugreporter::trackExpressionValue(N, StreamE, *R);
C.emitReport(std::move(R));
}
return nullptr;
}
return StateNotNull;
}
ProgramStateRef StreamChecker::ensureStreamOpened(SVal StreamVal,
CheckerContext &C,
ProgramStateRef State) const {
SymbolRef Sym = StreamVal.getAsSymbol();
if (!Sym)
return State;
const StreamState *SS = State->get<StreamMap>(Sym);
if (!SS)
return State;
if (SS->isClosed()) {
ExplodedNode *N = C.generateErrorNode();
if (N) {
C.emitReport(std::make_unique<PathSensitiveBugReport>(
BT_UseAfterClose,
"Stream might be already closed. Causes undefined behaviour.", N));
return nullptr;
}
return State;
}
if (SS->isOpenFailed()) {
ExplodedNode *N = C.generateErrorNode();
if (N) {
C.emitReport(std::make_unique<PathSensitiveBugReport>(
BT_UseAfterOpenFailed,
"Stream might be invalid after "
"(re-)opening it has failed. "
"Can cause undefined behaviour.",
N));
return nullptr;
}
return State;
}
return State;
}
ProgramStateRef StreamChecker::ensureNoFilePositionIndeterminate(
SVal StreamVal, CheckerContext &C, ProgramStateRef State) const {
static const char *BugMessage =
"File position of the stream might be 'indeterminate' "
"after a failed operation. "
"Can cause undefined behavior.";
SymbolRef Sym = StreamVal.getAsSymbol();
if (!Sym)
return State;
const StreamState *SS = State->get<StreamMap>(Sym);
if (!SS)
return State;
assert(SS->isOpened() && "First ensure that stream is opened.");
if (SS->FilePositionIndeterminate) {
if (SS->ErrorState & ErrorFEof) {
ExplodedNode *N = C.generateNonFatalErrorNode(State);
if (!N)
return nullptr;
C.emitReport(std::make_unique<PathSensitiveBugReport>(
BT_IndeterminatePosition, BugMessage, N));
return State->set<StreamMap>(
Sym, StreamState::getOpened(SS->LastOperation, ErrorFEof, false));
}
ExplodedNode *N = C.generateErrorNode(State);
if (N)
C.emitReport(std::make_unique<PathSensitiveBugReport>(
BT_IndeterminatePosition, BugMessage, N));
return nullptr;
}
return State;
}
ProgramStateRef
StreamChecker::ensureFseekWhenceCorrect(SVal WhenceVal, CheckerContext &C,
ProgramStateRef State) const {
Optional<nonloc::ConcreteInt> CI = WhenceVal.getAs<nonloc::ConcreteInt>();
if (!CI)
return State;
int64_t X = CI->getValue().getSExtValue();
if (X >= 0 && X <= 2)
return State;
if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
C.emitReport(std::make_unique<PathSensitiveBugReport>(
BT_IllegalWhence,
"The whence argument to fseek() should be "
"SEEK_SET, SEEK_END, or SEEK_CUR.",
N));
return nullptr;
}
return State;
}
void StreamChecker::reportFEofWarning(SymbolRef StreamSym, CheckerContext &C,
ProgramStateRef State) const {
if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
auto R = std::make_unique<PathSensitiveBugReport>(
BT_StreamEof,
"Read function called when stream is in EOF state. "
"Function has no effect.",
N);
R->markInteresting(StreamSym);
C.emitReport(std::move(R));
return;
}
C.addTransition(State);
}
ExplodedNode *
StreamChecker::reportLeaks(const SmallVector<SymbolRef, 2> &LeakedSyms,
CheckerContext &C, ExplodedNode *Pred) const {
ExplodedNode *Err = C.generateNonFatalErrorNode(C.getState(), Pred);
if (!Err)
return Pred;
for (SymbolRef LeakSym : LeakedSyms) {
const ExplodedNode *StreamOpenNode = getAcquisitionSite(Err, LeakSym, C);
assert(StreamOpenNode && "Could not find place of stream opening.");
PathDiagnosticLocation LocUsedForUniqueing =
PathDiagnosticLocation::createBegin(
StreamOpenNode->getStmtForDiagnostics(), C.getSourceManager(),
StreamOpenNode->getLocationContext());
std::unique_ptr<PathSensitiveBugReport> R =
std::make_unique<PathSensitiveBugReport>(
BT_ResourceLeak,
"Opened stream never closed. Potential resource leak.", Err,
LocUsedForUniqueing,
StreamOpenNode->getLocationContext()->getDecl());
R->markInteresting(LeakSym);
C.emitReport(std::move(R));
}
return Err;
}
void StreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
llvm::SmallVector<SymbolRef, 2> LeakedSyms;
const StreamMapTy &Map = State->get<StreamMap>();
for (const auto &I : Map) {
SymbolRef Sym = I.first;
const StreamState &SS = I.second;
if (!SymReaper.isDead(Sym))
continue;
if (SS.isOpened())
LeakedSyms.push_back(Sym);
State = State->remove<StreamMap>(Sym);
}
ExplodedNode *N = C.getPredecessor();
if (!LeakedSyms.empty())
N = reportLeaks(LeakedSyms, C, N);
C.addTransition(State, N);
}
ProgramStateRef StreamChecker::checkPointerEscape(
ProgramStateRef State, const InvalidatedSymbols &Escaped,
const CallEvent *Call, PointerEscapeKind Kind) const {
if (Kind == PSK_DirectEscapeOnCall && Call->isInSystemHeader())
return State;
for (SymbolRef Sym : Escaped) {
State = State->remove<StreamMap>(Sym);
}
return State;
}
void ento::registerStreamChecker(CheckerManager &Mgr) {
Mgr.registerChecker<StreamChecker>();
}
bool ento::shouldRegisterStreamChecker(const CheckerManager &Mgr) {
return true;
}
void ento::registerStreamTesterChecker(CheckerManager &Mgr) {
auto *Checker = Mgr.getChecker<StreamChecker>();
Checker->TestMode = true;
}
bool ento::shouldRegisterStreamTesterChecker(const CheckerManager &Mgr) {
return true;
}