MoveChecker.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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/Driver/DriverDiagnostic.h"
  16. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  18. #include "clang/StaticAnalyzer/Core/Checker.h"
  19. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  22. #include "llvm/ADT/StringSet.h"
  23. using namespace clang;
  24. using namespace ento;
  25. namespace {
  26. struct RegionState {
  27. private:
  28. enum Kind { Moved, Reported } K;
  29. RegionState(Kind InK) : K(InK) {}
  30. public:
  31. bool isReported() const { return K == Reported; }
  32. bool isMoved() const { return K == Moved; }
  33. static RegionState getReported() { return RegionState(Reported); }
  34. static RegionState getMoved() { return RegionState(Moved); }
  35. bool operator==(const RegionState &X) const { return K == X.K; }
  36. void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
  37. };
  38. } // end of anonymous namespace
  39. namespace {
  40. class MoveChecker
  41. : public Checker<check::PreCall, check::PostCall,
  42. check::DeadSymbols, check::RegionChanges> {
  43. public:
  44. void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
  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. mutable std::unique_ptr<BugType> BT;
  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. LLVM_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. if (!BT)
  346. BT.reset(new BugType(this, "Use-after-move",
  347. "C++ move semantics"));
  348. // Uniqueing report to the same object.
  349. PathDiagnosticLocation LocUsedForUniqueing;
  350. const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
  351. if (const Stmt *MoveStmt = MoveNode->getStmtForDiagnostics())
  352. LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
  353. MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
  354. // Creating the error message.
  355. llvm::SmallString<128> Str;
  356. llvm::raw_svector_ostream OS(Str);
  357. switch(MK) {
  358. case MK_FunCall:
  359. OS << "Method called on moved-from object";
  360. explainObject(OS, Region, RD, MK);
  361. break;
  362. case MK_Copy:
  363. OS << "Moved-from object";
  364. explainObject(OS, Region, RD, MK);
  365. OS << " is copied";
  366. break;
  367. case MK_Move:
  368. OS << "Moved-from object";
  369. explainObject(OS, Region, RD, MK);
  370. OS << " is moved";
  371. break;
  372. case MK_Dereference:
  373. OS << "Dereference of null smart pointer";
  374. explainObject(OS, Region, RD, MK);
  375. break;
  376. }
  377. auto R = std::make_unique<PathSensitiveBugReport>(
  378. *BT, OS.str(), N, LocUsedForUniqueing,
  379. MoveNode->getLocationContext()->getDecl());
  380. R->addVisitor(std::make_unique<MovedBugVisitor>(*this, Region, RD, MK));
  381. C.emitReport(std::move(R));
  382. return N;
  383. }
  384. return nullptr;
  385. }
  386. void MoveChecker::checkPostCall(const CallEvent &Call,
  387. CheckerContext &C) const {
  388. const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
  389. if (!AFC)
  390. return;
  391. ProgramStateRef State = C.getState();
  392. const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
  393. if (!MethodDecl)
  394. return;
  395. // Check if an object became moved-from.
  396. // Object can become moved from after a call to move assignment operator or
  397. // move constructor .
  398. const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
  399. if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
  400. return;
  401. if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
  402. return;
  403. const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
  404. if (!ArgRegion)
  405. return;
  406. // Skip moving the object to itself.
  407. const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
  408. if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
  409. return;
  410. if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
  411. if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
  412. return;
  413. const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
  414. // Skip temp objects because of their short lifetime.
  415. if (BaseRegion->getAs<CXXTempObjectRegion>() ||
  416. AFC->getArgExpr(0)->isRValue())
  417. return;
  418. // If it has already been reported do not need to modify the state.
  419. if (State->get<TrackedRegionMap>(ArgRegion))
  420. return;
  421. const CXXRecordDecl *RD = MethodDecl->getParent();
  422. ObjectKind OK = classifyObject(ArgRegion, RD);
  423. if (shouldBeTracked(OK)) {
  424. // Mark object as moved-from.
  425. State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
  426. C.addTransition(State);
  427. return;
  428. }
  429. assert(!C.isDifferent() && "Should not have made transitions on this path!");
  430. }
  431. bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const {
  432. // We abandon the cases where bool/void/void* conversion happens.
  433. if (const auto *ConversionDec =
  434. dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
  435. const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
  436. if (!Tp)
  437. return false;
  438. if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType())
  439. return true;
  440. }
  441. // Function call `empty` can be skipped.
  442. return (MethodDec && MethodDec->getDeclName().isIdentifier() &&
  443. (MethodDec->getName().lower() == "empty" ||
  444. MethodDec->getName().lower() == "isempty"));
  445. }
  446. bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const {
  447. if (!MethodDec)
  448. return false;
  449. if (MethodDec->hasAttr<ReinitializesAttr>())
  450. return true;
  451. if (MethodDec->getDeclName().isIdentifier()) {
  452. std::string MethodName = MethodDec->getName().lower();
  453. // TODO: Some of these methods (eg., resize) are not always resetting
  454. // the state, so we should consider looking at the arguments.
  455. if (MethodName == "assign" || MethodName == "clear" ||
  456. MethodName == "destroy" || MethodName == "reset" ||
  457. MethodName == "resize" || MethodName == "shrink")
  458. return true;
  459. }
  460. return false;
  461. }
  462. // Don't report an error inside a move related operation.
  463. // We assume that the programmer knows what she does.
  464. bool MoveChecker::isInMoveSafeContext(const LocationContext *LC) const {
  465. do {
  466. const auto *CtxDec = LC->getDecl();
  467. auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
  468. auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
  469. auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
  470. if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
  471. (MethodDec && MethodDec->isOverloadedOperator() &&
  472. MethodDec->getOverloadedOperator() == OO_Equal) ||
  473. isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec))
  474. return true;
  475. } while ((LC = LC->getParent()));
  476. return false;
  477. }
  478. bool MoveChecker::belongsTo(const CXXRecordDecl *RD,
  479. const llvm::StringSet<> &Set) const {
  480. const IdentifierInfo *II = RD->getIdentifier();
  481. return II && Set.count(II->getName());
  482. }
  483. MoveChecker::ObjectKind
  484. MoveChecker::classifyObject(const MemRegion *MR,
  485. const CXXRecordDecl *RD) const {
  486. // Local variables and local rvalue references are classified as "Local".
  487. // For the purposes of this checker, we classify move-safe STL types
  488. // as not-"STL" types, because that's how the checker treats them.
  489. MR = unwrapRValueReferenceIndirection(MR);
  490. bool IsLocal =
  491. MR && isa<VarRegion>(MR) && isa<StackSpaceRegion>(MR->getMemorySpace());
  492. if (!RD || !RD->getDeclContext()->isStdNamespace())
  493. return { IsLocal, SK_NonStd };
  494. if (belongsTo(RD, StdSmartPtrClasses))
  495. return { IsLocal, SK_SmartPtr };
  496. if (belongsTo(RD, StdSafeClasses))
  497. return { IsLocal, SK_Safe };
  498. return { IsLocal, SK_Unsafe };
  499. }
  500. void MoveChecker::explainObject(llvm::raw_ostream &OS, const MemRegion *MR,
  501. const CXXRecordDecl *RD, MisuseKind MK) const {
  502. // We may need a leading space every time we actually explain anything,
  503. // and we never know if we are to explain anything until we try.
  504. if (const auto DR =
  505. dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) {
  506. const auto *RegionDecl = cast<NamedDecl>(DR->getDecl());
  507. OS << " '" << RegionDecl->getNameAsString() << "'";
  508. }
  509. ObjectKind OK = classifyObject(MR, RD);
  510. switch (OK.StdKind) {
  511. case SK_NonStd:
  512. case SK_Safe:
  513. break;
  514. case SK_SmartPtr:
  515. if (MK != MK_Dereference)
  516. break;
  517. // We only care about the type if it's a dereference.
  518. LLVM_FALLTHROUGH;
  519. case SK_Unsafe:
  520. OS << " of type '" << RD->getQualifiedNameAsString() << "'";
  521. break;
  522. };
  523. }
  524. void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const {
  525. ProgramStateRef State = C.getState();
  526. // Remove the MemRegions from the map on which a ctor/dtor call or assignment
  527. // happened.
  528. // Checking constructor calls.
  529. if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
  530. State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
  531. auto CtorDec = CC->getDecl();
  532. // Check for copying a moved-from object and report the bug.
  533. if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
  534. const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
  535. const CXXRecordDecl *RD = CtorDec->getParent();
  536. MisuseKind MK = CtorDec->isMoveConstructor() ? MK_Move : MK_Copy;
  537. modelUse(State, ArgRegion, RD, MK, C);
  538. return;
  539. }
  540. }
  541. const auto IC = dyn_cast<CXXInstanceCall>(&Call);
  542. if (!IC)
  543. return;
  544. // Calling a destructor on a moved object is fine.
  545. if (isa<CXXDestructorCall>(IC))
  546. return;
  547. const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
  548. if (!ThisRegion)
  549. return;
  550. // The remaining part is check only for method call on a moved-from object.
  551. const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
  552. if (!MethodDecl)
  553. return;
  554. // We want to investigate the whole object, not only sub-object of a parent
  555. // class in which the encountered method defined.
  556. ThisRegion = ThisRegion->getMostDerivedObjectRegion();
  557. if (isStateResetMethod(MethodDecl)) {
  558. State = removeFromState(State, ThisRegion);
  559. C.addTransition(State);
  560. return;
  561. }
  562. if (isMoveSafeMethod(MethodDecl))
  563. return;
  564. // Store class declaration as well, for bug reporting purposes.
  565. const CXXRecordDecl *RD = MethodDecl->getParent();
  566. if (MethodDecl->isOverloadedOperator()) {
  567. OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator();
  568. if (OOK == OO_Equal) {
  569. // Remove the tracked object for every assignment operator, but report bug
  570. // only for move or copy assignment's argument.
  571. State = removeFromState(State, ThisRegion);
  572. if (MethodDecl->isCopyAssignmentOperator() ||
  573. MethodDecl->isMoveAssignmentOperator()) {
  574. const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
  575. MisuseKind MK =
  576. MethodDecl->isMoveAssignmentOperator() ? MK_Move : MK_Copy;
  577. modelUse(State, ArgRegion, RD, MK, C);
  578. return;
  579. }
  580. C.addTransition(State);
  581. return;
  582. }
  583. if (OOK == OO_Star || OOK == OO_Arrow) {
  584. modelUse(State, ThisRegion, RD, MK_Dereference, C);
  585. return;
  586. }
  587. }
  588. modelUse(State, ThisRegion, RD, MK_FunCall, C);
  589. }
  590. void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  591. CheckerContext &C) const {
  592. ProgramStateRef State = C.getState();
  593. TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
  594. for (TrackedRegionMapTy::value_type E : TrackedRegions) {
  595. const MemRegion *Region = E.first;
  596. bool IsRegDead = !SymReaper.isLiveRegion(Region);
  597. // Remove the dead regions from the region map.
  598. if (IsRegDead) {
  599. State = State->remove<TrackedRegionMap>(Region);
  600. }
  601. }
  602. C.addTransition(State);
  603. }
  604. ProgramStateRef MoveChecker::checkRegionChanges(
  605. ProgramStateRef State, const InvalidatedSymbols *Invalidated,
  606. ArrayRef<const MemRegion *> RequestedRegions,
  607. ArrayRef<const MemRegion *> InvalidatedRegions,
  608. const LocationContext *LCtx, const CallEvent *Call) const {
  609. if (Call) {
  610. // Relax invalidation upon function calls: only invalidate parameters
  611. // that are passed directly via non-const pointers or non-const references
  612. // or rvalue references.
  613. // In case of an InstanceCall don't invalidate the this-region since
  614. // it is fully handled in checkPreCall and checkPostCall.
  615. const MemRegion *ThisRegion = nullptr;
  616. if (const auto *IC = dyn_cast<CXXInstanceCall>(Call))
  617. ThisRegion = IC->getCXXThisVal().getAsRegion();
  618. // Requested ("explicit") regions are the regions passed into the call
  619. // directly, but not all of them end up being invalidated.
  620. // But when they do, they appear in the InvalidatedRegions array as well.
  621. for (const auto *Region : RequestedRegions) {
  622. if (ThisRegion != Region) {
  623. if (llvm::find(InvalidatedRegions, Region) !=
  624. std::end(InvalidatedRegions)) {
  625. State = removeFromState(State, Region);
  626. }
  627. }
  628. }
  629. } else {
  630. // For invalidations that aren't caused by calls, assume nothing. In
  631. // particular, direct write into an object's field invalidates the status.
  632. for (const auto *Region : InvalidatedRegions)
  633. State = removeFromState(State, Region->getBaseRegion());
  634. }
  635. return State;
  636. }
  637. void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State,
  638. const char *NL, const char *Sep) const {
  639. TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
  640. if (!RS.isEmpty()) {
  641. Out << Sep << "Moved-from objects :" << NL;
  642. for (auto I: RS) {
  643. I.first->dumpToStream(Out);
  644. if (I.second.isMoved())
  645. Out << ": moved";
  646. else
  647. Out << ": moved and reported";
  648. Out << NL;
  649. }
  650. }
  651. }
  652. void ento::registerMoveChecker(CheckerManager &mgr) {
  653. MoveChecker *chk = mgr.registerChecker<MoveChecker>();
  654. chk->setAggressiveness(
  655. mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr);
  656. }
  657. bool ento::shouldRegisterMoveChecker(const LangOptions &LO) {
  658. return true;
  659. }