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(const ReturnStmt *RS, 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 BugReporterVisitor {
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 for (auto &E : State->get<TrackedRegionMap>()) {
105 if (E.first->isSubRegionOf(Region))
106 State = State->remove<TrackedRegionMap>(E.first);
111 static bool isAnyBaseRegionReported(ProgramStateRef State,
112 const MemRegion *Region) {
113 for (auto &E : State->get<TrackedRegionMap>()) {
114 if (Region->isSubRegionOf(E.first) && E.second.isReported())
120 std::shared_ptr<PathDiagnosticPiece>
121 MisusedMovedObjectChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
122 const ExplodedNode *PrevN,
123 BugReporterContext &BRC,
125 // We need only the last move of the reported object's region.
126 // The visitor walks the ExplodedGraph backwards.
129 ProgramStateRef State = N->getState();
130 ProgramStateRef StatePrev = PrevN->getState();
131 const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
132 const RegionState *TrackedObjectPrev =
133 StatePrev->get<TrackedRegionMap>(Region);
136 if (TrackedObjectPrev && TrackedObject)
139 // Retrieve the associated statement.
140 const Stmt *S = PathDiagnosticLocation::getStmt(N);
145 std::string ObjectName;
146 if (const auto DecReg = Region->getAs<DeclRegion>()) {
147 const auto *RegionDecl = dyn_cast<NamedDecl>(DecReg->getDecl());
148 ObjectName = RegionDecl->getNameAsString();
150 std::string InfoText;
151 if (ObjectName != "")
152 InfoText = "'" + ObjectName + "' became 'moved-from' here";
154 InfoText = "Became 'moved-from' here";
156 // Generate the extra diagnostic.
157 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
158 N->getLocationContext());
159 return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
162 const ExplodedNode *MisusedMovedObjectChecker::getMoveLocation(
163 const ExplodedNode *N, const MemRegion *Region, CheckerContext &C) const {
164 // Walk the ExplodedGraph backwards and find the first node that referred to
165 // the tracked region.
166 const ExplodedNode *MoveNode = N;
169 ProgramStateRef State = N->getState();
170 if (!State->get<TrackedRegionMap>(Region))
173 N = N->pred_empty() ? nullptr : *(N->pred_begin());
178 ExplodedNode *MisusedMovedObjectChecker::reportBug(const MemRegion *Region,
179 const CallEvent &Call,
181 MisuseKind MK) const {
182 if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
184 BT.reset(new BugType(this, "Usage of a 'moved-from' object",
185 "C++ move semantics"));
187 // Uniqueing report to the same object.
188 PathDiagnosticLocation LocUsedForUniqueing;
189 const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
191 if (const Stmt *MoveStmt = PathDiagnosticLocation::getStmt(MoveNode))
192 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
193 MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
195 // Creating the error message.
196 std::string ErrorMessage;
199 ErrorMessage = "Method call on a 'moved-from' object";
202 ErrorMessage = "Copying a 'moved-from' object";
205 ErrorMessage = "Moving a 'moved-from' object";
208 if (const auto DecReg = Region->getAs<DeclRegion>()) {
209 const auto *RegionDecl = dyn_cast<NamedDecl>(DecReg->getDecl());
210 ErrorMessage += " '" + RegionDecl->getNameAsString() + "'";
214 llvm::make_unique<BugReport>(*BT, ErrorMessage, N, LocUsedForUniqueing,
215 MoveNode->getLocationContext()->getDecl());
216 R->addVisitor(llvm::make_unique<MovedBugVisitor>(Region));
217 C.emitReport(std::move(R));
223 // Removing the function parameters' MemRegion from the state. This is needed
224 // for PODs where the trivial destructor does not even created nor executed.
225 void MisusedMovedObjectChecker::checkEndFunction(const ReturnStmt *RS,
226 CheckerContext &C) const {
227 auto State = C.getState();
228 TrackedRegionMapTy Objects = State->get<TrackedRegionMap>();
229 if (Objects.isEmpty())
232 auto LC = C.getLocationContext();
234 const auto LD = dyn_cast_or_null<FunctionDecl>(LC->getDecl());
237 llvm::SmallSet<const MemRegion *, 8> InvalidRegions;
239 for (auto Param : LD->parameters()) {
240 auto Type = Param->getType().getTypePtrOrNull();
243 if (!Type->isPointerType() && !Type->isReferenceType()) {
244 InvalidRegions.insert(State->getLValue(Param, LC).getAsRegion());
248 if (InvalidRegions.empty())
251 for (const auto &E : State->get<TrackedRegionMap>()) {
252 if (InvalidRegions.count(E.first->getBaseRegion()))
253 State = State->remove<TrackedRegionMap>(E.first);
256 C.addTransition(State);
259 void MisusedMovedObjectChecker::checkPostCall(const CallEvent &Call,
260 CheckerContext &C) const {
261 const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
265 ProgramStateRef State = C.getState();
266 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
270 const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
272 const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
273 // Check if an object became moved-from.
274 // Object can become moved from after a call to move assignment operator or
275 // move constructor .
276 if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
279 if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
282 const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
286 // Skip moving the object to itself.
287 if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
289 if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
290 if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
293 const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
294 // Skip temp objects because of their short lifetime.
295 if (BaseRegion->getAs<CXXTempObjectRegion>() ||
296 AFC->getArgExpr(0)->isRValue())
298 // If it has already been reported do not need to modify the state.
300 if (State->get<TrackedRegionMap>(ArgRegion))
302 // Mark object as moved-from.
303 State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
304 C.addTransition(State);
307 bool MisusedMovedObjectChecker::isMoveSafeMethod(
308 const CXXMethodDecl *MethodDec) const {
309 // We abandon the cases where bool/void/void* conversion happens.
310 if (const auto *ConversionDec =
311 dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
312 const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
315 if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType())
318 // Function call `empty` can be skipped.
319 if (MethodDec && MethodDec->getDeclName().isIdentifier() &&
320 (MethodDec->getName().lower() == "empty" ||
321 MethodDec->getName().lower() == "isempty"))
327 bool MisusedMovedObjectChecker::isStateResetMethod(
328 const CXXMethodDecl *MethodDec) const {
329 if (MethodDec && MethodDec->getDeclName().isIdentifier()) {
330 std::string MethodName = MethodDec->getName().lower();
331 if (MethodName == "reset" || MethodName == "clear" ||
332 MethodName == "destroy")
338 // Don't report an error inside a move related operation.
339 // We assume that the programmer knows what she does.
340 bool MisusedMovedObjectChecker::isInMoveSafeContext(
341 const LocationContext *LC) const {
343 const auto *CtxDec = LC->getDecl();
344 auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
345 auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
346 auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
347 if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
348 (MethodDec && MethodDec->isOverloadedOperator() &&
349 MethodDec->getOverloadedOperator() == OO_Equal) ||
350 isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec))
352 } while ((LC = LC->getParent()));
356 void MisusedMovedObjectChecker::checkPreCall(const CallEvent &Call,
357 CheckerContext &C) const {
358 ProgramStateRef State = C.getState();
359 const LocationContext *LC = C.getLocationContext();
360 ExplodedNode *N = nullptr;
362 // Remove the MemRegions from the map on which a ctor/dtor call or assignment
365 // Checking constructor calls.
366 if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
367 State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
368 auto CtorDec = CC->getDecl();
369 // Check for copying a moved-from object and report the bug.
370 if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
371 const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
372 const RegionState *ArgState = State->get<TrackedRegionMap>(ArgRegion);
373 if (ArgState && ArgState->isMoved()) {
374 if (!isInMoveSafeContext(LC)) {
375 if(CtorDec->isMoveConstructor())
376 N = reportBug(ArgRegion, Call, C, MK_Move);
378 N = reportBug(ArgRegion, Call, C, MK_Copy);
379 State = State->set<TrackedRegionMap>(ArgRegion,
380 RegionState::getReported());
384 C.addTransition(State, N);
388 const auto IC = dyn_cast<CXXInstanceCall>(&Call);
391 // In case of destructor call we do not track the object anymore.
392 const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
396 if (dyn_cast_or_null<CXXDestructorDecl>(Call.getDecl())) {
397 State = removeFromState(State, ThisRegion);
398 C.addTransition(State);
402 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
405 // Checking assignment operators.
406 bool OperatorEq = MethodDecl->isOverloadedOperator() &&
407 MethodDecl->getOverloadedOperator() == OO_Equal;
408 // Remove the tracked object for every assignment operator, but report bug
409 // only for move or copy assignment's argument.
411 State = removeFromState(State, ThisRegion);
412 if (MethodDecl->isCopyAssignmentOperator() ||
413 MethodDecl->isMoveAssignmentOperator()) {
414 const RegionState *ArgState =
415 State->get<TrackedRegionMap>(IC->getArgSVal(0).getAsRegion());
416 if (ArgState && ArgState->isMoved() && !isInMoveSafeContext(LC)) {
417 const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
418 if(MethodDecl->isMoveAssignmentOperator())
419 N = reportBug(ArgRegion, Call, C, MK_Move);
421 N = reportBug(ArgRegion, Call, C, MK_Copy);
423 State->set<TrackedRegionMap>(ArgRegion, RegionState::getReported());
426 C.addTransition(State, N);
430 // The remaining part is check only for method call on a moved-from object.
432 // We want to investigate the whole object, not only sub-object of a parent
433 // class in which the encountered method defined.
434 while (const CXXBaseObjectRegion *BR =
435 dyn_cast<CXXBaseObjectRegion>(ThisRegion))
436 ThisRegion = BR->getSuperRegion();
438 if (isMoveSafeMethod(MethodDecl))
441 if (isStateResetMethod(MethodDecl)) {
442 State = removeFromState(State, ThisRegion);
443 C.addTransition(State);
447 // If it is already reported then we don't report the bug again.
448 const RegionState *ThisState = State->get<TrackedRegionMap>(ThisRegion);
449 if (!(ThisState && ThisState->isMoved()))
452 // Don't report it in case if any base region is already reported
453 if (isAnyBaseRegionReported(State, ThisRegion))
456 if (isInMoveSafeContext(LC))
459 N = reportBug(ThisRegion, Call, C, MK_FunCall);
460 State = State->set<TrackedRegionMap>(ThisRegion, RegionState::getReported());
461 C.addTransition(State, N);
464 void MisusedMovedObjectChecker::checkDeadSymbols(SymbolReaper &SymReaper,
465 CheckerContext &C) const {
466 ProgramStateRef State = C.getState();
467 TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
468 for (TrackedRegionMapTy::value_type E : TrackedRegions) {
469 const MemRegion *Region = E.first;
470 bool IsRegDead = !SymReaper.isLiveRegion(Region);
472 // Remove the dead regions from the region map.
474 State = State->remove<TrackedRegionMap>(Region);
477 C.addTransition(State);
480 ProgramStateRef MisusedMovedObjectChecker::checkRegionChanges(
481 ProgramStateRef State, const InvalidatedSymbols *Invalidated,
482 ArrayRef<const MemRegion *> ExplicitRegions,
483 ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx,
484 const CallEvent *Call) const {
485 // In case of an InstanceCall don't remove the ThisRegion from the GDM since
486 // it is handled in checkPreCall and checkPostCall.
487 const MemRegion *ThisRegion = nullptr;
488 if (const auto *IC = dyn_cast_or_null<CXXInstanceCall>(Call)) {
489 ThisRegion = IC->getCXXThisVal().getAsRegion();
492 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
493 E = ExplicitRegions.end();
495 const auto *Region = *I;
496 if (ThisRegion != Region) {
497 State = removeFromState(State, Region);
504 void MisusedMovedObjectChecker::printState(raw_ostream &Out,
505 ProgramStateRef State,
507 const char *Sep) const {
509 TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
512 Out << Sep << "Moved-from objects :" << NL;
514 I.first->dumpToStream(Out);
515 if (I.second.isMoved())
518 Out << ": moved and reported";
523 void ento::registerMisusedMovedObjectChecker(CheckerManager &mgr) {
524 mgr.registerChecker<MisusedMovedObjectChecker>();