1 // MisusedMovedObjectChecker.cpp - Check use of moved-from objects. - C++ -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines checker which checks for potential misuses of a moved-from
11 // object. That means method calls on the object or copying it in moved-from
14 //===----------------------------------------------------------------------===//
16 #include "ClangSACheckers.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24 using namespace clang;
31 enum Kind { Moved, Reported } K;
32 RegionState(Kind InK) : K(InK) {}
35 bool isReported() const { return K == Reported; }
36 bool isMoved() const { return K == Moved; }
38 static RegionState getReported() { return RegionState(Reported); }
39 static RegionState getMoved() { return RegionState(Moved); }
41 bool operator==(const RegionState &X) const { return K == X.K; }
42 void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
45 class MisusedMovedObjectChecker
46 : public Checker<check::PreCall, check::PostCall, check::EndFunction,
47 check::DeadSymbols, check::RegionChanges> {
49 void checkEndFunction(CheckerContext &C) const;
50 void checkPreCall(const CallEvent &MC, CheckerContext &C) const;
51 void checkPostCall(const CallEvent &MC, CheckerContext &C) const;
52 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
54 checkRegionChanges(ProgramStateRef State,
55 const InvalidatedSymbols *Invalidated,
56 ArrayRef<const MemRegion *> ExplicitRegions,
57 ArrayRef<const MemRegion *> Regions,
58 const LocationContext *LCtx, const CallEvent *Call) const;
59 void printState(raw_ostream &Out, ProgramStateRef State,
60 const char *NL, const char *Sep) const override;
63 enum MisuseKind {MK_FunCall, MK_Copy, MK_Move};
64 class MovedBugVisitor : public BugReporterVisitorImpl<MovedBugVisitor> {
66 MovedBugVisitor(const MemRegion *R) : Region(R), Found(false) {}
68 void Profile(llvm::FoldingSetNodeID &ID) const override {
71 ID.AddPointer(Region);
74 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
75 const ExplodedNode *PrevN,
76 BugReporterContext &BRC,
77 BugReport &BR) override;
80 // The tracked region.
81 const MemRegion *Region;
85 mutable std::unique_ptr<BugType> BT;
86 ExplodedNode *reportBug(const MemRegion *Region, const CallEvent &Call,
87 CheckerContext &C, MisuseKind MK) const;
88 bool isInMoveSafeContext(const LocationContext *LC) const;
89 bool isStateResetMethod(const CXXMethodDecl *MethodDec) const;
90 bool isMoveSafeMethod(const CXXMethodDecl *MethodDec) const;
91 const ExplodedNode *getMoveLocation(const ExplodedNode *N,
92 const MemRegion *Region,
93 CheckerContext &C) const;
95 } // end anonymous namespace
97 REGISTER_MAP_WITH_PROGRAMSTATE(TrackedRegionMap, const MemRegion *, RegionState)
99 // If a region is removed all of the subregions needs to be removed too.
100 static ProgramStateRef removeFromState(ProgramStateRef State,
101 const MemRegion *Region) {
104 // Note: The isSubRegionOf function is not reflexive.
105 State = State->remove<TrackedRegionMap>(Region);
106 for (auto &E : State->get<TrackedRegionMap>()) {
107 if (E.first->isSubRegionOf(Region))
108 State = State->remove<TrackedRegionMap>(E.first);
113 static bool isAnyBaseRegionReported(ProgramStateRef State,
114 const MemRegion *Region) {
115 for (auto &E : State->get<TrackedRegionMap>()) {
116 if (Region->isSubRegionOf(E.first) && E.second.isReported())
122 std::shared_ptr<PathDiagnosticPiece>
123 MisusedMovedObjectChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
124 const ExplodedNode *PrevN,
125 BugReporterContext &BRC,
127 // We need only the last move of the reported object's region.
128 // The visitor walks the ExplodedGraph backwards.
131 ProgramStateRef State = N->getState();
132 ProgramStateRef StatePrev = PrevN->getState();
133 const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
134 const RegionState *TrackedObjectPrev =
135 StatePrev->get<TrackedRegionMap>(Region);
138 if (TrackedObjectPrev && TrackedObject)
141 // Retrieve the associated statement.
142 const Stmt *S = PathDiagnosticLocation::getStmt(N);
147 std::string ObjectName;
148 if (const auto DecReg = Region->getAs<DeclRegion>()) {
149 const auto *RegionDecl = dyn_cast<NamedDecl>(DecReg->getDecl());
150 ObjectName = RegionDecl->getNameAsString();
152 std::string InfoText;
153 if (ObjectName != "")
154 InfoText = "'" + ObjectName + "' became 'moved-from' here";
156 InfoText = "Became 'moved-from' here";
158 // Generate the extra diagnostic.
159 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
160 N->getLocationContext());
161 return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
164 const ExplodedNode *MisusedMovedObjectChecker::getMoveLocation(
165 const ExplodedNode *N, const MemRegion *Region, CheckerContext &C) const {
166 // Walk the ExplodedGraph backwards and find the first node that referred to
167 // the tracked region.
168 const ExplodedNode *MoveNode = N;
171 ProgramStateRef State = N->getState();
172 if (!State->get<TrackedRegionMap>(Region))
175 N = N->pred_empty() ? nullptr : *(N->pred_begin());
180 ExplodedNode *MisusedMovedObjectChecker::reportBug(const MemRegion *Region,
181 const CallEvent &Call,
183 MisuseKind MK) const {
184 if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
186 BT.reset(new BugType(this, "Usage of a 'moved-from' object",
187 "C++ move semantics"));
189 // Uniqueing report to the same object.
190 PathDiagnosticLocation LocUsedForUniqueing;
191 const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
193 if (const Stmt *MoveStmt = PathDiagnosticLocation::getStmt(MoveNode))
194 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
195 MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
197 // Creating the error message.
198 std::string ErrorMessage;
201 ErrorMessage = "Method call on a 'moved-from' object";
204 ErrorMessage = "Copying a 'moved-from' object";
207 ErrorMessage = "Moving a 'moved-from' object";
210 if (const auto DecReg = Region->getAs<DeclRegion>()) {
211 const auto *RegionDecl = dyn_cast<NamedDecl>(DecReg->getDecl());
212 ErrorMessage += " '" + RegionDecl->getNameAsString() + "'";
216 llvm::make_unique<BugReport>(*BT, ErrorMessage, N, LocUsedForUniqueing,
217 MoveNode->getLocationContext()->getDecl());
218 R->addVisitor(llvm::make_unique<MovedBugVisitor>(Region));
219 C.emitReport(std::move(R));
225 // Removing the function parameters' MemRegion from the state. This is needed
226 // for PODs where the trivial destructor does not even created nor executed.
227 void MisusedMovedObjectChecker::checkEndFunction(CheckerContext &C) const {
228 auto State = C.getState();
229 TrackedRegionMapTy Objects = State->get<TrackedRegionMap>();
230 if (Objects.isEmpty())
233 auto LC = C.getLocationContext();
235 const auto LD = dyn_cast_or_null<FunctionDecl>(LC->getDecl());
238 llvm::SmallSet<const MemRegion *, 8> InvalidRegions;
240 for (auto Param : LD->parameters()) {
241 auto Type = Param->getType().getTypePtrOrNull();
244 if (!Type->isPointerType() && !Type->isReferenceType()) {
245 InvalidRegions.insert(State->getLValue(Param, LC).getAsRegion());
249 if (InvalidRegions.empty())
252 for (const auto &E : State->get<TrackedRegionMap>()) {
253 if (InvalidRegions.count(E.first->getBaseRegion()))
254 State = State->remove<TrackedRegionMap>(E.first);
257 C.addTransition(State);
260 void MisusedMovedObjectChecker::checkPostCall(const CallEvent &Call,
261 CheckerContext &C) const {
262 const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
266 ProgramStateRef State = C.getState();
267 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
271 const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
273 const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
274 // Check if an object became moved-from.
275 // Object can become moved from after a call to move assignment operator or
276 // move constructor .
277 if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
280 if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
283 const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
287 // Skip moving the object to itself.
288 if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
290 if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
291 if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
294 const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
295 // Skip temp objects because of their short lifetime.
296 if (BaseRegion->getAs<CXXTempObjectRegion>() ||
297 AFC->getArgExpr(0)->isRValue())
299 // If it has already been reported do not need to modify the state.
301 if (State->get<TrackedRegionMap>(ArgRegion))
303 // Mark object as moved-from.
304 State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
305 C.addTransition(State);
308 bool MisusedMovedObjectChecker::isMoveSafeMethod(
309 const CXXMethodDecl *MethodDec) const {
310 // We abandon the cases where bool/void/void* conversion happens.
311 if (const auto *ConversionDec =
312 dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
313 const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
316 if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType())
319 // Function call `empty` can be skipped.
320 if (MethodDec && MethodDec->getDeclName().isIdentifier() &&
321 (MethodDec->getName().lower() == "empty" ||
322 MethodDec->getName().lower() == "isempty"))
328 bool MisusedMovedObjectChecker::isStateResetMethod(
329 const CXXMethodDecl *MethodDec) const {
330 if (MethodDec && MethodDec->getDeclName().isIdentifier()) {
331 std::string MethodName = MethodDec->getName().lower();
332 if (MethodName == "reset" || MethodName == "clear" ||
333 MethodName == "destroy")
339 // Don't report an error inside a move related operation.
340 // We assume that the programmer knows what she does.
341 bool MisusedMovedObjectChecker::isInMoveSafeContext(
342 const LocationContext *LC) const {
344 const auto *CtxDec = LC->getDecl();
345 auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
346 auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
347 auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
348 if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
349 (MethodDec && MethodDec->isOverloadedOperator() &&
350 MethodDec->getOverloadedOperator() == OO_Equal) ||
351 isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec))
353 } while ((LC = LC->getParent()));
357 void MisusedMovedObjectChecker::checkPreCall(const CallEvent &Call,
358 CheckerContext &C) const {
359 ProgramStateRef State = C.getState();
360 const LocationContext *LC = C.getLocationContext();
361 ExplodedNode *N = nullptr;
363 // Remove the MemRegions from the map on which a ctor/dtor call or assignment
366 // Checking constructor calls.
367 if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
368 State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
369 auto CtorDec = CC->getDecl();
370 // Check for copying a moved-from object and report the bug.
371 if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
372 const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
373 const RegionState *ArgState = State->get<TrackedRegionMap>(ArgRegion);
374 if (ArgState && ArgState->isMoved()) {
375 if (!isInMoveSafeContext(LC)) {
376 if(CtorDec->isMoveConstructor())
377 N = reportBug(ArgRegion, Call, C, MK_Move);
379 N = reportBug(ArgRegion, Call, C, MK_Copy);
380 State = State->set<TrackedRegionMap>(ArgRegion,
381 RegionState::getReported());
385 C.addTransition(State, N);
389 const auto IC = dyn_cast<CXXInstanceCall>(&Call);
392 // In case of destructor call we do not track the object anymore.
393 const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
397 if (dyn_cast_or_null<CXXDestructorDecl>(Call.getDecl())) {
398 State = removeFromState(State, ThisRegion);
399 C.addTransition(State);
403 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
406 // Checking assignment operators.
407 bool OperatorEq = MethodDecl->isOverloadedOperator() &&
408 MethodDecl->getOverloadedOperator() == OO_Equal;
409 // Remove the tracked object for every assignment operator, but report bug
410 // only for move or copy assignment's argument.
412 State = removeFromState(State, ThisRegion);
413 if (MethodDecl->isCopyAssignmentOperator() ||
414 MethodDecl->isMoveAssignmentOperator()) {
415 const RegionState *ArgState =
416 State->get<TrackedRegionMap>(IC->getArgSVal(0).getAsRegion());
417 if (ArgState && ArgState->isMoved() && !isInMoveSafeContext(LC)) {
418 const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
419 if(MethodDecl->isMoveAssignmentOperator())
420 N = reportBug(ArgRegion, Call, C, MK_Move);
422 N = reportBug(ArgRegion, Call, C, MK_Copy);
424 State->set<TrackedRegionMap>(ArgRegion, RegionState::getReported());
427 C.addTransition(State, N);
431 // The remaining part is check only for method call on a moved-from object.
433 // We want to investigate the whole object, not only sub-object of a parent
434 // class in which the encountered method defined.
435 while (const CXXBaseObjectRegion *BR =
436 dyn_cast<CXXBaseObjectRegion>(ThisRegion))
437 ThisRegion = BR->getSuperRegion();
439 if (isMoveSafeMethod(MethodDecl))
442 if (isStateResetMethod(MethodDecl)) {
443 State = removeFromState(State, ThisRegion);
444 C.addTransition(State);
448 // If it is already reported then we don't report the bug again.
449 const RegionState *ThisState = State->get<TrackedRegionMap>(ThisRegion);
450 if (!(ThisState && ThisState->isMoved()))
453 // Don't report it in case if any base region is already reported
454 if (isAnyBaseRegionReported(State, ThisRegion))
457 if (isInMoveSafeContext(LC))
460 N = reportBug(ThisRegion, Call, C, MK_FunCall);
461 State = State->set<TrackedRegionMap>(ThisRegion, RegionState::getReported());
462 C.addTransition(State, N);
465 void MisusedMovedObjectChecker::checkDeadSymbols(SymbolReaper &SymReaper,
466 CheckerContext &C) const {
467 ProgramStateRef State = C.getState();
468 TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
469 for (TrackedRegionMapTy::value_type E : TrackedRegions) {
470 const MemRegion *Region = E.first;
471 bool IsRegDead = !SymReaper.isLiveRegion(Region);
473 // Remove the dead regions from the region map.
475 State = State->remove<TrackedRegionMap>(Region);
478 C.addTransition(State);
481 ProgramStateRef MisusedMovedObjectChecker::checkRegionChanges(
482 ProgramStateRef State, const InvalidatedSymbols *Invalidated,
483 ArrayRef<const MemRegion *> ExplicitRegions,
484 ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx,
485 const CallEvent *Call) const {
486 // In case of an InstanceCall don't remove the ThisRegion from the GDM since
487 // it is handled in checkPreCall and checkPostCall.
488 const MemRegion *ThisRegion = nullptr;
489 if (const auto *IC = dyn_cast_or_null<CXXInstanceCall>(Call)) {
490 ThisRegion = IC->getCXXThisVal().getAsRegion();
493 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
494 E = ExplicitRegions.end();
496 const auto *Region = *I;
497 if (ThisRegion != Region) {
498 State = removeFromState(State, Region);
505 void MisusedMovedObjectChecker::printState(raw_ostream &Out,
506 ProgramStateRef State,
508 const char *Sep) const {
510 TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
513 Out << Sep << "Moved-from objects :" << NL;
515 I.first->dumpToStream(Out);
516 if (I.second.isMoved())
519 Out << ": moved and reported";
524 void ento::registerMisusedMovedObjectChecker(CheckerManager &mgr) {
525 mgr.registerChecker<MisusedMovedObjectChecker>();