#include "clang/AST/Attr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Driver/DriverDiagnostic.h"
#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/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "llvm/ADT/StringSet.h"
using namespace clang;
using namespace ento;
namespace {
struct RegionState {
private:
enum Kind { Moved, Reported } K;
RegionState(Kind InK) : K(InK) {}
public:
bool isReported() const { return K == Reported; }
bool isMoved() const { return K == Moved; }
static RegionState getReported() { return RegionState(Reported); }
static RegionState getMoved() { return RegionState(Moved); }
bool operator==(const RegionState &X) const { return K == X.K; }
void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
};
}
namespace {
class MoveChecker
: public Checker<check::PreCall, check::PostCall,
check::DeadSymbols, check::RegionChanges> {
public:
void checkPreCall(const CallEvent &MC, CheckerContext &C) const;
void checkPostCall(const CallEvent &MC, CheckerContext &C) const;
void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
ProgramStateRef
checkRegionChanges(ProgramStateRef State,
const InvalidatedSymbols *Invalidated,
ArrayRef<const MemRegion *> RequestedRegions,
ArrayRef<const MemRegion *> InvalidatedRegions,
const LocationContext *LCtx, const CallEvent *Call) const;
void printState(raw_ostream &Out, ProgramStateRef State,
const char *NL, const char *Sep) const override;
private:
enum MisuseKind { MK_FunCall, MK_Copy, MK_Move, MK_Dereference };
enum StdObjectKind { SK_NonStd, SK_Unsafe, SK_Safe, SK_SmartPtr };
enum AggressivenessKind { AK_Invalid = -1,
AK_KnownsOnly = 0, AK_KnownsAndLocals = 1, AK_All = 2, AK_NumKinds = AK_All
};
static bool misuseCausesCrash(MisuseKind MK) {
return MK == MK_Dereference;
}
struct ObjectKind {
bool IsLocal;
StdObjectKind StdKind;
};
const llvm::StringSet<> StdSmartPtrClasses = {
"shared_ptr",
"unique_ptr",
"weak_ptr",
};
const llvm::StringSet<> StdSafeClasses = {
"basic_filebuf",
"basic_ios",
"future",
"optional",
"packaged_task",
"promise",
"shared_future",
"shared_lock",
"thread",
"unique_lock",
};
bool shouldBeTracked(ObjectKind OK) const {
return (Aggressiveness == AK_All) ||
(Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
OK.StdKind == SK_Unsafe || OK.StdKind == SK_SmartPtr;
}
bool shouldWarnAbout(ObjectKind OK, MisuseKind MK) const {
return shouldBeTracked(OK) &&
((Aggressiveness == AK_All) ||
(Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
OK.StdKind != SK_SmartPtr || MK == MK_Dereference);
}
ObjectKind classifyObject(const MemRegion *MR, const CXXRecordDecl *RD) const;
void explainObject(llvm::raw_ostream &OS, const MemRegion *MR,
const CXXRecordDecl *RD, MisuseKind MK) const;
bool belongsTo(const CXXRecordDecl *RD, const llvm::StringSet<> &Set) const;
class MovedBugVisitor : public BugReporterVisitor {
public:
MovedBugVisitor(const MoveChecker &Chk, const MemRegion *R,
const CXXRecordDecl *RD, MisuseKind MK)
: Chk(Chk), Region(R), RD(RD), MK(MK), Found(false) {}
void Profile(llvm::FoldingSetNodeID &ID) const override {
static int X = 0;
ID.AddPointer(&X);
ID.AddPointer(Region);
}
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) override;
private:
const MoveChecker &Chk;
const MemRegion *Region;
const CXXRecordDecl *RD;
const MisuseKind MK;
bool Found;
};
AggressivenessKind Aggressiveness;
public:
void setAggressiveness(StringRef Str, CheckerManager &Mgr) {
Aggressiveness =
llvm::StringSwitch<AggressivenessKind>(Str)
.Case("KnownsOnly", AK_KnownsOnly)
.Case("KnownsAndLocals", AK_KnownsAndLocals)
.Case("All", AK_All)
.Default(AK_Invalid);
if (Aggressiveness == AK_Invalid)
Mgr.reportInvalidCheckerOptionValue(this, "WarnOn",
"either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value");
};
private:
BugType BT{this, "Use-after-move", categories::CXXMoveSemantics};
void modelUse(ProgramStateRef State, const MemRegion *Region,
const CXXRecordDecl *RD, MisuseKind MK,
CheckerContext &C) const;
ExplodedNode *reportBug(const MemRegion *Region, const CXXRecordDecl *RD,
CheckerContext &C, MisuseKind MK) const;
bool isInMoveSafeContext(const LocationContext *LC) const;
bool isStateResetMethod(const CXXMethodDecl *MethodDec) const;
bool isMoveSafeMethod(const CXXMethodDecl *MethodDec) const;
const ExplodedNode *getMoveLocation(const ExplodedNode *N,
const MemRegion *Region,
CheckerContext &C) const;
};
}
REGISTER_MAP_WITH_PROGRAMSTATE(TrackedRegionMap, const MemRegion *, RegionState)
namespace clang {
namespace ento {
namespace move {
bool isMovedFrom(ProgramStateRef State, const MemRegion *Region) {
const RegionState *RS = State->get<TrackedRegionMap>(Region);
return RS && (RS->isMoved() || RS->isReported());
}
} } }
static ProgramStateRef removeFromState(ProgramStateRef State,
const MemRegion *Region) {
if (!Region)
return State;
for (auto &E : State->get<TrackedRegionMap>()) {
if (E.first->isSubRegionOf(Region))
State = State->remove<TrackedRegionMap>(E.first);
}
return State;
}
static bool isAnyBaseRegionReported(ProgramStateRef State,
const MemRegion *Region) {
for (auto &E : State->get<TrackedRegionMap>()) {
if (Region->isSubRegionOf(E.first) && E.second.isReported())
return true;
}
return false;
}
static const MemRegion *unwrapRValueReferenceIndirection(const MemRegion *MR) {
if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) {
SymbolRef Sym = SR->getSymbol();
if (Sym->getType()->isRValueReferenceType())
if (const MemRegion *OriginMR = Sym->getOriginRegion())
return OriginMR;
}
return MR;
}
PathDiagnosticPieceRef
MoveChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
if (Found)
return nullptr;
ProgramStateRef State = N->getState();
ProgramStateRef StatePrev = N->getFirstPred()->getState();
const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
const RegionState *TrackedObjectPrev =
StatePrev->get<TrackedRegionMap>(Region);
if (!TrackedObject)
return nullptr;
if (TrackedObjectPrev && TrackedObject)
return nullptr;
const Stmt *S = N->getStmtForDiagnostics();
if (!S)
return nullptr;
Found = true;
SmallString<128> Str;
llvm::raw_svector_ostream OS(Str);
ObjectKind OK = Chk.classifyObject(Region, RD);
switch (OK.StdKind) {
case SK_SmartPtr:
if (MK == MK_Dereference) {
OS << "Smart pointer";
Chk.explainObject(OS, Region, RD, MK);
OS << " is reset to null when moved from";
break;
}
LLVM_FALLTHROUGH;
case SK_NonStd:
case SK_Safe:
OS << "Object";
Chk.explainObject(OS, Region, RD, MK);
OS << " is moved";
break;
case SK_Unsafe:
OS << "Object";
Chk.explainObject(OS, Region, RD, MK);
OS << " is left in a valid but unspecified state after move";
break;
}
PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
N->getLocationContext());
return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true);
}
const ExplodedNode *MoveChecker::getMoveLocation(const ExplodedNode *N,
const MemRegion *Region,
CheckerContext &C) const {
const ExplodedNode *MoveNode = N;
while (N) {
ProgramStateRef State = N->getState();
if (!State->get<TrackedRegionMap>(Region))
break;
MoveNode = N;
N = N->pred_empty() ? nullptr : *(N->pred_begin());
}
return MoveNode;
}
void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region,
const CXXRecordDecl *RD, MisuseKind MK,
CheckerContext &C) const {
assert(!C.isDifferent() && "No transitions should have been made by now");
const RegionState *RS = State->get<TrackedRegionMap>(Region);
ObjectKind OK = classifyObject(Region, RD);
if (MK == MK_Dereference && OK.StdKind != SK_SmartPtr)
MK = MK_FunCall;
if (!RS || !shouldWarnAbout(OK, MK)
|| isInMoveSafeContext(C.getLocationContext())) {
C.addTransition(State);
return;
}
if (isAnyBaseRegionReported(State, Region)) {
if (misuseCausesCrash(MK)) {
C.generateSink(State, C.getPredecessor());
} else {
C.addTransition(State);
}
return;
}
ExplodedNode *N = reportBug(Region, RD, C, MK);
if (N->isSink())
return;
State = State->set<TrackedRegionMap>(Region, RegionState::getReported());
C.addTransition(State, N);
}
ExplodedNode *MoveChecker::reportBug(const MemRegion *Region,
const CXXRecordDecl *RD, CheckerContext &C,
MisuseKind MK) const {
if (ExplodedNode *N = misuseCausesCrash(MK) ? C.generateErrorNode()
: C.generateNonFatalErrorNode()) {
PathDiagnosticLocation LocUsedForUniqueing;
const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
if (const Stmt *MoveStmt = MoveNode->getStmtForDiagnostics())
LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
llvm::SmallString<128> Str;
llvm::raw_svector_ostream OS(Str);
switch(MK) {
case MK_FunCall:
OS << "Method called on moved-from object";
explainObject(OS, Region, RD, MK);
break;
case MK_Copy:
OS << "Moved-from object";
explainObject(OS, Region, RD, MK);
OS << " is copied";
break;
case MK_Move:
OS << "Moved-from object";
explainObject(OS, Region, RD, MK);
OS << " is moved";
break;
case MK_Dereference:
OS << "Dereference of null smart pointer";
explainObject(OS, Region, RD, MK);
break;
}
auto R = std::make_unique<PathSensitiveBugReport>(
BT, OS.str(), N, LocUsedForUniqueing,
MoveNode->getLocationContext()->getDecl());
R->addVisitor(std::make_unique<MovedBugVisitor>(*this, Region, RD, MK));
C.emitReport(std::move(R));
return N;
}
return nullptr;
}
void MoveChecker::checkPostCall(const CallEvent &Call,
CheckerContext &C) const {
const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
if (!AFC)
return;
ProgramStateRef State = C.getState();
const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
if (!MethodDecl)
return;
const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
return;
if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
return;
const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
if (!ArgRegion)
return;
const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
return;
if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
return;
const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
if (BaseRegion->getAs<CXXTempObjectRegion>() ||
AFC->getArgExpr(0)->isPRValue())
return;
if (State->get<TrackedRegionMap>(ArgRegion))
return;
const CXXRecordDecl *RD = MethodDecl->getParent();
ObjectKind OK = classifyObject(ArgRegion, RD);
if (shouldBeTracked(OK)) {
State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
C.addTransition(State);
return;
}
assert(!C.isDifferent() && "Should not have made transitions on this path!");
}
bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const {
if (const auto *ConversionDec =
dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
if (!Tp)
return false;
if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType())
return true;
}
return (MethodDec && MethodDec->getDeclName().isIdentifier() &&
(MethodDec->getName().lower() == "empty" ||
MethodDec->getName().lower() == "isempty"));
}
bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const {
if (!MethodDec)
return false;
if (MethodDec->hasAttr<ReinitializesAttr>())
return true;
if (MethodDec->getDeclName().isIdentifier()) {
std::string MethodName = MethodDec->getName().lower();
if (MethodName == "assign" || MethodName == "clear" ||
MethodName == "destroy" || MethodName == "reset" ||
MethodName == "resize" || MethodName == "shrink")
return true;
}
return false;
}
bool MoveChecker::isInMoveSafeContext(const LocationContext *LC) const {
do {
const auto *CtxDec = LC->getDecl();
auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
(MethodDec && MethodDec->isOverloadedOperator() &&
MethodDec->getOverloadedOperator() == OO_Equal) ||
isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec))
return true;
} while ((LC = LC->getParent()));
return false;
}
bool MoveChecker::belongsTo(const CXXRecordDecl *RD,
const llvm::StringSet<> &Set) const {
const IdentifierInfo *II = RD->getIdentifier();
return II && Set.count(II->getName());
}
MoveChecker::ObjectKind
MoveChecker::classifyObject(const MemRegion *MR,
const CXXRecordDecl *RD) const {
MR = unwrapRValueReferenceIndirection(MR);
bool IsLocal = isa_and_nonnull<VarRegion>(MR) &&
isa<StackSpaceRegion>(MR->getMemorySpace());
if (!RD || !RD->getDeclContext()->isStdNamespace())
return { IsLocal, SK_NonStd };
if (belongsTo(RD, StdSmartPtrClasses))
return { IsLocal, SK_SmartPtr };
if (belongsTo(RD, StdSafeClasses))
return { IsLocal, SK_Safe };
return { IsLocal, SK_Unsafe };
}
void MoveChecker::explainObject(llvm::raw_ostream &OS, const MemRegion *MR,
const CXXRecordDecl *RD, MisuseKind MK) const {
if (const auto DR =
dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) {
const auto *RegionDecl = cast<NamedDecl>(DR->getDecl());
OS << " '" << RegionDecl->getDeclName() << "'";
}
ObjectKind OK = classifyObject(MR, RD);
switch (OK.StdKind) {
case SK_NonStd:
case SK_Safe:
break;
case SK_SmartPtr:
if (MK != MK_Dereference)
break;
LLVM_FALLTHROUGH;
case SK_Unsafe:
OS << " of type '" << RD->getQualifiedNameAsString() << "'";
break;
};
}
void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const {
ProgramStateRef State = C.getState();
if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
auto CtorDec = CC->getDecl();
if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
const CXXRecordDecl *RD = CtorDec->getParent();
MisuseKind MK = CtorDec->isMoveConstructor() ? MK_Move : MK_Copy;
modelUse(State, ArgRegion, RD, MK, C);
return;
}
}
const auto IC = dyn_cast<CXXInstanceCall>(&Call);
if (!IC)
return;
if (isa<CXXDestructorCall>(IC))
return;
const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
if (!ThisRegion)
return;
const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
if (!MethodDecl)
return;
ThisRegion = ThisRegion->getMostDerivedObjectRegion();
if (isStateResetMethod(MethodDecl)) {
State = removeFromState(State, ThisRegion);
C.addTransition(State);
return;
}
if (isMoveSafeMethod(MethodDecl))
return;
const CXXRecordDecl *RD = MethodDecl->getParent();
if (MethodDecl->isOverloadedOperator()) {
OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator();
if (OOK == OO_Equal) {
State = removeFromState(State, ThisRegion);
if (MethodDecl->isCopyAssignmentOperator() ||
MethodDecl->isMoveAssignmentOperator()) {
const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
MisuseKind MK =
MethodDecl->isMoveAssignmentOperator() ? MK_Move : MK_Copy;
modelUse(State, ArgRegion, RD, MK, C);
return;
}
C.addTransition(State);
return;
}
if (OOK == OO_Star || OOK == OO_Arrow) {
modelUse(State, ThisRegion, RD, MK_Dereference, C);
return;
}
}
modelUse(State, ThisRegion, RD, MK_FunCall, C);
}
void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
for (auto E : TrackedRegions) {
const MemRegion *Region = E.first;
bool IsRegDead = !SymReaper.isLiveRegion(Region);
if (IsRegDead) {
State = State->remove<TrackedRegionMap>(Region);
}
}
C.addTransition(State);
}
ProgramStateRef MoveChecker::checkRegionChanges(
ProgramStateRef State, const InvalidatedSymbols *Invalidated,
ArrayRef<const MemRegion *> RequestedRegions,
ArrayRef<const MemRegion *> InvalidatedRegions,
const LocationContext *LCtx, const CallEvent *Call) const {
if (Call) {
const MemRegion *ThisRegion = nullptr;
if (const auto *IC = dyn_cast<CXXInstanceCall>(Call))
ThisRegion = IC->getCXXThisVal().getAsRegion();
for (const auto *Region : RequestedRegions) {
if (ThisRegion != Region &&
llvm::is_contained(InvalidatedRegions, Region))
State = removeFromState(State, Region);
}
} else {
for (const auto *Region : InvalidatedRegions)
State = removeFromState(State, Region->getBaseRegion());
}
return State;
}
void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State,
const char *NL, const char *Sep) const {
TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
if (!RS.isEmpty()) {
Out << Sep << "Moved-from objects :" << NL;
for (auto I: RS) {
I.first->dumpToStream(Out);
if (I.second.isMoved())
Out << ": moved";
else
Out << ": moved and reported";
Out << NL;
}
}
}
void ento::registerMoveChecker(CheckerManager &mgr) {
MoveChecker *chk = mgr.registerChecker<MoveChecker>();
chk->setAggressiveness(
mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr);
}
bool ento::shouldRegisterMoveChecker(const CheckerManager &mgr) {
return true;
}