MoveChecker.cpp 27 KB

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