#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Analysis/Analyses/Dominators.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/CFGStmtMap.h"
#include "clang/Analysis/PathDiagnostic.h"
#include "clang/Analysis/ProgramPoint.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <deque>
#include <memory>
#include <string>
#include <utility>
using namespace clang;
using namespace ento;
using namespace bugreporter;
static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
if (B->isAdditiveOp() && B->getType()->isPointerType()) {
if (B->getLHS()->getType()->isPointerType()) {
return B->getLHS();
} else if (B->getRHS()->getType()->isPointerType()) {
return B->getRHS();
}
}
return nullptr;
}
static const Expr *peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N);
const Expr *bugreporter::getDerefExpr(const Stmt *S) {
const auto *E = dyn_cast<Expr>(S);
if (!E)
return nullptr;
while (true) {
if (const auto *CE = dyn_cast<CastExpr>(E)) {
if (CE->getCastKind() == CK_LValueToRValue) {
break;
}
E = CE->getSubExpr();
} else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
if (const Expr *Inner = peelOffPointerArithmetic(B)) {
E = Inner;
} else {
break;
}
} else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
(U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
E = U->getSubExpr();
} else {
break;
}
}
else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
E = ME->getBase();
} else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
E = IvarRef->getBase();
} else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
E = AE->getBase();
} else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
E = PE->getSubExpr();
} else if (const auto *FE = dyn_cast<FullExpr>(E)) {
E = FE->getSubExpr();
} else {
break;
}
}
if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
if (CE->getCastKind() == CK_LValueToRValue)
E = CE->getSubExpr();
return E;
}
static const MemRegion *
getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
bool LookingForReference = true) {
if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
if (LookingForReference && !VD->getType()->isReferenceType())
return nullptr;
return N->getState()
->getLValue(VD, N->getLocationContext())
.getAsRegion();
}
}
return nullptr;
}
static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
const ExplodedNode *RightNode, SVal RightVal) {
if (LeftVal == RightVal)
return true;
const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
if (!LLCV)
return false;
const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
if (!RLCV)
return false;
return LLCV->getRegion() == RLCV->getRegion() &&
LLCV->getStore() == LeftNode->getState()->getStore() &&
RLCV->getStore() == RightNode->getState()->getStore();
}
static Optional<SVal> getSValForVar(const Expr *CondVarExpr,
const ExplodedNode *N) {
ProgramStateRef State = N->getState();
const LocationContext *LCtx = N->getLocationContext();
assert(CondVarExpr);
CondVarExpr = CondVarExpr->IgnoreImpCasts();
if (const auto *DRE = dyn_cast<DeclRefExpr>(CondVarExpr))
if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
return State->getSVal(State->getLValue(VD, LCtx));
if (const auto *ME = dyn_cast<MemberExpr>(CondVarExpr))
if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
if (auto FieldL = State->getSVal(ME, LCtx).getAs<Loc>())
return State->getRawSVal(*FieldL, FD->getType());
return None;
}
static Optional<const llvm::APSInt *>
getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) {
if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
if (auto CI = V->getAs<nonloc::ConcreteInt>())
return &CI->getValue();
return None;
}
static bool isVarAnInterestingCondition(const Expr *CondVarExpr,
const ExplodedNode *N,
const PathSensitiveBugReport *B) {
if (!B->getErrorNode()->getStackFrame()->isParentOf(N->getStackFrame()))
return false;
if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
if (Optional<bugreporter::TrackingKind> K = B->getInterestingnessKind(*V))
return *K == bugreporter::TrackingKind::Condition;
return false;
}
static bool isInterestingExpr(const Expr *E, const ExplodedNode *N,
const PathSensitiveBugReport *B) {
if (Optional<SVal> V = getSValForVar(E, N))
return B->getInterestingnessKind(*V).has_value();
return false;
}
static StringRef getMacroName(SourceLocation Loc,
BugReporterContext &BRC) {
return Lexer::getImmediateMacroName(
Loc,
BRC.getSourceManager(),
BRC.getASTContext().getLangOpts());
}
static bool isFunctionMacroExpansion(SourceLocation Loc,
const SourceManager &SM) {
if (!Loc.isMacroID())
return false;
while (SM.isMacroArgExpansion(Loc))
Loc = SM.getImmediateExpansionRange(Loc).getBegin();
std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
return EInfo.isFunctionMacroExpansion();
}
static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest,
const ExplodedNode *N,
SVal ValueAfter) {
ProgramStateRef State = N->getState();
ProgramStateManager &Mgr = N->getState()->getStateManager();
if (!N->getLocationAs<PostStore>() && !N->getLocationAs<PostInitializer>() &&
!N->getLocationAs<PostStmt>())
return false;
if (auto PS = N->getLocationAs<PostStmt>())
if (auto *BO = PS->getStmtAs<BinaryOperator>())
if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
N->getSVal(BO->getLHS()).getAsRegion()))
return true;
SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
if (!Mgr.getSValBuilder()
.areEqual(State, ValueAtN, ValueAfter)
.isConstrainedTrue() &&
(!ValueAtN.isUndef() || !ValueAfter.isUndef()))
return true;
return false;
}
PathDiagnosticPieceRef BugReporterVisitor::getEndPath(BugReporterContext &,
const ExplodedNode *,
PathSensitiveBugReport &) {
return nullptr;
}
void BugReporterVisitor::finalizeVisitor(BugReporterContext &,
const ExplodedNode *,
PathSensitiveBugReport &) {}
PathDiagnosticPieceRef
BugReporterVisitor::getDefaultEndPath(const BugReporterContext &BRC,
const ExplodedNode *EndPathNode,
const PathSensitiveBugReport &BR) {
PathDiagnosticLocation L = BR.getLocation();
const auto &Ranges = BR.getRanges();
auto P = std::make_shared<PathDiagnosticEventPiece>(
L, BR.getDescription(), Ranges.begin() == Ranges.end());
for (SourceRange Range : Ranges)
P->addRange(Range);
return P;
}
bool NoStateChangeFuncVisitor::isModifiedInFrame(const ExplodedNode *N) {
const LocationContext *Ctx = N->getLocationContext();
const StackFrameContext *SCtx = Ctx->getStackFrame();
if (!FramesModifyingCalculated.count(SCtx))
findModifyingFrames(N);
return FramesModifying.count(SCtx);
}
void NoStateChangeFuncVisitor::markFrameAsModifying(
const StackFrameContext *SCtx) {
while (!SCtx->inTopFrame()) {
auto p = FramesModifying.insert(SCtx);
if (!p.second)
break;
SCtx = SCtx->getParent()->getStackFrame();
}
}
static const ExplodedNode *getMatchingCallExitEnd(const ExplodedNode *N) {
assert(N->getLocationAs<CallEnter>());
const StackFrameContext *OrigSCtx = N->getFirstSucc()->getStackFrame();
auto IsMatchingCallExitEnd = [OrigSCtx](const ExplodedNode *N) {
return N->getLocationAs<CallExitEnd>() &&
OrigSCtx == N->getFirstPred()->getStackFrame();
};
while (N && !IsMatchingCallExitEnd(N)) {
assert(N->succ_size() <= 1 &&
"This function is to be used on the trimmed ExplodedGraph!");
N = N->getFirstSucc();
}
return N;
}
void NoStateChangeFuncVisitor::findModifyingFrames(
const ExplodedNode *const CallExitBeginN) {
assert(CallExitBeginN->getLocationAs<CallExitBegin>());
const StackFrameContext *const OriginalSCtx =
CallExitBeginN->getLocationContext()->getStackFrame();
const ExplodedNode *CurrCallExitBeginN = CallExitBeginN;
const StackFrameContext *CurrentSCtx = OriginalSCtx;
for (const ExplodedNode *CurrN = CallExitBeginN; CurrN;
CurrN = CurrN->getFirstPred()) {
if (CurrN->getLocationAs<CallExitBegin>()) {
CurrCallExitBeginN = CurrN;
CurrentSCtx = CurrN->getStackFrame();
FramesModifyingCalculated.insert(CurrentSCtx);
continue;
}
if (auto CE = CurrN->getLocationAs<CallEnter>()) {
if (const ExplodedNode *CallExitEndN = getMatchingCallExitEnd(CurrN))
if (wasModifiedInFunction(CurrN, CallExitEndN))
markFrameAsModifying(CurrentSCtx);
CurrentSCtx = CurrN->getStackFrame();
if (CE->getCalleeContext() == OriginalSCtx) {
markFrameAsModifying(CurrentSCtx);
break;
}
}
if (wasModifiedBeforeCallExit(CurrN, CurrCallExitBeginN))
markFrameAsModifying(CurrentSCtx);
}
}
PathDiagnosticPieceRef NoStateChangeFuncVisitor::VisitNode(
const ExplodedNode *N, BugReporterContext &BR, PathSensitiveBugReport &R) {
const LocationContext *Ctx = N->getLocationContext();
const StackFrameContext *SCtx = Ctx->getStackFrame();
ProgramStateRef State = N->getState();
auto CallExitLoc = N->getLocationAs<CallExitBegin>();
if (!CallExitLoc || isModifiedInFrame(N))
return nullptr;
CallEventRef<> Call =
BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
if (Call->isInSystemHeader()) {
if (!N->getStackFrame()->getCFG()->isLinear()) {
static int i = 0;
R.markInvalid(&i, nullptr);
}
return nullptr;
}
if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
if (PathDiagnosticPieceRef Piece = maybeEmitNoteForObjCSelf(R, *MC, N))
return Piece;
}
if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
return maybeEmitNoteForCXXThis(R, *CCall, N);
}
return maybeEmitNoteForParameters(R, *Call, N);
}
namespace {
class NoStoreFuncVisitor final : public NoStateChangeFuncVisitor {
const SubRegion *RegionOfInterest;
MemRegionManager &MmrMgr;
const SourceManager &SM;
const PrintingPolicy &PP;
static const unsigned DEREFERENCE_LIMIT = 2;
using RegionVector = SmallVector<const MemRegion *, 5>;
public:
NoStoreFuncVisitor(const SubRegion *R, bugreporter::TrackingKind TKind)
: NoStateChangeFuncVisitor(TKind), RegionOfInterest(R),
MmrMgr(R->getMemRegionManager()),
SM(MmrMgr.getContext().getSourceManager()),
PP(MmrMgr.getContext().getPrintingPolicy()) {}
void Profile(llvm::FoldingSetNodeID &ID) const override {
static int Tag = 0;
ID.AddPointer(&Tag);
ID.AddPointer(RegionOfInterest);
}
private:
bool wasModifiedBeforeCallExit(const ExplodedNode *CurrN,
const ExplodedNode *CallExitBeginN) override;
const Optional<RegionVector>
findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
const MemRegion *R, const RegionVector &Vec = {},
int depth = 0);
PathDiagnosticPieceRef maybeEmitNoteForObjCSelf(PathSensitiveBugReport &R,
const ObjCMethodCall &Call,
const ExplodedNode *N) final;
PathDiagnosticPieceRef maybeEmitNoteForCXXThis(PathSensitiveBugReport &R,
const CXXConstructorCall &Call,
const ExplodedNode *N) final;
PathDiagnosticPieceRef
maybeEmitNoteForParameters(PathSensitiveBugReport &R, const CallEvent &Call,
const ExplodedNode *N) final;
PathDiagnosticPieceRef
maybeEmitNote(PathSensitiveBugReport &R, const CallEvent &Call,
const ExplodedNode *N, const RegionVector &FieldChain,
const MemRegion *MatchedRegion, StringRef FirstElement,
bool FirstIsReferenceType, unsigned IndirectionLevel);
bool prettyPrintRegionName(const RegionVector &FieldChain,
const MemRegion *MatchedRegion,
StringRef FirstElement, bool FirstIsReferenceType,
unsigned IndirectionLevel,
llvm::raw_svector_ostream &os);
StringRef prettyPrintFirstElement(StringRef FirstElement,
bool MoreItemsExpected,
int IndirectionLevel,
llvm::raw_svector_ostream &os);
};
}
static bool potentiallyWritesIntoIvar(const Decl *Parent,
const ObjCIvarDecl *Ivar) {
using namespace ast_matchers;
const char *IvarBind = "Ivar";
if (!Parent || !Parent->hasBody())
return false;
StatementMatcher WriteIntoIvarM = binaryOperator(
hasOperatorName("="),
hasLHS(ignoringParenImpCasts(
objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
for (BoundNodes &Match : Matches) {
auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
if (IvarRef->isFreeIvar())
return true;
const Expr *Base = IvarRef->getBase();
if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
Base = ICE->getSubExpr();
if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
return true;
return false;
}
return false;
}
const Optional<NoStoreFuncVisitor::RegionVector>
NoStoreFuncVisitor::findRegionOfInterestInRecord(
const RecordDecl *RD, ProgramStateRef State, const MemRegion *R,
const NoStoreFuncVisitor::RegionVector &Vec ,
int depth ) {
if (depth == DEREFERENCE_LIMIT) return None;
if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
if (!RDX->hasDefinition())
return None;
if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
for (const auto &II : RDX->bases())
if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
if (Optional<RegionVector> Out =
findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
return Out;
for (const FieldDecl *I : RD->fields()) {
QualType FT = I->getType();
const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
const SVal V = State->getSVal(FR);
const MemRegion *VR = V.getAsRegion();
RegionVector VecF = Vec;
VecF.push_back(FR);
if (RegionOfInterest == VR)
return VecF;
if (const RecordDecl *RRD = FT->getAsRecordDecl())
if (auto Out =
findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
return Out;
QualType PT = FT->getPointeeType();
if (PT.isNull() || PT->isVoidType() || !VR)
continue;
if (const RecordDecl *RRD = PT->getAsRecordDecl())
if (Optional<RegionVector> Out =
findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
return Out;
}
return None;
}
PathDiagnosticPieceRef
NoStoreFuncVisitor::maybeEmitNoteForObjCSelf(PathSensitiveBugReport &R,
const ObjCMethodCall &Call,
const ExplodedNode *N) {
if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
const MemRegion *SelfRegion = Call.getReceiverSVal().getAsRegion();
if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
potentiallyWritesIntoIvar(Call.getRuntimeDefinition().getDecl(),
IvarR->getDecl()))
return maybeEmitNote(R, Call, N, {}, SelfRegion, "self",
false, 1);
}
return nullptr;
}
PathDiagnosticPieceRef
NoStoreFuncVisitor::maybeEmitNoteForCXXThis(PathSensitiveBugReport &R,
const CXXConstructorCall &Call,
const ExplodedNode *N) {
const MemRegion *ThisR = Call.getCXXThisVal().getAsRegion();
if (RegionOfInterest->isSubRegionOf(ThisR) && !Call.getDecl()->isImplicit())
return maybeEmitNote(R, Call, N, {}, ThisR, "this",
false, 1);
return nullptr;
}
static bool isPointerToConst(QualType Ty) {
return !Ty->getPointeeType().isNull() &&
Ty->getPointeeType().getCanonicalType().isConstQualified();
}
PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNoteForParameters(
PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N) {
ArrayRef<ParmVarDecl *> Parameters = Call.parameters();
for (unsigned I = 0; I < Call.getNumArgs() && I < Parameters.size(); ++I) {
const ParmVarDecl *PVD = Parameters[I];
SVal V = Call.getArgSVal(I);
bool ParamIsReferenceType = PVD->getType()->isReferenceType();
std::string ParamName = PVD->getNameAsString();
unsigned IndirectionLevel = 1;
QualType T = PVD->getType();
while (const MemRegion *MR = V.getAsRegion()) {
if (RegionOfInterest->isSubRegionOf(MR) && !isPointerToConst(T))
return maybeEmitNote(R, Call, N, {}, MR, ParamName,
ParamIsReferenceType, IndirectionLevel);
QualType PT = T->getPointeeType();
if (PT.isNull() || PT->isVoidType())
break;
ProgramStateRef State = N->getState();
if (const RecordDecl *RD = PT->getAsRecordDecl())
if (Optional<RegionVector> P =
findRegionOfInterestInRecord(RD, State, MR))
return maybeEmitNote(R, Call, N, *P, RegionOfInterest, ParamName,
ParamIsReferenceType, IndirectionLevel);
V = State->getSVal(MR, PT);
T = PT;
IndirectionLevel++;
}
}
return nullptr;
}
bool NoStoreFuncVisitor::wasModifiedBeforeCallExit(
const ExplodedNode *CurrN, const ExplodedNode *CallExitBeginN) {
return ::wasRegionOfInterestModifiedAt(
RegionOfInterest, CurrN,
CallExitBeginN->getState()->getSVal(RegionOfInterest));
}
static llvm::StringLiteral WillBeUsedForACondition =
", which participates in a condition later";
PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNote(
PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N,
const RegionVector &FieldChain, const MemRegion *MatchedRegion,
StringRef FirstElement, bool FirstIsReferenceType,
unsigned IndirectionLevel) {
PathDiagnosticLocation L =
PathDiagnosticLocation::create(N->getLocation(), SM);
if (!L.hasValidLocation())
return nullptr;
SmallString<256> sbuf;
llvm::raw_svector_ostream os(sbuf);
os << "Returning without writing to '";
if (!prettyPrintRegionName(FieldChain, MatchedRegion, FirstElement,
FirstIsReferenceType, IndirectionLevel, os))
return nullptr;
os << "'";
if (TKind == bugreporter::TrackingKind::Condition)
os << WillBeUsedForACondition;
return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
}
bool NoStoreFuncVisitor::prettyPrintRegionName(const RegionVector &FieldChain,
const MemRegion *MatchedRegion,
StringRef FirstElement,
bool FirstIsReferenceType,
unsigned IndirectionLevel,
llvm::raw_svector_ostream &os) {
if (FirstIsReferenceType)
IndirectionLevel--;
RegionVector RegionSequence;
assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
const MemRegion *R = RegionOfInterest;
while (R != MatchedRegion) {
RegionSequence.push_back(R);
R = cast<SubRegion>(R)->getSuperRegion();
}
std::reverse(RegionSequence.begin(), RegionSequence.end());
RegionSequence.append(FieldChain.begin(), FieldChain.end());
StringRef Sep;
for (const MemRegion *R : RegionSequence) {
if (isa<CXXBaseObjectRegion, CXXTempObjectRegion>(R))
continue;
if (Sep.empty())
Sep = prettyPrintFirstElement(FirstElement,
true,
IndirectionLevel, os);
os << Sep;
if (!isa<DeclRegion>(R))
return false;
const auto *DR = cast<DeclRegion>(R);
Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
DR->getDecl()->getDeclName().print(os, PP);
}
if (Sep.empty())
prettyPrintFirstElement(FirstElement,
false, IndirectionLevel, os);
return true;
}
StringRef NoStoreFuncVisitor::prettyPrintFirstElement(
StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel,
llvm::raw_svector_ostream &os) {
StringRef Out = ".";
if (IndirectionLevel > 0 && MoreItemsExpected) {
IndirectionLevel--;
Out = "->";
}
if (IndirectionLevel > 0 && MoreItemsExpected)
os << "(";
for (int i = 0; i < IndirectionLevel; i++)
os << "*";
os << FirstElement;
if (IndirectionLevel > 0 && MoreItemsExpected)
os << ")";
return Out;
}
namespace {
class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
const SubRegion *RegionOfInterest;
const SVal ValueAtDereference;
bool WasModified = false;
public:
MacroNullReturnSuppressionVisitor(const SubRegion *R, const SVal V)
: RegionOfInterest(R), ValueAtDereference(V) {}
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) override {
if (WasModified)
return nullptr;
auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
if (!BugPoint)
return nullptr;
const SourceManager &SMgr = BRC.getSourceManager();
if (auto Loc = matchAssignment(N)) {
if (isFunctionMacroExpansion(*Loc, SMgr)) {
std::string MacroName = std::string(getMacroName(*Loc, BRC));
SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
BR.markInvalid(getTag(), MacroName.c_str());
}
}
if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
WasModified = true;
return nullptr;
}
static void addMacroVisitorIfNecessary(
const ExplodedNode *N, const MemRegion *R,
bool EnableNullFPSuppression, PathSensitiveBugReport &BR,
const SVal V) {
AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
if (EnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths &&
isa<Loc>(V))
BR.addVisitor<MacroNullReturnSuppressionVisitor>(R->getAs<SubRegion>(),
V);
}
void* getTag() const {
static int Tag = 0;
return static_cast<void *>(&Tag);
}
void Profile(llvm::FoldingSetNodeID &ID) const override {
ID.AddPointer(getTag());
}
private:
Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
const Stmt *S = N->getStmtForDiagnostics();
ProgramStateRef State = N->getState();
auto *LCtx = N->getLocationContext();
if (!S)
return None;
if (const auto *DS = dyn_cast<DeclStmt>(S)) {
if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
if (const Expr *RHS = VD->getInit())
if (RegionOfInterest->isSubRegionOf(
State->getLValue(VD, LCtx).getAsRegion()))
return RHS->getBeginLoc();
} else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
const Expr *RHS = BO->getRHS();
if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
return RHS->getBeginLoc();
}
}
return None;
}
};
}
namespace {
class ReturnVisitor : public TrackingBugReporterVisitor {
const StackFrameContext *CalleeSFC;
enum {
Initial,
MaybeUnsuppress,
Satisfied
} Mode = Initial;
bool EnableNullFPSuppression;
bool ShouldInvalidate = true;
AnalyzerOptions& Options;
bugreporter::TrackingKind TKind;
public:
ReturnVisitor(TrackerRef ParentTracker, const StackFrameContext *Frame,
bool Suppressed, AnalyzerOptions &Options,
bugreporter::TrackingKind TKind)
: TrackingBugReporterVisitor(ParentTracker), CalleeSFC(Frame),
EnableNullFPSuppression(Suppressed), Options(Options), TKind(TKind) {}
static void *getTag() {
static int Tag = 0;
return static_cast<void *>(&Tag);
}
void Profile(llvm::FoldingSetNodeID &ID) const override {
ID.AddPointer(ReturnVisitor::getTag());
ID.AddPointer(CalleeSFC);
ID.AddBoolean(EnableNullFPSuppression);
}
PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
if (N->getLocationContext() != CalleeSFC)
return nullptr;
Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
if (!SP)
return nullptr;
const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
if (!Ret)
return nullptr;
ProgramStateRef State = N->getState();
SVal V = State->getSVal(Ret, CalleeSFC);
if (V.isUnknownOrUndef())
return nullptr;
Mode = Satisfied;
const Expr *RetE = Ret->getRetValue();
assert(RetE && "Tracking a return value for a void function");
Optional<Loc> LValue;
if (RetE->isGLValue()) {
if ((LValue = V.getAs<Loc>())) {
SVal RValue = State->getRawSVal(*LValue, RetE->getType());
if (isa<DefinedSVal>(RValue))
V = RValue;
}
}
if (isa<nonloc::LazyCompoundVal, nonloc::CompoundVal>(V))
return nullptr;
RetE = RetE->IgnoreParenCasts();
getParentTracker().track(RetE, N, {TKind, EnableNullFPSuppression});
SmallString<64> Msg;
llvm::raw_svector_ostream Out(Msg);
bool WouldEventBeMeaningless = false;
if (State->isNull(V).isConstrainedTrue()) {
if (isa<Loc>(V)) {
if (EnableNullFPSuppression &&
Options.ShouldAvoidSuppressingNullArgumentPaths)
Mode = MaybeUnsuppress;
if (RetE->getType()->isObjCObjectPointerType()) {
Out << "Returning nil";
} else {
Out << "Returning null pointer";
}
} else {
Out << "Returning zero";
}
} else {
if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
Out << "Returning the value " << CI->getValue();
} else {
if (N->getCFG().size() == 3)
WouldEventBeMeaningless = true;
Out << (isa<Loc>(V) ? "Returning pointer" : "Returning value");
}
}
if (LValue) {
if (const MemRegion *MR = LValue->getAsRegion()) {
if (MR->canPrintPretty()) {
Out << " (reference to ";
MR->printPretty(Out);
Out << ")";
}
}
} else {
if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
Out << " (loaded from '" << *DD << "')";
}
PathDiagnosticLocation L(Ret, BRC.getSourceManager(), CalleeSFC);
if (!L.isValid() || !L.asLocation().isValid())
return nullptr;
if (TKind == bugreporter::TrackingKind::Condition)
Out << WillBeUsedForACondition;
auto EventPiece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
if (WouldEventBeMeaningless)
EventPiece->setPrunable(true);
else
BR.markInteresting(CalleeSFC);
return EventPiece;
}
PathDiagnosticPieceRef visitNodeMaybeUnsuppress(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
if (!CE)
return nullptr;
if (CE->getCalleeContext() != CalleeSFC)
return nullptr;
Mode = Satisfied;
ProgramStateManager &StateMgr = BRC.getStateManager();
CallEventManager &CallMgr = StateMgr.getCallEventManager();
ProgramStateRef State = N->getState();
CallEventRef<> Call = CallMgr.getCaller(CalleeSFC, State);
for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
if (!ArgV)
continue;
const Expr *ArgE = Call->getArgExpr(I);
if (!ArgE)
continue;
if (!State->isNull(*ArgV).isConstrainedTrue())
continue;
if (getParentTracker()
.track(ArgE, N, {TKind, EnableNullFPSuppression})
.FoundSomethingToTrack)
ShouldInvalidate = false;
}
return nullptr;
}
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) override {
switch (Mode) {
case Initial:
return visitNodeInitial(N, BRC, BR);
case MaybeUnsuppress:
return visitNodeMaybeUnsuppress(N, BRC, BR);
case Satisfied:
return nullptr;
}
llvm_unreachable("Invalid visit mode!");
}
void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
PathSensitiveBugReport &BR) override {
if (EnableNullFPSuppression && ShouldInvalidate)
BR.markInvalid(ReturnVisitor::getTag(), CalleeSFC);
}
};
}
class StoreSiteFinder final : public TrackingBugReporterVisitor {
const MemRegion *R;
SVal V;
bool Satisfied = false;
TrackingOptions Options;
const StackFrameContext *OriginSFC;
public:
StoreSiteFinder(bugreporter::TrackerRef ParentTracker, KnownSVal V,
const MemRegion *R, TrackingOptions Options,
const StackFrameContext *OriginSFC = nullptr)
: TrackingBugReporterVisitor(ParentTracker), R(R), V(V), Options(Options),
OriginSFC(OriginSFC) {
assert(R);
}
void Profile(llvm::FoldingSetNodeID &ID) const override;
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) override;
};
void StoreSiteFinder::Profile(llvm::FoldingSetNodeID &ID) const {
static int tag = 0;
ID.AddPointer(&tag);
ID.AddPointer(R);
ID.Add(V);
ID.AddInteger(static_cast<int>(Options.Kind));
ID.AddBoolean(Options.EnableNullFPSuppression);
}
static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
Optional<PostStmt> P = N->getLocationAs<PostStmt>();
if (!P)
return false;
const DeclStmt *DS = P->getStmtAs<DeclStmt>();
if (!DS)
return false;
if (DS->getSingleDecl() != VR->getDecl())
return false;
const MemSpaceRegion *VarSpace = VR->getMemorySpace();
const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
if (!FrameSpace) {
assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
return true;
}
assert(VR->getDecl()->hasLocalStorage());
const LocationContext *LCtx = N->getLocationContext();
return FrameSpace->getStackFrame() == LCtx->getStackFrame();
}
static bool isObjCPointer(const MemRegion *R) {
if (R->isBoundable())
if (const auto *TR = dyn_cast<TypedValueRegion>(R))
return TR->getValueType()->isObjCObjectPointerType();
return false;
}
static bool isObjCPointer(const ValueDecl *D) {
return D->getType()->isObjCObjectPointerType();
}
static void showBRDiagnostics(llvm::raw_svector_ostream &OS, StoreInfo SI) {
const bool HasPrefix = SI.Dest->canPrintPretty();
if (HasPrefix) {
SI.Dest->printPretty(OS);
OS << " ";
}
const char *Action = nullptr;
switch (SI.StoreKind) {
case StoreInfo::Initialization:
Action = HasPrefix ? "initialized to " : "Initializing to ";
break;
case StoreInfo::BlockCapture:
Action = HasPrefix ? "captured by block as " : "Captured by block as ";
break;
default:
llvm_unreachable("Unexpected store kind");
}
if (isa<loc::ConcreteInt>(SI.Value)) {
OS << Action << (isObjCPointer(SI.Dest) ? "nil" : "a null pointer value");
} else if (auto CVal = SI.Value.getAs<nonloc::ConcreteInt>()) {
OS << Action << CVal->getValue();
} else if (SI.Origin && SI.Origin->canPrintPretty()) {
OS << Action << "the value of ";
SI.Origin->printPretty(OS);
} else if (SI.StoreKind == StoreInfo::Initialization) {
const auto *DS =
cast<DeclStmt>(SI.StoreSite->getLocationAs<PostStmt>()->getStmt());
if (SI.Value.isUndef()) {
if (isa<VarRegion>(SI.Dest)) {
const auto *VD = cast<VarDecl>(DS->getSingleDecl());
if (VD->getInit()) {
OS << (HasPrefix ? "initialized" : "Initializing")
<< " to a garbage value";
} else {
OS << (HasPrefix ? "declared" : "Declaring")
<< " without an initial value";
}
}
} else {
OS << (HasPrefix ? "initialized" : "Initialized") << " here";
}
}
}
static void showBRParamDiagnostics(llvm::raw_svector_ostream &OS,
StoreInfo SI) {
const auto *VR = cast<VarRegion>(SI.Dest);
const auto *Param = cast<ParmVarDecl>(VR->getDecl());
OS << "Passing ";
if (isa<loc::ConcreteInt>(SI.Value)) {
OS << (isObjCPointer(Param) ? "nil object reference"
: "null pointer value");
} else if (SI.Value.isUndef()) {
OS << "uninitialized value";
} else if (auto CI = SI.Value.getAs<nonloc::ConcreteInt>()) {
OS << "the value " << CI->getValue();
} else if (SI.Origin && SI.Origin->canPrintPretty()) {
SI.Origin->printPretty(OS);
} else {
OS << "value";
}
unsigned Idx = Param->getFunctionScopeIndex() + 1;
OS << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
if (VR->canPrintPretty()) {
OS << " ";
VR->printPretty(OS);
}
}
static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &OS,
StoreInfo SI) {
const bool HasSuffix = SI.Dest->canPrintPretty();
if (isa<loc::ConcreteInt>(SI.Value)) {
OS << (isObjCPointer(SI.Dest) ? "nil object reference stored"
: (HasSuffix ? "Null pointer value stored"
: "Storing null pointer value"));
} else if (SI.Value.isUndef()) {
OS << (HasSuffix ? "Uninitialized value stored"
: "Storing uninitialized value");
} else if (auto CV = SI.Value.getAs<nonloc::ConcreteInt>()) {
if (HasSuffix)
OS << "The value " << CV->getValue() << " is assigned";
else
OS << "Assigning " << CV->getValue();
} else if (SI.Origin && SI.Origin->canPrintPretty()) {
if (HasSuffix) {
OS << "The value of ";
SI.Origin->printPretty(OS);
OS << " is assigned";
} else {
OS << "Assigning the value of ";
SI.Origin->printPretty(OS);
}
} else {
OS << (HasSuffix ? "Value assigned" : "Assigning value");
}
if (HasSuffix) {
OS << " to ";
SI.Dest->printPretty(OS);
}
}
PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
if (Satisfied)
return nullptr;
const ExplodedNode *StoreSite = nullptr;
const ExplodedNode *Pred = Succ->getFirstPred();
const Expr *InitE = nullptr;
bool IsParam = false;
if (const auto *VR = dyn_cast<VarRegion>(R)) {
if (isInitializationOfVar(Pred, VR)) {
StoreSite = Pred;
InitE = VR->getDecl()->getInit();
}
}
if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
if (FieldReg == R) {
StoreSite = Pred;
InitE = PIP->getInitializer()->getInit();
}
}
if (!StoreSite) {
if (Succ->getState()->getSVal(R) != V)
return nullptr;
if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
if (!PS || PS->getLocationValue() != R)
return nullptr;
}
StoreSite = Succ;
if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
if (BO->isAssignmentOp())
InitE = BO->getRHS();
if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
if (const auto *VR = dyn_cast<VarRegion>(R)) {
if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) {
ProgramStateManager &StateMgr = BRC.getStateManager();
CallEventManager &CallMgr = StateMgr.getCallEventManager();
CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
Succ->getState());
InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
} else {
assert(isa<ImplicitParamDecl>(VR->getDecl()));
InitE = cast<ObjCMessageExpr>(CE->getCalleeContext()->getCallSite())
->getInstanceReceiver()->IgnoreParenCasts();
}
IsParam = true;
}
}
if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
InitE = TmpR->getExpr();
}
if (!StoreSite)
return nullptr;
Satisfied = true;
if (InitE) {
if (!IsParam)
InitE = InitE->IgnoreParenCasts();
getParentTracker().track(InitE, StoreSite, Options);
}
const MemRegion *OldRegion = nullptr;
if (InitE) {
if (const MemRegion *Candidate =
getLocationRegionIfReference(InitE, Succ, false)) {
const StoreManager &SM = BRC.getStateManager().getStoreManager();
for (const ExplodedNode *N = StoreSite; N; N = N->getFirstPred()) {
if (SM.includedInBindings(N->getState()->getStore(), Candidate)) {
if (N->getState()->getSVal(Candidate) == V) {
OldRegion = Candidate;
}
break;
}
}
}
}
if (!OldRegion && StoreSite->getState()->getSVal(R) == V) {
const ExplodedNode *NodeWithoutBinding = StoreSite->getFirstPred();
for (;
NodeWithoutBinding && NodeWithoutBinding->getState()->getSVal(R) == V;
NodeWithoutBinding = NodeWithoutBinding->getFirstPred()) {
}
if (NodeWithoutBinding) {
StoreManager::FindUniqueBinding FB(V.getAsLocSymbol());
BRC.getStateManager().iterBindings(NodeWithoutBinding->getState(), FB);
if (FB)
OldRegion = FB.getRegion();
}
}
if (Options.Kind == TrackingKind::Condition && OriginSFC &&
!OriginSFC->isParentOf(StoreSite->getStackFrame()))
return nullptr;
SmallString<256> sbuf;
llvm::raw_svector_ostream os(sbuf);
StoreInfo SI = {StoreInfo::Assignment, StoreSite,
InitE,
V,
R,
OldRegion};
if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
const Stmt *S = PS->getStmt();
const auto *DS = dyn_cast<DeclStmt>(S);
const auto *VR = dyn_cast<VarRegion>(R);
if (DS) {
SI.StoreKind = StoreInfo::Initialization;
} else if (isa<BlockExpr>(S)) {
SI.StoreKind = StoreInfo::BlockCapture;
if (VR) {
ProgramStateRef State = StoreSite->getState();
SVal V = StoreSite->getSVal(S);
if (const auto *BDR =
dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
getParentTracker().track(State->getSVal(OriginalR), OriginalR,
Options, OriginSFC);
}
}
}
}
} else if (SI.StoreSite->getLocation().getAs<CallEnter>() &&
isa<VarRegion>(SI.Dest)) {
SI.StoreKind = StoreInfo::CallArgument;
}
return getParentTracker().handle(SI, BRC, Options);
}
void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
static int tag = 0;
ID.AddPointer(&tag);
ID.AddBoolean(Assumption);
ID.Add(Constraint);
}
const char *TrackConstraintBRVisitor::getTag() {
return "TrackConstraintBRVisitor";
}
bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
if (IsZeroCheck)
return N->getState()->isNull(Constraint).isUnderconstrained();
return (bool)N->getState()->assume(Constraint, !Assumption);
}
PathDiagnosticPieceRef TrackConstraintBRVisitor::VisitNode(
const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) {
const ExplodedNode *PrevN = N->getFirstPred();
if (IsSatisfied)
return nullptr;
if (!IsTrackingTurnedOn)
if (!isUnderconstrained(N))
IsTrackingTurnedOn = true;
if (!IsTrackingTurnedOn)
return nullptr;
if (isUnderconstrained(PrevN)) {
IsSatisfied = true;
assert(!isUnderconstrained(N));
SmallString<64> sbuf;
llvm::raw_svector_ostream os(sbuf);
if (isa<Loc>(Constraint)) {
os << "Assuming pointer value is ";
os << (Assumption ? "non-null" : "null");
}
if (os.str().empty())
return nullptr;
ProgramPoint P = N->getLocation();
if (isa_and_nonnull<NoteTag>(P.getTag()))
return nullptr;
PathDiagnosticLocation L =
PathDiagnosticLocation::create(P, BRC.getSourceManager());
if (!L.isValid())
return nullptr;
auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
X->setTag(getTag());
return std::move(X);
}
return nullptr;
}
SuppressInlineDefensiveChecksVisitor::
SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
: V(Value) {
AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
if (!Options.ShouldSuppressInlinedDefensiveChecks)
IsSatisfied = true;
}
void SuppressInlineDefensiveChecksVisitor::Profile(
llvm::FoldingSetNodeID &ID) const {
static int id = 0;
ID.AddPointer(&id);
ID.Add(V);
}
const char *SuppressInlineDefensiveChecksVisitor::getTag() {
return "IDCVisitor";
}
PathDiagnosticPieceRef
SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
const ExplodedNode *Pred = Succ->getFirstPred();
if (IsSatisfied)
return nullptr;
if (!IsTrackingTurnedOn)
if (Succ->getState()->isNull(V).isConstrainedTrue())
IsTrackingTurnedOn = true;
if (!IsTrackingTurnedOn)
return nullptr;
if (!Pred->getState()->isNull(V).isConstrainedTrue() &&
Succ->getState()->isNull(V).isConstrainedTrue()) {
IsSatisfied = true;
const LocationContext *CurLC = Succ->getLocationContext();
const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
BR.markInvalid("Suppress IDC", CurLC);
return nullptr;
}
auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
if (!BugPoint)
return nullptr;
ProgramPoint CurPoint = Succ->getLocation();
const Stmt *CurTerminatorStmt = nullptr;
if (auto BE = CurPoint.getAs<BlockEdge>()) {
CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
} else if (auto SP = CurPoint.getAs<StmtPoint>()) {
const Stmt *CurStmt = SP->getStmt();
if (!CurStmt->getBeginLoc().isMacroID())
return nullptr;
CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
} else {
return nullptr;
}
if (!CurTerminatorStmt)
return nullptr;
SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
if (TerminatorLoc.isMacroID()) {
SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
if (!BugLoc.isMacroID() ||
getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
BR.markInvalid("Suppress Macro IDC", CurLC);
}
return nullptr;
}
}
return nullptr;
}
namespace {
class TrackControlDependencyCondBRVisitor final
: public TrackingBugReporterVisitor {
const ExplodedNode *Origin;
ControlDependencyCalculator ControlDeps;
llvm::SmallSet<const CFGBlock *, 32> VisitedBlocks;
public:
TrackControlDependencyCondBRVisitor(TrackerRef ParentTracker,
const ExplodedNode *O)
: TrackingBugReporterVisitor(ParentTracker), Origin(O),
ControlDeps(&O->getCFG()) {}
void Profile(llvm::FoldingSetNodeID &ID) const override {
static int x = 0;
ID.AddPointer(&x);
}
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) override;
};
}
static std::shared_ptr<PathDiagnosticEventPiece>
constructDebugPieceForTrackedCondition(const Expr *Cond,
const ExplodedNode *N,
BugReporterContext &BRC) {
if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE ||
!BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
return nullptr;
std::string ConditionText = std::string(Lexer::getSourceText(
CharSourceRange::getTokenRange(Cond->getSourceRange()),
BRC.getSourceManager(), BRC.getASTContext().getLangOpts()));
return std::make_shared<PathDiagnosticEventPiece>(
PathDiagnosticLocation::createBegin(
Cond, BRC.getSourceManager(), N->getLocationContext()),
(Twine() + "Tracking condition '" + ConditionText + "'").str());
}
static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context) {
if (B->succ_size() != 2)
return false;
const CFGBlock *Then = B->succ_begin()->getReachableBlock();
const CFGBlock *Else = (B->succ_begin() + 1)->getReachableBlock();
if (!Then || !Else)
return false;
if (Then->isInevitablySinking() != Else->isInevitablySinking())
return true;
if (const Stmt *ElseCond = Else->getTerminatorCondition())
if (const auto *BinOp = dyn_cast<BinaryOperator>(ElseCond))
if (BinOp->isLogicalOp())
return isAssertlikeBlock(Else, Context);
return false;
}
PathDiagnosticPieceRef
TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
if (Origin->getStackFrame() != N->getStackFrame())
return nullptr;
CFGBlock *NB = const_cast<CFGBlock *>(N->getCFGBlock());
if (!VisitedBlocks.insert(NB).second)
return nullptr;
CFGBlock *OriginB = const_cast<CFGBlock *>(Origin->getCFGBlock());
if (!OriginB || !NB)
return nullptr;
if (isAssertlikeBlock(NB, BRC.getASTContext()))
return nullptr;
if (ControlDeps.isControlDependent(OriginB, NB)) {
if (llvm::isa_and_nonnull<CXXForRangeStmt>(NB->getTerminatorStmt()))
return nullptr;
if (const Expr *Condition = NB->getLastCondition()) {
const Expr *InnerExpr = peelOffOuterExpr(Condition, N);
if (!InnerExpr)
return nullptr;
if (isa<CallExpr>(InnerExpr))
return nullptr;
if (BR.addTrackedCondition(N)) {
getParentTracker().track(InnerExpr, N,
{bugreporter::TrackingKind::Condition,
false});
return constructDebugPieceForTrackedCondition(Condition, N, BRC);
}
}
}
return nullptr;
}
static const Expr *peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N) {
Ex = Ex->IgnoreParenCasts();
if (const auto *FE = dyn_cast<FullExpr>(Ex))
return peelOffOuterExpr(FE->getSubExpr(), N);
if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
return peelOffOuterExpr(OVE->getSourceExpr(), N);
if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
if (PropRef && PropRef->isMessagingGetter()) {
const Expr *GetterMessageSend =
POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
return peelOffOuterExpr(GetterMessageSend, N);
}
}
if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
const ExplodedNode *NI = N;
do {
ProgramPoint ProgPoint = NI->getLocation();
if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
const CFGBlock *srcBlk = BE->getSrc();
if (const Stmt *term = srcBlk->getTerminatorStmt()) {
if (term == CO) {
bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
if (TookTrueBranch)
return peelOffOuterExpr(CO->getTrueExpr(), N);
else
return peelOffOuterExpr(CO->getFalseExpr(), N);
}
}
}
NI = NI->getFirstPred();
} while (NI);
}
if (auto *BO = dyn_cast<BinaryOperator>(Ex))
if (const Expr *SubEx = peelOffPointerArithmetic(BO))
return peelOffOuterExpr(SubEx, N);
if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
if (UO->getOpcode() == UO_LNot)
return peelOffOuterExpr(UO->getSubExpr(), N);
if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
return peelOffOuterExpr(DerefEx, N);
}
return Ex;
}
static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
const Expr *Inner) {
while (N) {
if (N->getStmtForDiagnostics() == Inner)
return N;
N = N->getFirstPred();
}
return N;
}
PathDiagnosticPieceRef StoreHandler::constructNote(StoreInfo SI,
BugReporterContext &BRC,
StringRef NodeText) {
ProgramPoint P = SI.StoreSite->getLocation();
PathDiagnosticLocation L;
if (P.getAs<CallEnter>() && SI.SourceOfTheValue)
L = PathDiagnosticLocation(SI.SourceOfTheValue, BRC.getSourceManager(),
P.getLocationContext());
if (!L.isValid() || !L.asLocation().isValid())
L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
if (!L.isValid() || !L.asLocation().isValid())
return nullptr;
return std::make_shared<PathDiagnosticEventPiece>(L, NodeText);
}
class DefaultStoreHandler final : public StoreHandler {
public:
using StoreHandler::StoreHandler;
PathDiagnosticPieceRef handle(StoreInfo SI, BugReporterContext &BRC,
TrackingOptions Opts) override {
SmallString<256> Buffer;
llvm::raw_svector_ostream OS(Buffer);
switch (SI.StoreKind) {
case StoreInfo::Initialization:
case StoreInfo::BlockCapture:
showBRDiagnostics(OS, SI);
break;
case StoreInfo::CallArgument:
showBRParamDiagnostics(OS, SI);
break;
case StoreInfo::Assignment:
showBRDefaultDiagnostics(OS, SI);
break;
}
if (Opts.Kind == bugreporter::TrackingKind::Condition)
OS << WillBeUsedForACondition;
return constructNote(SI, BRC, OS.str());
}
};
class ControlDependencyHandler final : public ExpressionHandler {
public:
using ExpressionHandler::ExpressionHandler;
Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
const ExplodedNode *LVNode,
TrackingOptions Opts) override {
PathSensitiveBugReport &Report = getParentTracker().getReport();
if (LVNode->getState()
->getAnalysisManager()
.getAnalyzerOptions()
.ShouldTrackConditions) {
Report.addVisitor<TrackControlDependencyCondBRVisitor>(
&getParentTracker(), InputNode);
return {true};
}
return {};
}
};
class NilReceiverHandler final : public ExpressionHandler {
public:
using ExpressionHandler::ExpressionHandler;
Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
const ExplodedNode *LVNode,
TrackingOptions Opts) override {
if (const Expr *Receiver =
NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
return getParentTracker().track(Receiver, LVNode, Opts);
return {};
}
};
class ArrayIndexHandler final : public ExpressionHandler {
public:
using ExpressionHandler::ExpressionHandler;
Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
const ExplodedNode *LVNode,
TrackingOptions Opts) override {
if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
return getParentTracker().track(
Arr->getIdx(), LVNode,
{Opts.Kind, false});
return {};
}
};
class InterestingLValueHandler final : public ExpressionHandler {
public:
using ExpressionHandler::ExpressionHandler;
Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
const ExplodedNode *LVNode,
TrackingOptions Opts) override {
ProgramStateRef LVState = LVNode->getState();
const StackFrameContext *SFC = LVNode->getStackFrame();
PathSensitiveBugReport &Report = getParentTracker().getReport();
Tracker::Result Result;
if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
SVal LVal = LVNode->getSVal(Inner);
const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
if (RR && !LVIsNull)
Result.combineWith(getParentTracker().track(LVal, RR, Opts, SFC));
const MemRegion *R =
(RR && LVIsNull) ? RR : LVNode->getSVal(Inner).getAsRegion();
if (R) {
SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
Report.addVisitor<NoStoreFuncVisitor>(cast<SubRegion>(R), Opts.Kind);
Result.FoundSomethingToTrack = true;
Result.WasInterrupted = true;
MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
LVNode, R, Opts.EnableNullFPSuppression, Report, V);
Report.markInteresting(V, Opts.Kind);
Report.addVisitor<UndefOrNullArgVisitor>(R);
if (V.getAsLocSymbol(true))
if (LVState->isNull(V).isConstrainedTrue())
Report.addVisitor<TrackConstraintBRVisitor>(V.castAs<DefinedSVal>(),
false);
if (auto DV = V.getAs<DefinedSVal>())
if (!DV->isZeroConstant() && Opts.EnableNullFPSuppression)
Report.addVisitor<SuppressInlineDefensiveChecksVisitor>(*DV,
InputNode);
getParentTracker().track(V, R, Opts, SFC);
}
}
return Result;
}
};
class InlinedFunctionCallHandler final : public ExpressionHandler {
using ExpressionHandler::ExpressionHandler;
Tracker::Result handle(const Expr *E, const ExplodedNode *InputNode,
const ExplodedNode *ExprNode,
TrackingOptions Opts) override {
if (!CallEvent::isCallStmt(E))
return {};
const bool BypassCXXNewExprEval = isa<CXXNewExpr>(E);
const StackFrameContext *CurrentSFC = ExprNode->getStackFrame();
do {
if (Optional<CallExitEnd> CEE = ExprNode->getLocationAs<CallExitEnd>())
if (CEE->getCalleeContext()->getCallSite() == E)
break;
ExprNode = ExprNode->getFirstPred();
if (!ExprNode)
break;
const StackFrameContext *PredSFC = ExprNode->getStackFrame();
if (!BypassCXXNewExprEval)
if (Optional<StmtPoint> SP = ExprNode->getLocationAs<StmtPoint>())
if (SP->getStmt() == E && CurrentSFC == PredSFC)
break;
CurrentSFC = PredSFC;
} while (ExprNode->getStackFrame() == CurrentSFC);
while (ExprNode && ExprNode->getLocation().getAs<PostStmt>())
ExprNode = ExprNode->getFirstPred();
if (!ExprNode)
return {};
Optional<CallExitEnd> CEE = ExprNode->getLocationAs<CallExitEnd>();
if (!CEE)
return {};
const StackFrameContext *CalleeContext = CEE->getCalleeContext();
if (CalleeContext->getCallSite() != E)
return {};
ProgramStateRef State = ExprNode->getState();
SVal RetVal = ExprNode->getSVal(E);
if (cast<Expr>(E)->isGLValue())
if (Optional<Loc> LValue = RetVal.getAs<Loc>())
RetVal = State->getSVal(*LValue);
AnalyzerOptions &Options = State->getAnalysisManager().options;
bool EnableNullFPSuppression = false;
if (Opts.EnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths)
if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
PathSensitiveBugReport &Report = getParentTracker().getReport();
Report.addVisitor<ReturnVisitor>(&getParentTracker(), CalleeContext,
EnableNullFPSuppression, Options,
Opts.Kind);
return {true};
}
};
class DefaultExpressionHandler final : public ExpressionHandler {
public:
using ExpressionHandler::ExpressionHandler;
Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
const ExplodedNode *LVNode,
TrackingOptions Opts) override {
ProgramStateRef LVState = LVNode->getState();
const StackFrameContext *SFC = LVNode->getStackFrame();
PathSensitiveBugReport &Report = getParentTracker().getReport();
Tracker::Result Result;
SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
if (auto L = V.getAs<loc::MemRegionVal>()) {
bool CanDereference = true;
if (const auto *SR = L->getRegionAs<SymbolicRegion>()) {
if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
CanDereference = false;
} else if (L->getRegionAs<AllocaRegion>())
CanDereference = false;
SVal RVal;
if (ExplodedGraph::isInterestingLValueExpr(Inner))
RVal = LVState->getRawSVal(*L, Inner->getType());
else if (CanDereference)
RVal = LVState->getSVal(L->getRegion());
if (CanDereference) {
Report.addVisitor<UndefOrNullArgVisitor>(L->getRegion());
Result.FoundSomethingToTrack = true;
if (auto KV = RVal.getAs<KnownSVal>())
Result.combineWith(
getParentTracker().track(*KV, L->getRegion(), Opts, SFC));
}
const MemRegion *RegionRVal = RVal.getAsRegion();
if (isa_and_nonnull<SymbolicRegion>(RegionRVal)) {
Report.markInteresting(RegionRVal, Opts.Kind);
Report.addVisitor<TrackConstraintBRVisitor>(
loc::MemRegionVal(RegionRVal),
false);
Result.FoundSomethingToTrack = true;
}
}
return Result;
}
};
class PRValueHandler final : public ExpressionHandler {
public:
using ExpressionHandler::ExpressionHandler;
Tracker::Result handle(const Expr *E, const ExplodedNode *InputNode,
const ExplodedNode *ExprNode,
TrackingOptions Opts) override {
if (!E->isPRValue())
return {};
const ExplodedNode *RVNode = findNodeForExpression(ExprNode, E);
if (!RVNode)
return {};
ProgramStateRef RVState = RVNode->getState();
SVal V = RVState->getSValAsScalarOrLoc(E, RVNode->getLocationContext());
const auto *BO = dyn_cast<BinaryOperator>(E);
if (!BO || !BO->isMultiplicativeOp() || !V.isZeroConstant())
return {};
SVal RHSV = RVState->getSVal(BO->getRHS(), RVNode->getLocationContext());
SVal LHSV = RVState->getSVal(BO->getLHS(), RVNode->getLocationContext());
Tracker::Result CombinedResult;
Tracker &Parent = getParentTracker();
const auto track = [&CombinedResult, &Parent, ExprNode, Opts](Expr *Inner) {
CombinedResult.combineWith(Parent.track(Inner, ExprNode, Opts));
};
if (BO->getOpcode() == BO_Mul) {
if (LHSV.isZeroConstant())
track(BO->getLHS());
if (RHSV.isZeroConstant())
track(BO->getRHS());
} else { if (LHSV.isZeroConstant())
track(BO->getLHS());
}
return CombinedResult;
}
};
Tracker::Tracker(PathSensitiveBugReport &Report) : Report(Report) {
addLowPriorityHandler<ControlDependencyHandler>();
addLowPriorityHandler<NilReceiverHandler>();
addLowPriorityHandler<ArrayIndexHandler>();
addLowPriorityHandler<InterestingLValueHandler>();
addLowPriorityHandler<InlinedFunctionCallHandler>();
addLowPriorityHandler<DefaultExpressionHandler>();
addLowPriorityHandler<PRValueHandler>();
addHighPriorityHandler<DefaultStoreHandler>();
}
Tracker::Result Tracker::track(const Expr *E, const ExplodedNode *N,
TrackingOptions Opts) {
if (!E || !N)
return {};
const Expr *Inner = peelOffOuterExpr(E, N);
const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
if (!LVNode)
return {};
Result CombinedResult;
for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
CombinedResult.combineWith(Handler->handle(Inner, N, LVNode, Opts));
if (CombinedResult.WasInterrupted) {
CombinedResult.WasInterrupted = false;
break;
}
}
return CombinedResult;
}
Tracker::Result Tracker::track(SVal V, const MemRegion *R, TrackingOptions Opts,
const StackFrameContext *Origin) {
if (auto KV = V.getAs<KnownSVal>()) {
Report.addVisitor<StoreSiteFinder>(this, *KV, R, Opts, Origin);
return {true};
}
return {};
}
PathDiagnosticPieceRef Tracker::handle(StoreInfo SI, BugReporterContext &BRC,
TrackingOptions Opts) {
for (StoreHandlerPtr &Handler : StoreHandlers) {
if (PathDiagnosticPieceRef Result = Handler->handle(SI, BRC, Opts))
return Result;
}
return {};
}
bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
const Expr *E,
PathSensitiveBugReport &Report,
TrackingOptions Opts) {
return Tracker::create(Report)
->track(E, InputNode, Opts)
.FoundSomethingToTrack;
}
void bugreporter::trackStoredValue(KnownSVal V, const MemRegion *R,
PathSensitiveBugReport &Report,
TrackingOptions Opts,
const StackFrameContext *Origin) {
Tracker::create(Report)->track(V, R, Opts, Origin);
}
const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
const ExplodedNode *N) {
const auto *ME = dyn_cast<ObjCMessageExpr>(S);
if (!ME)
return nullptr;
if (const Expr *Receiver = ME->getInstanceReceiver()) {
ProgramStateRef state = N->getState();
SVal V = N->getSVal(Receiver);
if (state->isNull(V).isConstrainedTrue())
return Receiver;
}
return nullptr;
}
PathDiagnosticPieceRef
NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
Optional<PreStmt> P = N->getLocationAs<PreStmt>();
if (!P)
return nullptr;
const Stmt *S = P->getStmt();
const Expr *Receiver = getNilReceiver(S, N);
if (!Receiver)
return nullptr;
llvm::SmallString<256> Buf;
llvm::raw_svector_ostream OS(Buf);
if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
OS << "'";
ME->getSelector().print(OS);
OS << "' not called";
}
else {
OS << "No method is called";
}
OS << " because the receiver is nil";
bugreporter::trackExpressionValue(N, Receiver, BR,
{bugreporter::TrackingKind::Thorough,
false});
PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
N->getLocationContext());
return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
}
const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; }
PathDiagnosticPieceRef
ConditionBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
auto piece = VisitNodeImpl(N, BRC, BR);
if (piece) {
piece->setTag(getTag());
if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
ev->setPrunable(true, false);
}
return piece;
}
PathDiagnosticPieceRef
ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
ProgramPoint ProgPoint = N->getLocation();
const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
const CFGBlock *SrcBlock = BE->getSrc();
if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
const ProgramPointTag *PreviousNodeTag =
N->getFirstPred()->getLocation().getTag();
if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second)
return nullptr;
return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
}
return nullptr;
}
if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
const ProgramPointTag *CurrentNodeTag = PS->getTag();
if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second)
return nullptr;
bool TookTrue = CurrentNodeTag == Tags.first;
return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
}
return nullptr;
}
PathDiagnosticPieceRef ConditionBRVisitor::VisitTerminator(
const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
const CFGBlock *dstBlk, PathSensitiveBugReport &R,
BugReporterContext &BRC) {
const Expr *Cond = nullptr;
switch (Term->getStmtClass()) {
default:
return nullptr;
case Stmt::IfStmtClass:
Cond = cast<IfStmt>(Term)->getCond();
break;
case Stmt::ConditionalOperatorClass:
Cond = cast<ConditionalOperator>(Term)->getCond();
break;
case Stmt::BinaryOperatorClass:
const auto *BO = cast<BinaryOperator>(Term);
assert(BO->isLogicalOp() &&
"CFG terminator is not a short-circuit operator!");
Cond = BO->getLHS();
break;
}
Cond = Cond->IgnoreParens();
while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
if (!InnerBO->isLogicalOp())
break;
Cond = InnerBO->getRHS()->IgnoreParens();
}
assert(Cond);
assert(srcBlk->succ_size() == 2);
const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
return VisitTrueTest(Cond, BRC, R, N, TookTrue);
}
PathDiagnosticPieceRef
ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC,
PathSensitiveBugReport &R,
const ExplodedNode *N, bool TookTrue) {
ProgramStateRef CurrentState = N->getState();
ProgramStateRef PrevState = N->getFirstPred()->getState();
const LocationContext *LCtx = N->getLocationContext();
bool IsAssuming =
!BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef();
const Expr *CondTmp = Cond;
bool TookTrueTmp = TookTrue;
while (true) {
CondTmp = CondTmp->IgnoreParenCasts();
switch (CondTmp->getStmtClass()) {
default:
break;
case Stmt::BinaryOperatorClass:
if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
BRC, R, N, TookTrueTmp, IsAssuming))
return P;
break;
case Stmt::DeclRefExprClass:
if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
BRC, R, N, TookTrueTmp, IsAssuming))
return P;
break;
case Stmt::MemberExprClass:
if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
BRC, R, N, TookTrueTmp, IsAssuming))
return P;
break;
case Stmt::UnaryOperatorClass: {
const auto *UO = cast<UnaryOperator>(CondTmp);
if (UO->getOpcode() == UO_LNot) {
TookTrueTmp = !TookTrueTmp;
CondTmp = UO->getSubExpr();
continue;
}
break;
}
}
break;
}
if (!IsAssuming)
return nullptr;
PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
if (!Loc.isValid() || !Loc.asLocation().isValid())
return nullptr;
return std::make_shared<PathDiagnosticEventPiece>(
Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage);
}
bool ConditionBRVisitor::patternMatch(const Expr *Ex,
const Expr *ParentEx,
raw_ostream &Out,
BugReporterContext &BRC,
PathSensitiveBugReport &report,
const ExplodedNode *N,
Optional<bool> &prunable,
bool IsSameFieldName) {
const Expr *OriginalExpr = Ex;
Ex = Ex->IgnoreParenCasts();
if (isa<GNUNullExpr, ObjCBoolLiteralExpr, CXXBoolLiteralExpr, IntegerLiteral,
FloatingLiteral>(Ex)) {
SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
SourceLocation EndLoc = OriginalExpr->getEndLoc();
if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
const SourceManager &SM = BRC.getSourceManager();
const LangOptions &LO = BRC.getASTContext().getLangOpts();
if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
Out << Lexer::getSourceText(R, SM, LO);
return false;
}
}
}
if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
const bool quotes = isa<VarDecl>(DR->getDecl());
if (quotes) {
Out << '\'';
const LocationContext *LCtx = N->getLocationContext();
const ProgramState *state = N->getState().get();
if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
LCtx).getAsRegion()) {
if (report.isInteresting(R))
prunable = false;
else {
const ProgramState *state = N->getState().get();
SVal V = state->getSVal(R);
if (report.isInteresting(V))
prunable = false;
}
}
}
Out << DR->getDecl()->getDeclName().getAsString();
if (quotes)
Out << '\'';
return quotes;
}
if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
QualType OriginalTy = OriginalExpr->getType();
if (OriginalTy->isPointerType()) {
if (IL->getValue() == 0) {
Out << "null";
return false;
}
}
else if (OriginalTy->isObjCObjectPointerType()) {
if (IL->getValue() == 0) {
Out << "nil";
return false;
}
}
Out << IL->getValue();
return false;
}
if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
if (!IsSameFieldName)
Out << "field '" << ME->getMemberDecl()->getName() << '\'';
else
Out << '\''
<< Lexer::getSourceText(
CharSourceRange::getTokenRange(Ex->getSourceRange()),
BRC.getSourceManager(), BRC.getASTContext().getLangOpts(),
nullptr)
<< '\'';
}
return false;
}
PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue,
bool IsAssuming) {
bool shouldInvert = false;
Optional<bool> shouldPrune;
bool IsSameFieldName = false;
const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts());
const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts());
if (LhsME && RhsME)
IsSameFieldName =
LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName();
SmallString<128> LhsString, RhsString;
{
llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
N, shouldPrune, IsSameFieldName);
const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
N, shouldPrune, IsSameFieldName);
shouldInvert = !isVarLHS && isVarRHS;
}
BinaryOperator::Opcode Op = BExpr->getOpcode();
if (BinaryOperator::isAssignmentOp(Op)) {
return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
TookTrue);
}
if (LhsString.empty() || RhsString.empty() ||
!BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
return nullptr;
SmallString<256> buf;
llvm::raw_svector_ostream Out(buf);
Out << (IsAssuming ? "Assuming " : "")
<< (shouldInvert ? RhsString : LhsString) << " is ";
if (shouldInvert)
switch (Op) {
default: break;
case BO_LT: Op = BO_GT; break;
case BO_GT: Op = BO_LT; break;
case BO_LE: Op = BO_GE; break;
case BO_GE: Op = BO_LE; break;
}
if (!TookTrue)
switch (Op) {
case BO_EQ: Op = BO_NE; break;
case BO_NE: Op = BO_EQ; break;
case BO_LT: Op = BO_GE; break;
case BO_GT: Op = BO_LE; break;
case BO_LE: Op = BO_GT; break;
case BO_GE: Op = BO_LT; break;
default:
return nullptr;
}
switch (Op) {
case BO_EQ:
Out << "equal to ";
break;
case BO_NE:
Out << "not equal to ";
break;
default:
Out << BinaryOperator::getOpcodeStr(Op) << ' ';
break;
}
Out << (shouldInvert ? LhsString : RhsString);
const LocationContext *LCtx = N->getLocationContext();
const SourceManager &SM = BRC.getSourceManager();
if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) ||
isVarAnInterestingCondition(BExpr->getRHS(), N, &R))
Out << WillBeUsedForACondition;
std::string Message = std::string(Out.str());
Message[0] = toupper(Message[0]);
if (!IsAssuming) {
PathDiagnosticLocation Loc;
if (!shouldInvert) {
if (LhsME && LhsME->getMemberLoc().isValid())
Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM);
else
Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, LCtx);
} else {
if (RhsME && RhsME->getMemberLoc().isValid())
Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM);
else
Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, LCtx);
}
return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
}
PathDiagnosticLocation Loc(Cond, SM, LCtx);
auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
if (shouldPrune)
event->setPrunable(shouldPrune.value());
return event;
}
PathDiagnosticPieceRef ConditionBRVisitor::VisitConditionVariable(
StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) {
SmallString<256> buf;
llvm::raw_svector_ostream Out(buf);
Out << "Assuming " << LhsString << " is ";
if (!printValue(CondVarExpr, Out, N, TookTrue, true))
return nullptr;
const LocationContext *LCtx = N->getLocationContext();
PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
if (isVarAnInterestingCondition(CondVarExpr, N, &report))
Out << WillBeUsedForACondition;
auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
if (isInterestingExpr(CondVarExpr, N, &report))
event->setPrunable(false);
return event;
}
PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
bool IsAssuming) {
const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
if (!VD)
return nullptr;
SmallString<256> Buf;
llvm::raw_svector_ostream Out(Buf);
Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is ";
if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
return nullptr;
const LocationContext *LCtx = N->getLocationContext();
if (isVarAnInterestingCondition(DRE, N, &report))
Out << WillBeUsedForACondition;
if (!IsAssuming) {
PathDiagnosticLocation Loc(DRE, BRC.getSourceManager(), LCtx);
return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
}
PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
if (isInterestingExpr(DRE, N, &report))
event->setPrunable(false);
return std::move(event);
}
PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
bool IsAssuming) {
SmallString<256> Buf;
llvm::raw_svector_ostream Out(Buf);
Out << (IsAssuming ? "Assuming field '" : "Field '")
<< ME->getMemberDecl()->getName() << "' is ";
if (!printValue(ME, Out, N, TookTrue, IsAssuming))
return nullptr;
const LocationContext *LCtx = N->getLocationContext();
PathDiagnosticLocation Loc;
if (!IsAssuming && ME->getMemberLoc().isValid())
Loc = PathDiagnosticLocation(ME->getMemberLoc(), BRC.getSourceManager());
else
Loc = PathDiagnosticLocation(Cond, BRC.getSourceManager(), LCtx);
if (!Loc.isValid() || !Loc.asLocation().isValid())
return nullptr;
if (isVarAnInterestingCondition(ME, N, &report))
Out << WillBeUsedForACondition;
if (!IsAssuming)
return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
if (isInterestingExpr(ME, N, &report))
event->setPrunable(false);
return event;
}
bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
const ExplodedNode *N, bool TookTrue,
bool IsAssuming) {
QualType Ty = CondVarExpr->getType();
if (Ty->isPointerType()) {
Out << (TookTrue ? "non-null" : "null");
return true;
}
if (Ty->isObjCObjectPointerType()) {
Out << (TookTrue ? "non-nil" : "nil");
return true;
}
if (!Ty->isIntegralOrEnumerationType())
return false;
Optional<const llvm::APSInt *> IntValue;
if (!IsAssuming)
IntValue = getConcreteIntegerValue(CondVarExpr, N);
if (IsAssuming || !IntValue) {
if (Ty->isBooleanType())
Out << (TookTrue ? "true" : "false");
else
Out << (TookTrue ? "not equal to 0" : "0");
} else {
if (Ty->isBooleanType())
Out << (IntValue.value()->getBoolValue() ? "true" : "false");
else
Out << *IntValue.value();
}
return true;
}
constexpr llvm::StringLiteral ConditionBRVisitor::GenericTrueMessage;
constexpr llvm::StringLiteral ConditionBRVisitor::GenericFalseMessage;
bool ConditionBRVisitor::isPieceMessageGeneric(
const PathDiagnosticPiece *Piece) {
return Piece->getString() == GenericTrueMessage ||
Piece->getString() == GenericFalseMessage;
}
void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
BugReporterContext &BRC, const ExplodedNode *N,
PathSensitiveBugReport &BR) {
const AnalyzerOptions &Options = BRC.getAnalyzerOptions();
const Decl *D = N->getLocationContext()->getDecl();
if (AnalysisDeclContext::isInStdNamespace(D)) {
if (Options.ShouldSuppressFromCXXStandardLibrary) {
BR.markInvalid(getTag(), nullptr);
return;
} else {
if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
const CXXRecordDecl *CD = MD->getParent();
if (CD->getName() == "list") {
BR.markInvalid(getTag(), nullptr);
return;
}
}
if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
const CXXRecordDecl *CD = MD->getParent();
if (CD->getName() == "__independent_bits_engine") {
BR.markInvalid(getTag(), nullptr);
return;
}
}
for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
LCtx = LCtx->getParent()) {
const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
if (!MD)
continue;
const CXXRecordDecl *CD = MD->getParent();
if (CD->getName() == "basic_string") {
BR.markInvalid(getTag(), nullptr);
return;
}
if (CD->getName() == "shared_ptr") {
BR.markInvalid(getTag(), nullptr);
return;
}
}
}
}
const SourceManager &SM = BRC.getSourceManager();
FullSourceLoc Loc = BR.getLocation().asLocation();
while (Loc.isMacroID()) {
Loc = Loc.getSpellingLoc();
if (SM.getFilename(Loc).endswith("sys/queue.h")) {
BR.markInvalid(getTag(), nullptr);
return;
}
}
}
PathDiagnosticPieceRef
UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
ProgramStateRef State = N->getState();
ProgramPoint ProgLoc = N->getLocation();
Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
if (!CEnter)
return nullptr;
CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
unsigned Idx = 0;
ArrayRef<ParmVarDecl *> parms = Call->parameters();
for (const auto ParamDecl : parms) {
const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
++Idx;
if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
continue;
assert(ParamDecl && "Formal parameter has no decl?");
QualType T = ParamDecl->getType();
if (!(T->isAnyPointerType() || T->isReferenceType())) {
continue;
}
if (T->getPointeeType().isConstQualified())
continue;
SVal BoundVal = State->getSVal(R);
if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
BR.markInteresting(CEnter->getCalleeContext());
return nullptr;
}
}
return nullptr;
}
FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
: Constraints(ConstraintMap::Factory().getEmptyMap()) {}
void FalsePositiveRefutationBRVisitor::finalizeVisitor(
BugReporterContext &BRC, const ExplodedNode *EndPathNode,
PathSensitiveBugReport &BR) {
addConstraints(EndPathNode, true);
llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
ASTContext &Ctx = BRC.getASTContext();
for (const auto &I : Constraints) {
const SymbolRef Sym = I.first;
auto RangeIt = I.second.begin();
llvm::SMTExprRef SMTConstraints = SMTConv::getRangeExpr(
RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
true);
while ((++RangeIt) != I.second.end()) {
SMTConstraints = RefutationSolver->mkOr(
SMTConstraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
RangeIt->From(), RangeIt->To(),
true));
}
RefutationSolver->addConstraint(SMTConstraints);
}
Optional<bool> IsSAT = RefutationSolver->check();
if (!IsSAT)
return;
if (!IsSAT.value())
BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
}
void FalsePositiveRefutationBRVisitor::addConstraints(
const ExplodedNode *N, bool OverwriteConstraintsOnExistingSyms) {
ConstraintMap NewCs = getConstraintMap(N->getState());
ConstraintMap::Factory &CF = N->getState()->get_context<ConstraintMap>();
for (auto const &C : NewCs) {
const SymbolRef &Sym = C.first;
if (!Constraints.contains(Sym)) {
Constraints = CF.add(Constraints, Sym, C.second);
} else if (OverwriteConstraintsOnExistingSyms) {
Constraints = CF.remove(Constraints, Sym);
Constraints = CF.add(Constraints, Sym, C.second);
}
}
}
PathDiagnosticPieceRef FalsePositiveRefutationBRVisitor::VisitNode(
const ExplodedNode *N, BugReporterContext &, PathSensitiveBugReport &) {
addConstraints(N, false);
return nullptr;
}
void FalsePositiveRefutationBRVisitor::Profile(
llvm::FoldingSetNodeID &ID) const {
static int Tag = 0;
ID.AddPointer(&Tag);
}
int NoteTag::Kind = 0;
void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
static int Tag = 0;
ID.AddPointer(&Tag);
}
PathDiagnosticPieceRef TagVisitor::VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &R) {
ProgramPoint PP = N->getLocation();
const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
if (!T)
return nullptr;
if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
PathDiagnosticLocation Loc =
PathDiagnosticLocation::create(PP, BRC.getSourceManager());
auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
Piece->setPrunable(T->isPrunable());
return Piece;
}
return nullptr;
}