MoveChecker.cpp 26 KB

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