MoveChecker.cpp 27 KB

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