27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringSet.h"
37 enum Kind { Moved, Reported } K;
38 RegionState(Kind InK) : K(InK) {}
41 bool isReported()
const {
return K == Reported; }
42 bool isMoved()
const {
return K == Moved; }
44 static RegionState getReported() {
return RegionState(Reported); }
45 static RegionState getMoved() {
return RegionState(Moved); }
47 bool operator==(
const RegionState &
X)
const {
return K ==
X.K; }
48 void Profile(llvm::FoldingSetNodeID &ID)
const {
ID.AddInteger(K); }
54 :
public Checker<check::PreCall, check::PostCall, check::DeadSymbols,
55 check::RegionChanges, eval::Call> {
57 void checkPreCall(
const CallEvent &MC, CheckerContext &
C)
const;
58 void checkPostCall(
const CallEvent &MC, CheckerContext &
C)
const;
59 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &
C)
const;
60 bool evalCall(
const CallEvent &
Call, CheckerContext &
C)
const;
64 ArrayRef<const MemRegion *> RequestedRegions,
65 ArrayRef<const MemRegion *> InvalidatedRegions,
66 const StackFrame *SF,
const CallEvent *
Call)
const;
68 const char *NL,
const char *Sep)
const override;
71 enum MisuseKind { MK_FunCall, MK_Copy, MK_Move, MK_Dereference };
72 enum StdObjectKind { SK_NonStd, SK_Unsafe, SK_Safe, SK_SmartPtr };
74 enum AggressivenessKind {
77 AK_KnownsAndLocals = 1,
82 static bool misuseCausesCrash(MisuseKind MK) {
83 return MK == MK_Dereference;
90 StdObjectKind StdKind;
96 const llvm::StringSet<> StdSmartPtrClasses = {
107 const llvm::StringSet<> StdSafeClasses = {
121 bool shouldBeTracked(ObjectKind OK)
const {
135 return (Aggressiveness == AK_All) ||
136 (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
137 OK.StdKind == SK_Unsafe || OK.StdKind == SK_SmartPtr;
142 bool shouldWarnAbout(ObjectKind OK, MisuseKind MK)
const {
145 return shouldBeTracked(OK) &&
146 ((Aggressiveness == AK_All) ||
147 (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
148 OK.StdKind != SK_SmartPtr || MK == MK_Dereference);
154 const CXXRecordDecl *RD)
const;
159 const MemRegion *MR,
const CXXRecordDecl *RD,
160 MisuseKind MK)
const;
162 bool belongsTo(
const CXXRecordDecl *RD,
const llvm::StringSet<> &
Set)
const;
164 class MovedBugVisitor :
public BugReporterVisitor {
166 MovedBugVisitor(
const MoveChecker &Chk,
const MemRegion *R,
167 const CXXRecordDecl *RD, MisuseKind MK)
168 : Chk(Chk), Region(
R), RD(RD), MK(MK), Found(
false) {}
170 void Profile(llvm::FoldingSetNodeID &ID)
const override {
173 ID.AddPointer(Region);
181 BugReporterContext &BRC,
182 PathSensitiveBugReport &BR)
override;
185 const MoveChecker &Chk;
187 const MemRegion *Region;
189 const CXXRecordDecl *RD;
195 AggressivenessKind Aggressiveness = AK_KnownsAndLocals;
198 void setAggressiveness(StringRef Str, CheckerManager &Mgr) {
200 llvm::StringSwitch<AggressivenessKind>(Str)
201 .Case(
"KnownsOnly", AK_KnownsOnly)
202 .Case(
"KnownsAndLocals", AK_KnownsAndLocals)
204 .Default(AK_Invalid);
206 if (Aggressiveness == AK_Invalid)
208 "either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value");
215 const CallDescription StdMoveCall{CDM::SimpleFunc, {
"std",
"move"}, 3};
222 const CXXRecordDecl *RD, MisuseKind MK,
223 CheckerContext &
C)
const;
228 ExplodedNode *tryToReportBug(
const MemRegion *Region,
const CXXRecordDecl *RD,
229 CheckerContext &
C, MisuseKind MK)
const;
231 bool isInMoveSafeStackFrame(
const CheckerContext &
C)
const;
232 bool isStateResetMethod(
const CXXMethodDecl *MethodDec)
const;
233 bool isMoveSafeMethod(
const CXXMethodDecl *MethodDec)
const;
234 const ExplodedNode *getMoveLocation(
const ExplodedNode *N,
235 const MemRegion *Region,
236 CheckerContext &
C)
const;
252 const RegionState *RS = State->get<TrackedRegionMap>(Region);
253 return RS && (RS->isMoved() || RS->isReported());
262 bool Strict =
false) {
265 for (
auto &E : State->get<TrackedRegionMap>()) {
266 if ((!Strict || E.first != Region) && E.first->isSubRegionOf(Region))
267 State = State->remove<TrackedRegionMap>(E.first);
274 auto IsReportedBase = [&](
const auto &E) {
275 return Region->
isSubRegionOf(E.first) && E.second.isReported();
277 return llvm::any_of(State->get<TrackedRegionMap>(), IsReportedBase);
281 if (
const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) {
291MoveChecker::MovedBugVisitor::VisitNode(
const ExplodedNode *N,
300 const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
301 const RegionState *TrackedObjectPrev =
302 StatePrev->get<TrackedRegionMap>(Region);
305 if (TrackedObjectPrev && TrackedObject)
314 SmallString<128> Str;
315 llvm::raw_svector_ostream
OS(Str);
317 ObjectKind OK = Chk.classifyObject(State, Region, RD);
318 switch (OK.StdKind) {
320 if (MK == MK_Dereference) {
321 OS <<
"Smart pointer";
322 Chk.explainObject(State,
OS, Region, RD, MK);
323 OS <<
" is reset to null when moved from";
333 Chk.explainObject(State,
OS, Region, RD, MK);
338 Chk.explainObject(State,
OS, Region, RD, MK);
339 OS <<
" is left in a valid but unspecified state after move";
345 return std::make_shared<PathDiagnosticEventPiece>(Pos,
OS.str(),
true);
348const ExplodedNode *MoveChecker::getMoveLocation(
const ExplodedNode *N,
349 const MemRegion *Region,
350 CheckerContext &
C)
const {
353 const ExplodedNode *MoveNode = N;
357 if (!State->get<TrackedRegionMap>(Region))
365void MoveChecker::modelUse(
ProgramStateRef State,
const MemRegion *Region,
366 const CXXRecordDecl *RD, MisuseKind MK,
367 CheckerContext &
C)
const {
368 assert(!
C.isDifferent() &&
"No transitions should have been made by now");
369 const RegionState *RS = State->get<TrackedRegionMap>(Region);
370 ObjectKind OK = classifyObject(State, Region, RD);
374 if (MK == MK_Dereference && OK.StdKind != SK_SmartPtr)
377 if (!RS || !shouldWarnAbout(OK, MK) || isInMoveSafeStackFrame(
C)) {
379 C.addTransition(State);
387 if (misuseCausesCrash(MK)) {
390 C.addTransition(State);
395 ExplodedNode *N = tryToReportBug(Region, RD,
C, MK);
401 State = State->set<TrackedRegionMap>(Region, RegionState::getReported());
402 C.addTransition(State, N);
405ExplodedNode *MoveChecker::tryToReportBug(
const MemRegion *Region,
406 const CXXRecordDecl *RD,
408 MisuseKind MK)
const {
409 if (ExplodedNode *N =
410 misuseCausesCrash(MK) ?
C.addSink() :
C.generateNonFatalErrorNode()) {
412 PathDiagnosticLocation LocUsedForUniqueing;
413 const ExplodedNode *MoveNode = getMoveLocation(N, Region,
C);
420 llvm::SmallString<128> Str;
421 llvm::raw_svector_ostream
OS(Str);
425 OS <<
"Method called on moved-from object";
426 explainObject(State,
OS, Region, RD, MK);
429 OS <<
"Moved-from object";
430 explainObject(State,
OS, Region, RD, MK);
434 OS <<
"Moved-from object";
435 explainObject(State,
OS, Region, RD, MK);
439 OS <<
"Dereference of null smart pointer";
440 explainObject(State,
OS, Region, RD, MK);
444 auto R = std::make_unique<PathSensitiveBugReport>(
445 BT,
OS.str(), N, LocUsedForUniqueing,
447 R->addVisitor(std::make_unique<MovedBugVisitor>(*
this, Region, RD, MK));
448 C.emitReport(std::move(R));
454void MoveChecker::checkPostCall(
const CallEvent &
Call,
455 CheckerContext &
C)
const {
456 const auto *AFC = dyn_cast<AnyFunctionCall>(&
Call);
461 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
468 const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
469 if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
472 if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
475 const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
480 const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&
Call);
481 if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
484 if (
const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
485 if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
488 const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
490 if (BaseRegion->
getAs<CXXTempObjectRegion>() ||
491 AFC->getArgExpr(0)->isPRValue())
495 if (State->get<TrackedRegionMap>(ArgRegion))
498 const CXXRecordDecl *RD = MethodDecl->
getParent();
499 ObjectKind OK = classifyObject(State, ArgRegion, RD);
500 if (shouldBeTracked(OK)) {
502 State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
503 C.addTransition(State);
506 assert(!
C.isDifferent() &&
"Should not have made transitions on this path!");
509bool MoveChecker::evalCall(
const CallEvent &
Call, CheckerContext &
C)
const {
511 const auto *CE = dyn_cast_if_present<CallExpr>(
Call.getOriginExpr());
524 const MemRegion *ContainerRegion = POS->getContainer();
525 if (!ContainerRegion)
528 const auto *TypedRegion = dyn_cast<TypedValueRegion>(ContainerRegion);
533 QualType ObjTy = TypedRegion->getValueType();
539 ObjectKind OK = classifyObject(State, ContainerRegion, RD);
545 const auto *BackInsCall = dyn_cast<CallExpr>(CE->getArg(2)->IgnoreImpCasts());
549 const Expr *DestExpr = BackInsCall->getArg(0)->IgnoreImpCasts();
553 const auto *DestDRE = dyn_cast<DeclRefExpr>(DestExpr);
557 const auto *DestVD = dyn_cast<VarDecl>(DestDRE->getDecl());
561 const MemRegion *DestRegion =
562 State->getLValue(DestVD,
C.getStackFrame()).getAsRegion();
566 SValBuilder &SVB = State->getStateManager().getSValBuilder();
568 State = State->BindExpr(CE,
C.getStackFrame(), ReturnVal);
570 State = State->invalidateRegions({DestRegion},
Call.getCFGElementRef(),
571 C.blockCount(),
C.getStackFrame(),
574 if (shouldBeTracked(OK))
575 State = State->set<TrackedContentsMap>(ContainerRegion,
576 RegionState::getMoved());
578 C.addTransition(State);
582bool MoveChecker::isMoveSafeMethod(
const CXXMethodDecl *MethodDec)
const {
584 if (
const auto *ConversionDec =
585 dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
586 const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
594 (MethodDec->
getName().lower() ==
"empty" ||
595 MethodDec->
getName().lower() ==
"isempty"));
598bool MoveChecker::isStateResetMethod(
const CXXMethodDecl *MethodDec)
const {
601 if (MethodDec->
hasAttr<ReinitializesAttr>())
604 std::string MethodName = MethodDec->
getName().lower();
607 if (MethodName ==
"assign" || MethodName ==
"clear" ||
608 MethodName ==
"destroy" || MethodName ==
"reset" ||
609 MethodName ==
"resize" || MethodName ==
"shrink")
617bool MoveChecker::isInMoveSafeStackFrame(
const CheckerContext &
C)
const {
618 return llvm::any_of(
C.stackframes(), [
this](
const StackFrame &Frame) {
619 const auto *SFDec = Frame.getDecl();
620 auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(SFDec);
621 auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(SFDec);
622 auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(SFDec);
623 return DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
624 (MethodDec && MethodDec->isOverloadedOperator() &&
625 MethodDec->getOverloadedOperator() == OO_Equal) ||
626 isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec);
630bool MoveChecker::belongsTo(
const CXXRecordDecl *RD,
631 const llvm::StringSet<> &
Set)
const {
636MoveChecker::ObjectKind
638 const CXXRecordDecl *RD)
const {
644 isa_and_nonnull<VarRegion, CXXLifetimeExtendedObjectRegion>(MR) &&
648 return { IsLocal, SK_NonStd };
650 if (belongsTo(RD, StdSmartPtrClasses))
651 return { IsLocal, SK_SmartPtr };
653 if (belongsTo(RD, StdSafeClasses))
654 return { IsLocal, SK_Safe };
656 return { IsLocal, SK_Unsafe };
660 const MemRegion *MR,
const CXXRecordDecl *RD,
661 MisuseKind MK)
const {
667 OS <<
" '" << RegionDecl->getDeclName() <<
"'";
670 ObjectKind OK = classifyObject(State, MR, RD);
671 switch (OK.StdKind) {
676 if (MK != MK_Dereference)
687void MoveChecker::checkPreCall(
const CallEvent &
Call, CheckerContext &
C)
const {
694 if (
const auto *CC = dyn_cast<CXXConstructorCall>(&
Call)) {
696 auto CtorDec = CC->getDecl();
698 if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
699 const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
700 const CXXRecordDecl *RD = CtorDec->
getParent();
701 MisuseKind MK = CtorDec->isMoveConstructor() ? MK_Move : MK_Copy;
702 modelUse(State, ArgRegion, RD, MK,
C);
707 const auto IC = dyn_cast<CXXInstanceCall>(&
Call);
711 const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
716 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
729 const CXXRecordDecl *RD = MethodDecl->
getParent();
731 if (MethodDecl->getOverloadedOperator() == OO_Star ||
732 MethodDecl->getOverloadedOperator() == OO_Arrow) {
733 SVal Val = IC->getCXXThisVal();
736 const MemRegion *ContainerRegion = POS->getContainer();
737 if (!ContainerRegion)
740 const auto *TypedRegion = dyn_cast<TypedValueRegion>(ContainerRegion);
744 QualType ObjTy = TypedRegion->getValueType();
749 if (State->get<TrackedContentsMap>(ContainerRegion)) {
750 ExplodedNode *N = tryToReportBug(ContainerRegion, R,
C, MK_FunCall);
754 State = State->set<TrackedContentsMap>(ContainerRegion,
755 RegionState::getReported());
756 C.addTransition(State, N);
762 if (isStateResetMethod(MethodDecl)) {
764 C.addTransition(State);
768 if (isMoveSafeMethod(MethodDecl))
771 if (MethodDecl->isOverloadedOperator()) {
774 if (OOK == OO_Equal) {
779 if (MethodDecl->isCopyAssignmentOperator() ||
780 MethodDecl->isMoveAssignmentOperator()) {
781 const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
783 MethodDecl->isMoveAssignmentOperator() ? MK_Move : MK_Copy;
784 modelUse(State, ArgRegion, RD, MK,
C);
787 C.addTransition(State);
791 if (OOK == OO_Star || OOK == OO_Arrow) {
792 modelUse(State, ThisRegion, RD, MK_Dereference,
C);
797 modelUse(State, ThisRegion, RD, MK_FunCall,
C);
800void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper,
801 CheckerContext &
C)
const {
803 TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
804 for (
auto E : TrackedRegions) {
805 const MemRegion *Region = E.first;
810 State = State->remove<TrackedRegionMap>(Region);
813 C.addTransition(State);
818 ArrayRef<const MemRegion *> RequestedRegions,
819 ArrayRef<const MemRegion *> InvalidatedRegions,
const StackFrame *SF,
820 const CallEvent *
Call)
const {
832 for (
const auto *Region : RequestedRegions) {
833 if (llvm::is_contained(InvalidatedRegions, Region))
840 for (
const auto *Region : InvalidatedRegions)
848 const char *NL,
const char *Sep)
const {
850 TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
853 Out << Sep <<
"Moved-from objects :" << NL;
855 I.first->dumpToStream(Out);
856 if (I.second.isMoved())
859 Out <<
": moved and reported";
864void ento::registerMoveChecker(CheckerManager &mgr) {
866 chk->setAggressiveness(
870bool ento::shouldRegisterMoveChecker(
const CheckerManager &mgr) {
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool isAnyBaseRegionReported(ProgramStateRef State, const MemRegion *Region)
static ProgramStateRef removeFromState(ProgramStateRef State, const MemRegion *Region, bool Strict=false)
static const MemRegion * unwrapRValueReferenceIndirection(const MemRegion *MR)
Defines an enumeration for C++ overloaded operators.
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
StringRef getCheckerStringOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Query an option's string value.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
bool isStdNamespace() const
DeclContext * getDeclContext()
bool isIdentifier() const
Predicate functions for querying what type of name this is.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
std::string getQualifiedNameAsString() const
const Decl * getDecl() const
bool isBooleanType() const
bool isRValueReferenceType() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isVoidPointerType() const
const SourceManager & getSourceManager() const
bool matches(const CallEvent &Call) const
Returns true if the CallEvent is a call to a function that matches the CallDescription.
const AnalyzerOptions & getAnalyzerOptions() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
void reportInvalidCheckerOptionValue(const CheckerFrontend *Checker, StringRef OptionName, StringRef ExpectedValueDesc) const
Emits an error through a DiagnosticsEngine about an invalid user supplied checker option value.
Simple checker classes that implement one frontend (i.e.
const ProgramStateRef & getState() const
pred_iterator pred_begin()
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
MemRegion - The root abstract class for all memory regions.
bool hasMemorySpace(ProgramStateRef State) const
virtual bool isSubRegionOf(const MemRegion *R) const
Check if the region is a subregion of the given region.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
const RegionTy * getAs() const
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getMostDerivedObjectRegion() const
Recursively retrieve the region of the most derived class instance of regions of C++ base class insta...
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const StackFrame *SF, unsigned count)
Create a new symbol with a unique 'name'.
virtual const MemRegion * getOriginRegion() const
Find the region from which this symbol originates.
virtual QualType getType() const =0
bool isLiveRegion(const MemRegion *region)
const char *const CXXMoveSemantics
const IteratorPosition * getIteratorPosition(ProgramStateRef State, SVal Val)
bool isMovedFrom(ProgramStateRef State, const MemRegion *Region)
Returns true if the object is known to have been recently std::moved.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
bool isa(CodeGen::Address addr)
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)