]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MisusedMovedObjectChecker.cpp
MFC r345805: Unify SCSI_STATUS_BUSY retry handling with other cases.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / StaticAnalyzer / Checkers / MisusedMovedObjectChecker.cpp
1 // MisusedMovedObjectChecker.cpp - Check use of moved-from objects. - C++ -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This defines checker which checks for potential misuses of a moved-from
11 // object. That means method calls on the object or copying it in moved-from
12 // state.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "ClangSACheckers.h"
17 #include "clang/AST/ExprCXX.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
24 using namespace clang;
25 using namespace ento;
26
27 namespace {
28
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
45 class MisusedMovedObjectChecker
46     : public Checker<check::PreCall, check::PostCall, check::EndFunction,
47                      check::DeadSymbols, check::RegionChanges> {
48 public:
49   void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
50   void checkPreCall(const CallEvent &MC, CheckerContext &C) const;
51   void checkPostCall(const CallEvent &MC, CheckerContext &C) const;
52   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
53   ProgramStateRef
54   checkRegionChanges(ProgramStateRef State,
55                      const InvalidatedSymbols *Invalidated,
56                      ArrayRef<const MemRegion *> ExplicitRegions,
57                      ArrayRef<const MemRegion *> Regions,
58                      const LocationContext *LCtx, const CallEvent *Call) const;
59   void printState(raw_ostream &Out, ProgramStateRef State,
60                   const char *NL, const char *Sep) const override;
61
62 private:
63   enum MisuseKind {MK_FunCall, MK_Copy, MK_Move};
64   class MovedBugVisitor : public BugReporterVisitor {
65   public:
66     MovedBugVisitor(const MemRegion *R) : Region(R), Found(false) {}
67
68     void Profile(llvm::FoldingSetNodeID &ID) const override {
69       static int X = 0;
70       ID.AddPointer(&X);
71       ID.AddPointer(Region);
72     }
73
74     std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
75                                                    const ExplodedNode *PrevN,
76                                                    BugReporterContext &BRC,
77                                                    BugReport &BR) override;
78
79   private:
80     // The tracked region.
81     const MemRegion *Region;
82     bool Found;
83   };
84
85   mutable std::unique_ptr<BugType> BT;
86   ExplodedNode *reportBug(const MemRegion *Region, const CallEvent &Call,
87                           CheckerContext &C, MisuseKind MK) const;
88   bool isInMoveSafeContext(const LocationContext *LC) const;
89   bool isStateResetMethod(const CXXMethodDecl *MethodDec) const;
90   bool isMoveSafeMethod(const CXXMethodDecl *MethodDec) const;
91   const ExplodedNode *getMoveLocation(const ExplodedNode *N,
92                                       const MemRegion *Region,
93                                       CheckerContext &C) const;
94 };
95 } // end anonymous namespace
96
97 REGISTER_MAP_WITH_PROGRAMSTATE(TrackedRegionMap, const MemRegion *, RegionState)
98
99 // If a region is removed all of the subregions needs to be removed too.
100 static ProgramStateRef removeFromState(ProgramStateRef State,
101                                        const MemRegion *Region) {
102   if (!Region)
103     return State;
104   for (auto &E : State->get<TrackedRegionMap>()) {
105     if (E.first->isSubRegionOf(Region))
106       State = State->remove<TrackedRegionMap>(E.first);
107   }
108   return State;
109 }
110
111 static bool isAnyBaseRegionReported(ProgramStateRef State,
112                                     const MemRegion *Region) {
113   for (auto &E : State->get<TrackedRegionMap>()) {
114     if (Region->isSubRegionOf(E.first) && E.second.isReported())
115       return true;
116   }
117   return false;
118 }
119
120 std::shared_ptr<PathDiagnosticPiece>
121 MisusedMovedObjectChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
122                                                       const ExplodedNode *PrevN,
123                                                       BugReporterContext &BRC,
124                                                       BugReport &BR) {
125   // We need only the last move of the reported object's region.
126   // The visitor walks the ExplodedGraph backwards.
127   if (Found)
128     return nullptr;
129   ProgramStateRef State = N->getState();
130   ProgramStateRef StatePrev = PrevN->getState();
131   const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
132   const RegionState *TrackedObjectPrev =
133       StatePrev->get<TrackedRegionMap>(Region);
134   if (!TrackedObject)
135     return nullptr;
136   if (TrackedObjectPrev && TrackedObject)
137     return nullptr;
138
139   // Retrieve the associated statement.
140   const Stmt *S = PathDiagnosticLocation::getStmt(N);
141   if (!S)
142     return nullptr;
143   Found = true;
144
145   std::string ObjectName;
146   if (const auto DecReg = Region->getAs<DeclRegion>()) {
147     const auto *RegionDecl = dyn_cast<NamedDecl>(DecReg->getDecl());
148     ObjectName = RegionDecl->getNameAsString();
149   }
150   std::string InfoText;
151   if (ObjectName != "")
152     InfoText = "'" + ObjectName + "' became 'moved-from' here";
153   else
154     InfoText = "Became 'moved-from' here";
155
156   // Generate the extra diagnostic.
157   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
158                              N->getLocationContext());
159   return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
160 }
161
162 const ExplodedNode *MisusedMovedObjectChecker::getMoveLocation(
163     const ExplodedNode *N, const MemRegion *Region, CheckerContext &C) const {
164   // Walk the ExplodedGraph backwards and find the first node that referred to
165   // the tracked region.
166   const ExplodedNode *MoveNode = N;
167
168   while (N) {
169     ProgramStateRef State = N->getState();
170     if (!State->get<TrackedRegionMap>(Region))
171       break;
172     MoveNode = N;
173     N = N->pred_empty() ? nullptr : *(N->pred_begin());
174   }
175   return MoveNode;
176 }
177
178 ExplodedNode *MisusedMovedObjectChecker::reportBug(const MemRegion *Region,
179                                                    const CallEvent &Call,
180                                                    CheckerContext &C,
181                                                    MisuseKind MK) const {
182   if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
183     if (!BT)
184       BT.reset(new BugType(this, "Usage of a 'moved-from' object",
185                            "C++ move semantics"));
186
187     // Uniqueing report to the same object.
188     PathDiagnosticLocation LocUsedForUniqueing;
189     const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
190
191     if (const Stmt *MoveStmt = PathDiagnosticLocation::getStmt(MoveNode))
192       LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
193           MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
194
195     // Creating the error message.
196     std::string ErrorMessage;
197     switch(MK) {
198       case MK_FunCall:
199         ErrorMessage = "Method call on a 'moved-from' object";
200         break;
201       case MK_Copy:
202         ErrorMessage = "Copying a 'moved-from' object";
203         break;
204       case MK_Move:
205         ErrorMessage = "Moving a 'moved-from' object";
206         break;
207     }
208     if (const auto DecReg = Region->getAs<DeclRegion>()) {
209       const auto *RegionDecl = dyn_cast<NamedDecl>(DecReg->getDecl());
210       ErrorMessage += " '" + RegionDecl->getNameAsString() + "'";
211     }
212
213     auto R =
214         llvm::make_unique<BugReport>(*BT, ErrorMessage, N, LocUsedForUniqueing,
215                                      MoveNode->getLocationContext()->getDecl());
216     R->addVisitor(llvm::make_unique<MovedBugVisitor>(Region));
217     C.emitReport(std::move(R));
218     return N;
219   }
220   return nullptr;
221 }
222
223 // Removing the function parameters' MemRegion from the state. This is needed
224 // for PODs where the trivial destructor does not even created nor executed.
225 void MisusedMovedObjectChecker::checkEndFunction(const ReturnStmt *RS,
226                                                  CheckerContext &C) const {
227   auto State = C.getState();
228   TrackedRegionMapTy Objects = State->get<TrackedRegionMap>();
229   if (Objects.isEmpty())
230     return;
231
232   auto LC = C.getLocationContext();
233
234   const auto LD = dyn_cast_or_null<FunctionDecl>(LC->getDecl());
235   if (!LD)
236     return;
237   llvm::SmallSet<const MemRegion *, 8> InvalidRegions;
238
239   for (auto Param : LD->parameters()) {
240     auto Type = Param->getType().getTypePtrOrNull();
241     if (!Type)
242       continue;
243     if (!Type->isPointerType() && !Type->isReferenceType()) {
244       InvalidRegions.insert(State->getLValue(Param, LC).getAsRegion());
245     }
246   }
247
248   if (InvalidRegions.empty())
249     return;
250
251   for (const auto &E : State->get<TrackedRegionMap>()) {
252     if (InvalidRegions.count(E.first->getBaseRegion()))
253       State = State->remove<TrackedRegionMap>(E.first);
254   }
255
256   C.addTransition(State);
257 }
258
259 void MisusedMovedObjectChecker::checkPostCall(const CallEvent &Call,
260                                               CheckerContext &C) const {
261   const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
262   if (!AFC)
263     return;
264
265   ProgramStateRef State = C.getState();
266   const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
267   if (!MethodDecl)
268     return;
269
270   const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
271
272   const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
273   // Check if an object became moved-from.
274   // Object can become moved from after a call to move assignment operator or
275   // move constructor .
276   if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
277     return;
278
279   if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
280     return;
281
282   const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
283   if (!ArgRegion)
284     return;
285
286   // Skip moving the object to itself.
287   if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
288     return;
289   if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
290     if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
291       return;
292
293   const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
294   // Skip temp objects because of their short lifetime.
295   if (BaseRegion->getAs<CXXTempObjectRegion>() ||
296       AFC->getArgExpr(0)->isRValue())
297     return;
298   // If it has already been reported do not need to modify the state.
299
300   if (State->get<TrackedRegionMap>(ArgRegion))
301     return;
302   // Mark object as moved-from.
303   State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
304   C.addTransition(State);
305 }
306
307 bool MisusedMovedObjectChecker::isMoveSafeMethod(
308     const CXXMethodDecl *MethodDec) const {
309   // We abandon the cases where bool/void/void* conversion happens.
310   if (const auto *ConversionDec =
311           dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
312     const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
313     if (!Tp)
314       return false;
315     if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType())
316       return true;
317   }
318   // Function call `empty` can be skipped.
319   if (MethodDec && MethodDec->getDeclName().isIdentifier() &&
320       (MethodDec->getName().lower() == "empty" ||
321        MethodDec->getName().lower() == "isempty"))
322     return true;
323
324   return false;
325 }
326
327 bool MisusedMovedObjectChecker::isStateResetMethod(
328     const CXXMethodDecl *MethodDec) const {
329   if (MethodDec && MethodDec->getDeclName().isIdentifier()) {
330     std::string MethodName = MethodDec->getName().lower();
331     if (MethodName == "reset" || MethodName == "clear" ||
332         MethodName == "destroy")
333       return true;
334   }
335   return false;
336 }
337
338 // Don't report an error inside a move related operation.
339 // We assume that the programmer knows what she does.
340 bool MisusedMovedObjectChecker::isInMoveSafeContext(
341     const LocationContext *LC) const {
342   do {
343     const auto *CtxDec = LC->getDecl();
344     auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
345     auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
346     auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
347     if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
348         (MethodDec && MethodDec->isOverloadedOperator() &&
349          MethodDec->getOverloadedOperator() == OO_Equal) ||
350         isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec))
351       return true;
352   } while ((LC = LC->getParent()));
353   return false;
354 }
355
356 void MisusedMovedObjectChecker::checkPreCall(const CallEvent &Call,
357                                              CheckerContext &C) const {
358   ProgramStateRef State = C.getState();
359   const LocationContext *LC = C.getLocationContext();
360   ExplodedNode *N = nullptr;
361
362   // Remove the MemRegions from the map on which a ctor/dtor call or assignment
363   // happened.
364
365   // Checking constructor calls.
366   if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
367     State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
368     auto CtorDec = CC->getDecl();
369     // Check for copying a moved-from object and report the bug.
370     if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
371       const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
372       const RegionState *ArgState = State->get<TrackedRegionMap>(ArgRegion);
373       if (ArgState && ArgState->isMoved()) {
374         if (!isInMoveSafeContext(LC)) {
375           if(CtorDec->isMoveConstructor())
376             N = reportBug(ArgRegion, Call, C, MK_Move);
377           else
378             N = reportBug(ArgRegion, Call, C, MK_Copy);
379           State = State->set<TrackedRegionMap>(ArgRegion,
380                                                RegionState::getReported());
381         }
382       }
383     }
384     C.addTransition(State, N);
385     return;
386   }
387
388   const auto IC = dyn_cast<CXXInstanceCall>(&Call);
389   if (!IC)
390     return;
391   // In case of destructor call we do not track the object anymore.
392   const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
393   if (!ThisRegion)
394     return;
395
396   if (dyn_cast_or_null<CXXDestructorDecl>(Call.getDecl())) {
397     State = removeFromState(State, ThisRegion);
398     C.addTransition(State);
399     return;
400   }
401
402   const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
403   if (!MethodDecl)
404     return;
405   // Checking assignment operators.
406   bool OperatorEq = MethodDecl->isOverloadedOperator() &&
407                     MethodDecl->getOverloadedOperator() == OO_Equal;
408   // Remove the tracked object for every assignment operator, but report bug
409   // only for move or copy assignment's argument.
410   if (OperatorEq) {
411     State = removeFromState(State, ThisRegion);
412     if (MethodDecl->isCopyAssignmentOperator() ||
413         MethodDecl->isMoveAssignmentOperator()) {
414       const RegionState *ArgState =
415           State->get<TrackedRegionMap>(IC->getArgSVal(0).getAsRegion());
416       if (ArgState && ArgState->isMoved() && !isInMoveSafeContext(LC)) {
417         const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
418         if(MethodDecl->isMoveAssignmentOperator())
419           N = reportBug(ArgRegion, Call, C, MK_Move);
420         else
421           N = reportBug(ArgRegion, Call, C, MK_Copy);
422         State =
423             State->set<TrackedRegionMap>(ArgRegion, RegionState::getReported());
424       }
425     }
426     C.addTransition(State, N);
427     return;
428   }
429
430   // The remaining part is check only for method call on a moved-from object.
431
432   // We want to investigate the whole object, not only sub-object of a parent
433   // class in which the encountered method defined.
434   while (const CXXBaseObjectRegion *BR =
435              dyn_cast<CXXBaseObjectRegion>(ThisRegion))
436     ThisRegion = BR->getSuperRegion();
437
438   if (isMoveSafeMethod(MethodDecl))
439     return;
440
441   if (isStateResetMethod(MethodDecl)) {
442     State = removeFromState(State, ThisRegion);
443     C.addTransition(State);
444     return;
445   }
446
447   // If it is already reported then we don't report the bug again.
448   const RegionState *ThisState = State->get<TrackedRegionMap>(ThisRegion);
449   if (!(ThisState && ThisState->isMoved()))
450     return;
451
452   // Don't report it in case if any base region is already reported
453   if (isAnyBaseRegionReported(State, ThisRegion))
454     return;
455
456   if (isInMoveSafeContext(LC))
457     return;
458
459   N = reportBug(ThisRegion, Call, C, MK_FunCall);
460   State = State->set<TrackedRegionMap>(ThisRegion, RegionState::getReported());
461   C.addTransition(State, N);
462 }
463
464 void MisusedMovedObjectChecker::checkDeadSymbols(SymbolReaper &SymReaper,
465                                                  CheckerContext &C) const {
466   ProgramStateRef State = C.getState();
467   TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
468   for (TrackedRegionMapTy::value_type E : TrackedRegions) {
469     const MemRegion *Region = E.first;
470     bool IsRegDead = !SymReaper.isLiveRegion(Region);
471
472     // Remove the dead regions from the region map.
473     if (IsRegDead) {
474       State = State->remove<TrackedRegionMap>(Region);
475     }
476   }
477   C.addTransition(State);
478 }
479
480 ProgramStateRef MisusedMovedObjectChecker::checkRegionChanges(
481     ProgramStateRef State, const InvalidatedSymbols *Invalidated,
482     ArrayRef<const MemRegion *> ExplicitRegions,
483     ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx,
484     const CallEvent *Call) const {
485   // In case of an InstanceCall don't remove the ThisRegion from the GDM since
486   // it is handled in checkPreCall and checkPostCall.
487   const MemRegion *ThisRegion = nullptr;
488   if (const auto *IC = dyn_cast_or_null<CXXInstanceCall>(Call)) {
489     ThisRegion = IC->getCXXThisVal().getAsRegion();
490   }
491
492   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
493                                              E = ExplicitRegions.end();
494        I != E; ++I) {
495     const auto *Region = *I;
496     if (ThisRegion != Region) {
497       State = removeFromState(State, Region);
498     }
499   }
500
501   return State;
502 }
503
504 void MisusedMovedObjectChecker::printState(raw_ostream &Out,
505                                            ProgramStateRef State,
506                                            const char *NL,
507                                            const char *Sep) const {
508
509   TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
510
511   if (!RS.isEmpty()) {
512     Out << Sep << "Moved-from objects :" << NL;
513     for (auto I: RS) {
514       I.first->dumpToStream(Out);
515       if (I.second.isMoved())
516         Out << ": moved";
517       else
518         Out << ": moved and reported";
519       Out << NL;
520     }
521   }
522 }
523 void ento::registerMisusedMovedObjectChecker(CheckerManager &mgr) {
524   mgr.registerChecker<MisusedMovedObjectChecker>();
525 }