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