1 // MoveChecker.cpp - Check use of moved-from objects. - C++ ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This defines checker which checks for potential misuses of a moved-from 10 // object. That means method calls on the object or copying it in moved-from 11 // state. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/ExprCXX.h" 16 #include "clang/Driver/DriverDiagnostic.h" 17 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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" 23 #include "llvm/ADT/StringSet.h" 24 25 using namespace clang; 26 using namespace ento; 27 28 namespace { 29 struct RegionState { 30 private: 31 enum Kind { Moved, Reported } K; 32 RegionState(Kind InK) : K(InK) {} 33 34 public: 35 bool isReported() const { return K == Reported; } 36 bool isMoved() const { return K == Moved; } 37 38 static RegionState getReported() { return RegionState(Reported); } 39 static RegionState getMoved() { return RegionState(Moved); } 40 41 bool operator==(const RegionState &X) const { return K == X.K; } 42 void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); } 43 }; 44 } // end of anonymous namespace 45 46 namespace { 47 class MoveChecker 48 : public Checker<check::PreCall, check::PostCall, 49 check::DeadSymbols, check::RegionChanges> { 50 public: 51 void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const; 52 void checkPreCall(const CallEvent &MC, CheckerContext &C) const; 53 void checkPostCall(const CallEvent &MC, CheckerContext &C) const; 54 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; 55 ProgramStateRef 56 checkRegionChanges(ProgramStateRef State, 57 const InvalidatedSymbols *Invalidated, 58 ArrayRef<const MemRegion *> RequestedRegions, 59 ArrayRef<const MemRegion *> InvalidatedRegions, 60 const LocationContext *LCtx, const CallEvent *Call) const; 61 void printState(raw_ostream &Out, ProgramStateRef State, 62 const char *NL, const char *Sep) const override; 63 64 private: 65 enum MisuseKind { MK_FunCall, MK_Copy, MK_Move, MK_Dereference }; 66 enum StdObjectKind { SK_NonStd, SK_Unsafe, SK_Safe, SK_SmartPtr }; 67 68 enum AggressivenessKind { // In any case, don't warn after a reset. 69 AK_Invalid = -1, 70 AK_KnownsOnly = 0, // Warn only about known move-unsafe classes. 71 AK_KnownsAndLocals = 1, // Also warn about all local objects. 72 AK_All = 2, // Warn on any use-after-move. 73 AK_NumKinds = AK_All 74 }; 75 76 static bool misuseCausesCrash(MisuseKind MK) { 77 return MK == MK_Dereference; 78 } 79 80 struct ObjectKind { 81 // Is this a local variable or a local rvalue reference? 82 bool IsLocal; 83 // Is this an STL object? If so, of what kind? 84 StdObjectKind StdKind; 85 }; 86 87 // STL smart pointers are automatically re-initialized to null when moved 88 // from. So we can't warn on many methods, but we can warn when it is 89 // dereferenced, which is UB even if the resulting lvalue never gets read. 90 const llvm::StringSet<> StdSmartPtrClasses = { 91 "shared_ptr", 92 "unique_ptr", 93 "weak_ptr", 94 }; 95 96 // Not all of these are entirely move-safe, but they do provide *some* 97 // guarantees, and it means that somebody is using them after move 98 // in a valid manner. 99 // TODO: We can still try to identify *unsafe* use after move, 100 // like we did with smart pointers. 101 const llvm::StringSet<> StdSafeClasses = { 102 "basic_filebuf", 103 "basic_ios", 104 "future", 105 "optional", 106 "packaged_task" 107 "promise", 108 "shared_future", 109 "shared_lock", 110 "thread", 111 "unique_lock", 112 }; 113 114 // Should we bother tracking the state of the object? 115 bool shouldBeTracked(ObjectKind OK) const { 116 // In non-aggressive mode, only warn on use-after-move of local variables 117 // (or local rvalue references) and of STL objects. The former is possible 118 // because local variables (or local rvalue references) are not tempting 119 // their user to re-use the storage. The latter is possible because STL 120 // objects are known to end up in a valid but unspecified state after the 121 // move and their state-reset methods are also known, which allows us to 122 // predict precisely when use-after-move is invalid. 123 // Some STL objects are known to conform to additional contracts after move, 124 // so they are not tracked. However, smart pointers specifically are tracked 125 // because we can perform extra checking over them. 126 // In aggressive mode, warn on any use-after-move because the user has 127 // intentionally asked us to completely eliminate use-after-move 128 // in his code. 129 return (Aggressiveness == AK_All) || 130 (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) || 131 OK.StdKind == SK_Unsafe || OK.StdKind == SK_SmartPtr; 132 } 133 134 // Some objects only suffer from some kinds of misuses, but we need to track 135 // them anyway because we cannot know in advance what misuse will we find. 136 bool shouldWarnAbout(ObjectKind OK, MisuseKind MK) const { 137 // Additionally, only warn on smart pointers when they are dereferenced (or 138 // local or we are aggressive). 139 return shouldBeTracked(OK) && 140 ((Aggressiveness == AK_All) || 141 (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) || 142 OK.StdKind != SK_SmartPtr || MK == MK_Dereference); 143 } 144 145 // Obtains ObjectKind of an object. Because class declaration cannot always 146 // be easily obtained from the memory region, it is supplied separately. 147 ObjectKind classifyObject(const MemRegion *MR, const CXXRecordDecl *RD) const; 148 149 // Classifies the object and dumps a user-friendly description string to 150 // the stream. 151 void explainObject(llvm::raw_ostream &OS, const MemRegion *MR, 152 const CXXRecordDecl *RD, MisuseKind MK) const; 153 154 bool belongsTo(const CXXRecordDecl *RD, const llvm::StringSet<> &Set) const; 155 156 class MovedBugVisitor : public BugReporterVisitor { 157 public: 158 MovedBugVisitor(const MoveChecker &Chk, const MemRegion *R, 159 const CXXRecordDecl *RD, MisuseKind MK) 160 : Chk(Chk), Region(R), RD(RD), MK(MK), Found(false) {} 161 162 void Profile(llvm::FoldingSetNodeID &ID) const override { 163 static int X = 0; 164 ID.AddPointer(&X); 165 ID.AddPointer(Region); 166 // Don't add RD because it's, in theory, uniquely determined by 167 // the region. In practice though, it's not always possible to obtain 168 // the declaration directly from the region, that's why we store it 169 // in the first place. 170 } 171 172 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, 173 BugReporterContext &BRC, 174 PathSensitiveBugReport &BR) override; 175 176 private: 177 const MoveChecker &Chk; 178 // The tracked region. 179 const MemRegion *Region; 180 // The class of the tracked object. 181 const CXXRecordDecl *RD; 182 // How exactly the object was misused. 183 const MisuseKind MK; 184 bool Found; 185 }; 186 187 AggressivenessKind Aggressiveness; 188 189 public: 190 void setAggressiveness(StringRef Str, CheckerManager &Mgr) { 191 Aggressiveness = 192 llvm::StringSwitch<AggressivenessKind>(Str) 193 .Case("KnownsOnly", AK_KnownsOnly) 194 .Case("KnownsAndLocals", AK_KnownsAndLocals) 195 .Case("All", AK_All) 196 .Default(AK_Invalid); 197 198 if (Aggressiveness == AK_Invalid) 199 Mgr.reportInvalidCheckerOptionValue(this, "WarnOn", 200 "either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value"); 201 }; 202 203 private: 204 mutable std::unique_ptr<BugType> BT; 205 206 // Check if the given form of potential misuse of a given object 207 // should be reported. If so, get it reported. The callback from which 208 // this function was called should immediately return after the call 209 // because this function adds one or two transitions. 210 void modelUse(ProgramStateRef State, const MemRegion *Region, 211 const CXXRecordDecl *RD, MisuseKind MK, 212 CheckerContext &C) const; 213 214 // Returns the exploded node against which the report was emitted. 215 // The caller *must* add any further transitions against this node. 216 ExplodedNode *reportBug(const MemRegion *Region, const CXXRecordDecl *RD, 217 CheckerContext &C, MisuseKind MK) const; 218 219 bool isInMoveSafeContext(const LocationContext *LC) const; 220 bool isStateResetMethod(const CXXMethodDecl *MethodDec) const; 221 bool isMoveSafeMethod(const CXXMethodDecl *MethodDec) const; 222 const ExplodedNode *getMoveLocation(const ExplodedNode *N, 223 const MemRegion *Region, 224 CheckerContext &C) const; 225 }; 226 } // end anonymous namespace 227 228 REGISTER_MAP_WITH_PROGRAMSTATE(TrackedRegionMap, const MemRegion *, RegionState) 229 230 // Define the inter-checker API. 231 namespace clang { 232 namespace ento { 233 namespace move { 234 bool isMovedFrom(ProgramStateRef State, const MemRegion *Region) { 235 const RegionState *RS = State->get<TrackedRegionMap>(Region); 236 return RS && (RS->isMoved() || RS->isReported()); 237 } 238 } // namespace move 239 } // namespace ento 240 } // namespace clang 241 242 // If a region is removed all of the subregions needs to be removed too. 243 static ProgramStateRef removeFromState(ProgramStateRef State, 244 const MemRegion *Region) { 245 if (!Region) 246 return State; 247 for (auto &E : State->get<TrackedRegionMap>()) { 248 if (E.first->isSubRegionOf(Region)) 249 State = State->remove<TrackedRegionMap>(E.first); 250 } 251 return State; 252 } 253 254 static bool isAnyBaseRegionReported(ProgramStateRef State, 255 const MemRegion *Region) { 256 for (auto &E : State->get<TrackedRegionMap>()) { 257 if (Region->isSubRegionOf(E.first) && E.second.isReported()) 258 return true; 259 } 260 return false; 261 } 262 263 static const MemRegion *unwrapRValueReferenceIndirection(const MemRegion *MR) { 264 if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) { 265 SymbolRef Sym = SR->getSymbol(); 266 if (Sym->getType()->isRValueReferenceType()) 267 if (const MemRegion *OriginMR = Sym->getOriginRegion()) 268 return OriginMR; 269 } 270 return MR; 271 } 272 273 PathDiagnosticPieceRef 274 MoveChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N, 275 BugReporterContext &BRC, 276 PathSensitiveBugReport &BR) { 277 // We need only the last move of the reported object's region. 278 // The visitor walks the ExplodedGraph backwards. 279 if (Found) 280 return nullptr; 281 ProgramStateRef State = N->getState(); 282 ProgramStateRef StatePrev = N->getFirstPred()->getState(); 283 const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region); 284 const RegionState *TrackedObjectPrev = 285 StatePrev->get<TrackedRegionMap>(Region); 286 if (!TrackedObject) 287 return nullptr; 288 if (TrackedObjectPrev && TrackedObject) 289 return nullptr; 290 291 // Retrieve the associated statement. 292 const Stmt *S = N->getStmtForDiagnostics(); 293 if (!S) 294 return nullptr; 295 Found = true; 296 297 SmallString<128> Str; 298 llvm::raw_svector_ostream OS(Str); 299 300 ObjectKind OK = Chk.classifyObject(Region, RD); 301 switch (OK.StdKind) { 302 case SK_SmartPtr: 303 if (MK == MK_Dereference) { 304 OS << "Smart pointer"; 305 Chk.explainObject(OS, Region, RD, MK); 306 OS << " is reset to null when moved from"; 307 break; 308 } 309 310 // If it's not a dereference, we don't care if it was reset to null 311 // or that it is even a smart pointer. 312 LLVM_FALLTHROUGH; 313 case SK_NonStd: 314 case SK_Safe: 315 OS << "Object"; 316 Chk.explainObject(OS, Region, RD, MK); 317 OS << " is moved"; 318 break; 319 case SK_Unsafe: 320 OS << "Object"; 321 Chk.explainObject(OS, Region, RD, MK); 322 OS << " is left in a valid but unspecified state after move"; 323 break; 324 } 325 326 // Generate the extra diagnostic. 327 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 328 N->getLocationContext()); 329 return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true); 330 } 331 332 const ExplodedNode *MoveChecker::getMoveLocation(const ExplodedNode *N, 333 const MemRegion *Region, 334 CheckerContext &C) const { 335 // Walk the ExplodedGraph backwards and find the first node that referred to 336 // the tracked region. 337 const ExplodedNode *MoveNode = N; 338 339 while (N) { 340 ProgramStateRef State = N->getState(); 341 if (!State->get<TrackedRegionMap>(Region)) 342 break; 343 MoveNode = N; 344 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 345 } 346 return MoveNode; 347 } 348 349 void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region, 350 const CXXRecordDecl *RD, MisuseKind MK, 351 CheckerContext &C) const { 352 assert(!C.isDifferent() && "No transitions should have been made by now"); 353 const RegionState *RS = State->get<TrackedRegionMap>(Region); 354 ObjectKind OK = classifyObject(Region, RD); 355 356 // Just in case: if it's not a smart pointer but it does have operator *, 357 // we shouldn't call the bug a dereference. 358 if (MK == MK_Dereference && OK.StdKind != SK_SmartPtr) 359 MK = MK_FunCall; 360 361 if (!RS || !shouldWarnAbout(OK, MK) 362 || isInMoveSafeContext(C.getLocationContext())) { 363 // Finalize changes made by the caller. 364 C.addTransition(State); 365 return; 366 } 367 368 // Don't report it in case if any base region is already reported. 369 // But still generate a sink in case of UB. 370 // And still finalize changes made by the caller. 371 if (isAnyBaseRegionReported(State, Region)) { 372 if (misuseCausesCrash(MK)) { 373 C.generateSink(State, C.getPredecessor()); 374 } else { 375 C.addTransition(State); 376 } 377 return; 378 } 379 380 ExplodedNode *N = reportBug(Region, RD, C, MK); 381 382 // If the program has already crashed on this path, don't bother. 383 if (N->isSink()) 384 return; 385 386 State = State->set<TrackedRegionMap>(Region, RegionState::getReported()); 387 C.addTransition(State, N); 388 } 389 390 ExplodedNode *MoveChecker::reportBug(const MemRegion *Region, 391 const CXXRecordDecl *RD, CheckerContext &C, 392 MisuseKind MK) const { 393 if (ExplodedNode *N = misuseCausesCrash(MK) ? C.generateErrorNode() 394 : C.generateNonFatalErrorNode()) { 395 396 if (!BT) 397 BT.reset(new BugType(this, "Use-after-move", 398 "C++ move semantics")); 399 400 // Uniqueing report to the same object. 401 PathDiagnosticLocation LocUsedForUniqueing; 402 const ExplodedNode *MoveNode = getMoveLocation(N, Region, C); 403 404 if (const Stmt *MoveStmt = MoveNode->getStmtForDiagnostics()) 405 LocUsedForUniqueing = PathDiagnosticLocation::createBegin( 406 MoveStmt, C.getSourceManager(), MoveNode->getLocationContext()); 407 408 // Creating the error message. 409 llvm::SmallString<128> Str; 410 llvm::raw_svector_ostream OS(Str); 411 switch(MK) { 412 case MK_FunCall: 413 OS << "Method called on moved-from object"; 414 explainObject(OS, Region, RD, MK); 415 break; 416 case MK_Copy: 417 OS << "Moved-from object"; 418 explainObject(OS, Region, RD, MK); 419 OS << " is copied"; 420 break; 421 case MK_Move: 422 OS << "Moved-from object"; 423 explainObject(OS, Region, RD, MK); 424 OS << " is moved"; 425 break; 426 case MK_Dereference: 427 OS << "Dereference of null smart pointer"; 428 explainObject(OS, Region, RD, MK); 429 break; 430 } 431 432 auto R = std::make_unique<PathSensitiveBugReport>( 433 *BT, OS.str(), N, LocUsedForUniqueing, 434 MoveNode->getLocationContext()->getDecl()); 435 R->addVisitor(std::make_unique<MovedBugVisitor>(*this, Region, RD, MK)); 436 C.emitReport(std::move(R)); 437 return N; 438 } 439 return nullptr; 440 } 441 442 void MoveChecker::checkPostCall(const CallEvent &Call, 443 CheckerContext &C) const { 444 const auto *AFC = dyn_cast<AnyFunctionCall>(&Call); 445 if (!AFC) 446 return; 447 448 ProgramStateRef State = C.getState(); 449 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl()); 450 if (!MethodDecl) 451 return; 452 453 // Check if an object became moved-from. 454 // Object can become moved from after a call to move assignment operator or 455 // move constructor . 456 const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl); 457 if (ConstructorDecl && !ConstructorDecl->isMoveConstructor()) 458 return; 459 460 if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator()) 461 return; 462 463 const auto ArgRegion = AFC->getArgSVal(0).getAsRegion(); 464 if (!ArgRegion) 465 return; 466 467 // Skip moving the object to itself. 468 const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call); 469 if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion) 470 return; 471 472 if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC)) 473 if (IC->getCXXThisVal().getAsRegion() == ArgRegion) 474 return; 475 476 const MemRegion *BaseRegion = ArgRegion->getBaseRegion(); 477 // Skip temp objects because of their short lifetime. 478 if (BaseRegion->getAs<CXXTempObjectRegion>() || 479 AFC->getArgExpr(0)->isRValue()) 480 return; 481 // If it has already been reported do not need to modify the state. 482 483 if (State->get<TrackedRegionMap>(ArgRegion)) 484 return; 485 486 const CXXRecordDecl *RD = MethodDecl->getParent(); 487 ObjectKind OK = classifyObject(ArgRegion, RD); 488 if (shouldBeTracked(OK)) { 489 // Mark object as moved-from. 490 State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved()); 491 C.addTransition(State); 492 return; 493 } 494 assert(!C.isDifferent() && "Should not have made transitions on this path!"); 495 } 496 497 bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const { 498 // We abandon the cases where bool/void/void* conversion happens. 499 if (const auto *ConversionDec = 500 dyn_cast_or_null<CXXConversionDecl>(MethodDec)) { 501 const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull(); 502 if (!Tp) 503 return false; 504 if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType()) 505 return true; 506 } 507 // Function call `empty` can be skipped. 508 return (MethodDec && MethodDec->getDeclName().isIdentifier() && 509 (MethodDec->getName().lower() == "empty" || 510 MethodDec->getName().lower() == "isempty")); 511 } 512 513 bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const { 514 if (!MethodDec) 515 return false; 516 if (MethodDec->hasAttr<ReinitializesAttr>()) 517 return true; 518 if (MethodDec->getDeclName().isIdentifier()) { 519 std::string MethodName = MethodDec->getName().lower(); 520 // TODO: Some of these methods (eg., resize) are not always resetting 521 // the state, so we should consider looking at the arguments. 522 if (MethodName == "assign" || MethodName == "clear" || 523 MethodName == "destroy" || MethodName == "reset" || 524 MethodName == "resize" || MethodName == "shrink") 525 return true; 526 } 527 return false; 528 } 529 530 // Don't report an error inside a move related operation. 531 // We assume that the programmer knows what she does. 532 bool MoveChecker::isInMoveSafeContext(const LocationContext *LC) const { 533 do { 534 const auto *CtxDec = LC->getDecl(); 535 auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec); 536 auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec); 537 auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec); 538 if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) || 539 (MethodDec && MethodDec->isOverloadedOperator() && 540 MethodDec->getOverloadedOperator() == OO_Equal) || 541 isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec)) 542 return true; 543 } while ((LC = LC->getParent())); 544 return false; 545 } 546 547 bool MoveChecker::belongsTo(const CXXRecordDecl *RD, 548 const llvm::StringSet<> &Set) const { 549 const IdentifierInfo *II = RD->getIdentifier(); 550 return II && Set.count(II->getName()); 551 } 552 553 MoveChecker::ObjectKind 554 MoveChecker::classifyObject(const MemRegion *MR, 555 const CXXRecordDecl *RD) const { 556 // Local variables and local rvalue references are classified as "Local". 557 // For the purposes of this checker, we classify move-safe STL types 558 // as not-"STL" types, because that's how the checker treats them. 559 MR = unwrapRValueReferenceIndirection(MR); 560 bool IsLocal = 561 MR && isa<VarRegion>(MR) && isa<StackSpaceRegion>(MR->getMemorySpace()); 562 563 if (!RD || !RD->getDeclContext()->isStdNamespace()) 564 return { IsLocal, SK_NonStd }; 565 566 if (belongsTo(RD, StdSmartPtrClasses)) 567 return { IsLocal, SK_SmartPtr }; 568 569 if (belongsTo(RD, StdSafeClasses)) 570 return { IsLocal, SK_Safe }; 571 572 return { IsLocal, SK_Unsafe }; 573 } 574 575 void MoveChecker::explainObject(llvm::raw_ostream &OS, const MemRegion *MR, 576 const CXXRecordDecl *RD, MisuseKind MK) const { 577 // We may need a leading space every time we actually explain anything, 578 // and we never know if we are to explain anything until we try. 579 if (const auto DR = 580 dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) { 581 const auto *RegionDecl = cast<NamedDecl>(DR->getDecl()); 582 OS << " '" << RegionDecl->getNameAsString() << "'"; 583 } 584 585 ObjectKind OK = classifyObject(MR, RD); 586 switch (OK.StdKind) { 587 case SK_NonStd: 588 case SK_Safe: 589 break; 590 case SK_SmartPtr: 591 if (MK != MK_Dereference) 592 break; 593 594 // We only care about the type if it's a dereference. 595 LLVM_FALLTHROUGH; 596 case SK_Unsafe: 597 OS << " of type '" << RD->getQualifiedNameAsString() << "'"; 598 break; 599 }; 600 } 601 602 void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const { 603 ProgramStateRef State = C.getState(); 604 605 // Remove the MemRegions from the map on which a ctor/dtor call or assignment 606 // happened. 607 608 // Checking constructor calls. 609 if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) { 610 State = removeFromState(State, CC->getCXXThisVal().getAsRegion()); 611 auto CtorDec = CC->getDecl(); 612 // Check for copying a moved-from object and report the bug. 613 if (CtorDec && CtorDec->isCopyOrMoveConstructor()) { 614 const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion(); 615 const CXXRecordDecl *RD = CtorDec->getParent(); 616 MisuseKind MK = CtorDec->isMoveConstructor() ? MK_Move : MK_Copy; 617 modelUse(State, ArgRegion, RD, MK, C); 618 return; 619 } 620 } 621 622 const auto IC = dyn_cast<CXXInstanceCall>(&Call); 623 if (!IC) 624 return; 625 626 // Calling a destructor on a moved object is fine. 627 if (isa<CXXDestructorCall>(IC)) 628 return; 629 630 const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion(); 631 if (!ThisRegion) 632 return; 633 634 // The remaining part is check only for method call on a moved-from object. 635 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl()); 636 if (!MethodDecl) 637 return; 638 639 // We want to investigate the whole object, not only sub-object of a parent 640 // class in which the encountered method defined. 641 ThisRegion = ThisRegion->getMostDerivedObjectRegion(); 642 643 if (isStateResetMethod(MethodDecl)) { 644 State = removeFromState(State, ThisRegion); 645 C.addTransition(State); 646 return; 647 } 648 649 if (isMoveSafeMethod(MethodDecl)) 650 return; 651 652 // Store class declaration as well, for bug reporting purposes. 653 const CXXRecordDecl *RD = MethodDecl->getParent(); 654 655 if (MethodDecl->isOverloadedOperator()) { 656 OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator(); 657 658 if (OOK == OO_Equal) { 659 // Remove the tracked object for every assignment operator, but report bug 660 // only for move or copy assignment's argument. 661 State = removeFromState(State, ThisRegion); 662 663 if (MethodDecl->isCopyAssignmentOperator() || 664 MethodDecl->isMoveAssignmentOperator()) { 665 const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion(); 666 MisuseKind MK = 667 MethodDecl->isMoveAssignmentOperator() ? MK_Move : MK_Copy; 668 modelUse(State, ArgRegion, RD, MK, C); 669 return; 670 } 671 C.addTransition(State); 672 return; 673 } 674 675 if (OOK == OO_Star || OOK == OO_Arrow) { 676 modelUse(State, ThisRegion, RD, MK_Dereference, C); 677 return; 678 } 679 } 680 681 modelUse(State, ThisRegion, RD, MK_FunCall, C); 682 } 683 684 void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper, 685 CheckerContext &C) const { 686 ProgramStateRef State = C.getState(); 687 TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>(); 688 for (TrackedRegionMapTy::value_type E : TrackedRegions) { 689 const MemRegion *Region = E.first; 690 bool IsRegDead = !SymReaper.isLiveRegion(Region); 691 692 // Remove the dead regions from the region map. 693 if (IsRegDead) { 694 State = State->remove<TrackedRegionMap>(Region); 695 } 696 } 697 C.addTransition(State); 698 } 699 700 ProgramStateRef MoveChecker::checkRegionChanges( 701 ProgramStateRef State, const InvalidatedSymbols *Invalidated, 702 ArrayRef<const MemRegion *> RequestedRegions, 703 ArrayRef<const MemRegion *> InvalidatedRegions, 704 const LocationContext *LCtx, const CallEvent *Call) const { 705 if (Call) { 706 // Relax invalidation upon function calls: only invalidate parameters 707 // that are passed directly via non-const pointers or non-const references 708 // or rvalue references. 709 // In case of an InstanceCall don't invalidate the this-region since 710 // it is fully handled in checkPreCall and checkPostCall. 711 const MemRegion *ThisRegion = nullptr; 712 if (const auto *IC = dyn_cast<CXXInstanceCall>(Call)) 713 ThisRegion = IC->getCXXThisVal().getAsRegion(); 714 715 // Requested ("explicit") regions are the regions passed into the call 716 // directly, but not all of them end up being invalidated. 717 // But when they do, they appear in the InvalidatedRegions array as well. 718 for (const auto *Region : RequestedRegions) { 719 if (ThisRegion != Region) { 720 if (llvm::find(InvalidatedRegions, Region) != 721 std::end(InvalidatedRegions)) { 722 State = removeFromState(State, Region); 723 } 724 } 725 } 726 } else { 727 // For invalidations that aren't caused by calls, assume nothing. In 728 // particular, direct write into an object's field invalidates the status. 729 for (const auto *Region : InvalidatedRegions) 730 State = removeFromState(State, Region->getBaseRegion()); 731 } 732 733 return State; 734 } 735 736 void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State, 737 const char *NL, const char *Sep) const { 738 739 TrackedRegionMapTy RS = State->get<TrackedRegionMap>(); 740 741 if (!RS.isEmpty()) { 742 Out << Sep << "Moved-from objects :" << NL; 743 for (auto I: RS) { 744 I.first->dumpToStream(Out); 745 if (I.second.isMoved()) 746 Out << ": moved"; 747 else 748 Out << ": moved and reported"; 749 Out << NL; 750 } 751 } 752 } 753 void ento::registerMoveChecker(CheckerManager &mgr) { 754 MoveChecker *chk = mgr.registerChecker<MoveChecker>(); 755 chk->setAggressiveness( 756 mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr); 757 } 758 759 bool ento::shouldRegisterMoveChecker(const LangOptions &LO) { 760 return true; 761 } 762