clang 24.0.0git
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 "Iterator.h"
16#include "Move.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/ExprCXX.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringSet.h"
29
30using namespace clang;
31using namespace ento;
32using namespace iterator;
33
34namespace {
35struct RegionState {
36private:
37 enum Kind { Moved, Reported } K;
38 RegionState(Kind InK) : K(InK) {}
39
40public:
41 bool isReported() const { return K == Reported; }
42 bool isMoved() const { return K == Moved; }
43
44 static RegionState getReported() { return RegionState(Reported); }
45 static RegionState getMoved() { return RegionState(Moved); }
46
47 bool operator==(const RegionState &X) const { return K == X.K; }
48 void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
49};
50} // end of anonymous namespace
51
52namespace {
53class MoveChecker
54 : public Checker<check::PreCall, check::PostCall, check::DeadSymbols,
55 check::RegionChanges, eval::Call> {
56public:
57 void checkPreCall(const CallEvent &MC, CheckerContext &C) const;
58 void checkPostCall(const CallEvent &MC, CheckerContext &C) const;
59 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
60 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
62 checkRegionChanges(ProgramStateRef State,
63 const InvalidatedSymbols *Invalidated,
64 ArrayRef<const MemRegion *> RequestedRegions,
65 ArrayRef<const MemRegion *> InvalidatedRegions,
66 const StackFrame *SF, const CallEvent *Call) const;
67 void printState(raw_ostream &Out, ProgramStateRef State,
68 const char *NL, const char *Sep) const override;
69
70private:
71 enum MisuseKind { MK_FunCall, MK_Copy, MK_Move, MK_Dereference };
72 enum StdObjectKind { SK_NonStd, SK_Unsafe, SK_Safe, SK_SmartPtr };
73
74 enum AggressivenessKind { // In any case, don't warn after a reset.
75 AK_Invalid = -1,
76 AK_KnownsOnly = 0, // Warn only about known move-unsafe classes.
77 AK_KnownsAndLocals = 1, // Also warn about all local objects.
78 AK_All = 2, // Warn on any use-after-move.
79 AK_NumKinds = AK_All
80 };
81
82 static bool misuseCausesCrash(MisuseKind MK) {
83 return MK == MK_Dereference;
84 }
85
86 struct ObjectKind {
87 // Is this a local variable or a local rvalue reference?
88 bool IsLocal;
89 // Is this an STL object? If so, of what kind?
90 StdObjectKind StdKind;
91 };
92
93 // STL smart pointers are automatically re-initialized to null when moved
94 // from. So we can't warn on many methods, but we can warn when it is
95 // dereferenced, which is UB even if the resulting lvalue never gets read.
96 const llvm::StringSet<> StdSmartPtrClasses = {
97 "shared_ptr",
98 "unique_ptr",
99 "weak_ptr",
100 };
101
102 // Not all of these are entirely move-safe, but they do provide *some*
103 // guarantees, and it means that somebody is using them after move
104 // in a valid manner.
105 // TODO: We can still try to identify *unsafe* use after move,
106 // like we did with smart pointers.
107 const llvm::StringSet<> StdSafeClasses = {
108 "basic_filebuf",
109 "basic_ios",
110 "future",
111 "optional",
112 "packaged_task",
113 "promise",
114 "shared_future",
115 "shared_lock",
116 "thread",
117 "unique_lock",
118 };
119
120 // Should we bother tracking the state of the object?
121 bool shouldBeTracked(ObjectKind OK) const {
122 // In non-aggressive mode, only warn on use-after-move of local variables
123 // (or local rvalue references) and of STL objects. The former is possible
124 // because local variables (or local rvalue references) are not tempting
125 // their user to re-use the storage. The latter is possible because STL
126 // objects are known to end up in a valid but unspecified state after the
127 // move and their state-reset methods are also known, which allows us to
128 // predict precisely when use-after-move is invalid.
129 // Some STL objects are known to conform to additional contracts after move,
130 // so they are not tracked. However, smart pointers specifically are tracked
131 // because we can perform extra checking over them.
132 // In aggressive mode, warn on any use-after-move because the user has
133 // intentionally asked us to completely eliminate use-after-move
134 // in his code.
135 return (Aggressiveness == AK_All) ||
136 (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
137 OK.StdKind == SK_Unsafe || OK.StdKind == SK_SmartPtr;
138 }
139
140 // Some objects only suffer from some kinds of misuses, but we need to track
141 // them anyway because we cannot know in advance what misuse will we find.
142 bool shouldWarnAbout(ObjectKind OK, MisuseKind MK) const {
143 // Additionally, only warn on smart pointers when they are dereferenced (or
144 // local or we are aggressive).
145 return shouldBeTracked(OK) &&
146 ((Aggressiveness == AK_All) ||
147 (Aggressiveness >= AK_KnownsAndLocals && OK.IsLocal) ||
148 OK.StdKind != SK_SmartPtr || MK == MK_Dereference);
149 }
150
151 // Obtains ObjectKind of an object. Because class declaration cannot always
152 // be easily obtained from the memory region, it is supplied separately.
153 ObjectKind classifyObject(ProgramStateRef State, const MemRegion *MR,
154 const CXXRecordDecl *RD) const;
155
156 // Classifies the object and dumps a user-friendly description string to
157 // the stream.
158 void explainObject(ProgramStateRef State, llvm::raw_ostream &OS,
159 const MemRegion *MR, const CXXRecordDecl *RD,
160 MisuseKind MK) const;
161
162 bool belongsTo(const CXXRecordDecl *RD, const llvm::StringSet<> &Set) const;
163
164 class MovedBugVisitor : public BugReporterVisitor {
165 public:
166 MovedBugVisitor(const MoveChecker &Chk, const MemRegion *R,
167 const CXXRecordDecl *RD, MisuseKind MK)
168 : Chk(Chk), Region(R), RD(RD), MK(MK), Found(false) {}
169
170 void Profile(llvm::FoldingSetNodeID &ID) const override {
171 static int X = 0;
172 ID.AddPointer(&X);
173 ID.AddPointer(Region);
174 // Don't add RD because it's, in theory, uniquely determined by
175 // the region. In practice though, it's not always possible to obtain
176 // the declaration directly from the region, that's why we store it
177 // in the first place.
178 }
179
180 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
181 BugReporterContext &BRC,
182 PathSensitiveBugReport &BR) override;
183
184 private:
185 const MoveChecker &Chk;
186 // The tracked region.
187 const MemRegion *Region;
188 // The class of the tracked object.
189 const CXXRecordDecl *RD;
190 // How exactly the object was misused.
191 const MisuseKind MK;
192 bool Found;
193 };
194
195 AggressivenessKind Aggressiveness = AK_KnownsAndLocals;
196
197public:
198 void setAggressiveness(StringRef Str, CheckerManager &Mgr) {
199 Aggressiveness =
200 llvm::StringSwitch<AggressivenessKind>(Str)
201 .Case("KnownsOnly", AK_KnownsOnly)
202 .Case("KnownsAndLocals", AK_KnownsAndLocals)
203 .Case("All", AK_All)
204 .Default(AK_Invalid);
205
206 if (Aggressiveness == AK_Invalid)
207 Mgr.reportInvalidCheckerOptionValue(this, "WarnOn",
208 "either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value");
209 };
210
211private:
212 BugType BT{this, "Use-after-move", categories::CXXMoveSemantics};
213
214 // Modelling the 3 argument std::move calls
215 const CallDescription StdMoveCall{CDM::SimpleFunc, {"std", "move"}, 3};
216
217 // Check if the given form of potential misuse of a given object
218 // should be reported. If so, get it reported. The callback from which
219 // this function was called should immediately return after the call
220 // because this function adds one or two transitions.
221 void modelUse(ProgramStateRef State, const MemRegion *Region,
222 const CXXRecordDecl *RD, MisuseKind MK,
223 CheckerContext &C) const;
224
225 // Returns the exploded node against which the report was emitted.
226 // The caller *must* add any further transitions against this node.
227 // Returns nullptr and does not report if such node already exists.
228 ExplodedNode *tryToReportBug(const MemRegion *Region, const CXXRecordDecl *RD,
229 CheckerContext &C, MisuseKind MK) const;
230
231 bool isInMoveSafeStackFrame(const CheckerContext &C) const;
232 bool isStateResetMethod(const CXXMethodDecl *MethodDec) const;
233 bool isMoveSafeMethod(const CXXMethodDecl *MethodDec) const;
234 const ExplodedNode *getMoveLocation(const ExplodedNode *N,
235 const MemRegion *Region,
236 CheckerContext &C) const;
237};
238} // end anonymous namespace
239
240REGISTER_MAP_WITH_PROGRAMSTATE(TrackedRegionMap, const MemRegion *, RegionState)
241
242// Custom map designed to track containers whose contents were moved by 3-arg
243// std::move
244REGISTER_MAP_WITH_PROGRAMSTATE(TrackedContentsMap, const MemRegion *,
245 RegionState)
246
247// Define the inter-checker API.
248namespace clang {
249namespace ento {
250namespace move {
251bool isMovedFrom(ProgramStateRef State, const MemRegion *Region) {
252 const RegionState *RS = State->get<TrackedRegionMap>(Region);
253 return RS && (RS->isMoved() || RS->isReported());
254}
255} // namespace move
256} // namespace ento
257} // namespace clang
258
259// If a region is removed all of the subregions needs to be removed too.
261 const MemRegion *Region,
262 bool Strict = false) {
263 if (!Region)
264 return State;
265 for (auto &E : State->get<TrackedRegionMap>()) {
266 if ((!Strict || E.first != Region) && E.first->isSubRegionOf(Region))
267 State = State->remove<TrackedRegionMap>(E.first);
268 }
269 return State;
270}
271
273 const MemRegion *Region) {
274 auto IsReportedBase = [&](const auto &E) {
275 return Region->isSubRegionOf(E.first) && E.second.isReported();
276 };
277 return llvm::any_of(State->get<TrackedRegionMap>(), IsReportedBase);
278}
279
281 if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) {
282 SymbolRef Sym = SR->getSymbol();
283 if (Sym->getType()->isRValueReferenceType())
284 if (const MemRegion *OriginMR = Sym->getOriginRegion())
285 return OriginMR;
286 }
287 return MR;
288}
289
291MoveChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
294 // We need only the last move of the reported object's region.
295 // The visitor walks the ExplodedGraph backwards.
296 if (Found)
297 return nullptr;
298 ProgramStateRef State = N->getState();
299 ProgramStateRef StatePrev = N->getFirstPred()->getState();
300 const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
301 const RegionState *TrackedObjectPrev =
302 StatePrev->get<TrackedRegionMap>(Region);
303 if (!TrackedObject)
304 return nullptr;
305 if (TrackedObjectPrev && TrackedObject)
306 return nullptr;
307
308 // Retrieve the associated statement.
309 const Stmt *S = N->getStmtForDiagnostics();
310 if (!S)
311 return nullptr;
312 Found = true;
313
314 SmallString<128> Str;
315 llvm::raw_svector_ostream OS(Str);
316
317 ObjectKind OK = Chk.classifyObject(State, Region, RD);
318 switch (OK.StdKind) {
319 case SK_SmartPtr:
320 if (MK == MK_Dereference) {
321 OS << "Smart pointer";
322 Chk.explainObject(State, OS, Region, RD, MK);
323 OS << " is reset to null when moved from";
324 break;
325 }
326
327 // If it's not a dereference, we don't care if it was reset to null
328 // or that it is even a smart pointer.
329 [[fallthrough]];
330 case SK_NonStd:
331 case SK_Safe:
332 OS << "Object";
333 Chk.explainObject(State, OS, Region, RD, MK);
334 OS << " is moved";
335 break;
336 case SK_Unsafe:
337 OS << "Object";
338 Chk.explainObject(State, OS, Region, RD, MK);
339 OS << " is left in a valid but unspecified state after move";
340 break;
341 }
342
343 // Generate the extra diagnostic.
344 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), N->getStackFrame());
345 return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true);
346}
347
348const ExplodedNode *MoveChecker::getMoveLocation(const ExplodedNode *N,
349 const MemRegion *Region,
350 CheckerContext &C) const {
351 // Walk the ExplodedGraph backwards and find the first node that referred to
352 // the tracked region.
353 const ExplodedNode *MoveNode = N;
354
355 while (N) {
356 ProgramStateRef State = N->getState();
357 if (!State->get<TrackedRegionMap>(Region))
358 break;
359 MoveNode = N;
360 N = N->pred_empty() ? nullptr : *(N->pred_begin());
361 }
362 return MoveNode;
363}
364
365void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region,
366 const CXXRecordDecl *RD, MisuseKind MK,
367 CheckerContext &C) const {
368 assert(!C.isDifferent() && "No transitions should have been made by now");
369 const RegionState *RS = State->get<TrackedRegionMap>(Region);
370 ObjectKind OK = classifyObject(State, Region, RD);
371
372 // Just in case: if it's not a smart pointer but it does have operator *,
373 // we shouldn't call the bug a dereference.
374 if (MK == MK_Dereference && OK.StdKind != SK_SmartPtr)
375 MK = MK_FunCall;
376
377 if (!RS || !shouldWarnAbout(OK, MK) || isInMoveSafeStackFrame(C)) {
378 // Finalize changes made by the caller.
379 C.addTransition(State);
380 return;
381 }
382
383 // Don't report it in case if any base region is already reported.
384 // But still generate a sink in case of UB.
385 // And still finalize changes made by the caller.
386 if (isAnyBaseRegionReported(State, Region)) {
387 if (misuseCausesCrash(MK)) {
388 C.addSink(State);
389 } else {
390 C.addTransition(State);
391 }
392 return;
393 }
394
395 ExplodedNode *N = tryToReportBug(Region, RD, C, MK);
396
397 // If the program has already crashed on this path, don't bother.
398 if (!N || N->isSink())
399 return;
400
401 State = State->set<TrackedRegionMap>(Region, RegionState::getReported());
402 C.addTransition(State, N);
403}
404
405ExplodedNode *MoveChecker::tryToReportBug(const MemRegion *Region,
406 const CXXRecordDecl *RD,
407 CheckerContext &C,
408 MisuseKind MK) const {
409 if (ExplodedNode *N =
410 misuseCausesCrash(MK) ? C.addSink() : C.generateNonFatalErrorNode()) {
411 // Uniqueing report to the same object.
412 PathDiagnosticLocation LocUsedForUniqueing;
413 const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
414
415 if (const Stmt *MoveStmt = MoveNode->getStmtForDiagnostics())
416 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
417 MoveStmt, C.getSourceManager(), MoveNode->getStackFrame());
418
419 // Creating the error message.
420 llvm::SmallString<128> Str;
421 llvm::raw_svector_ostream OS(Str);
422 ProgramStateRef State = N->getState();
423 switch(MK) {
424 case MK_FunCall:
425 OS << "Method called on moved-from object";
426 explainObject(State, OS, Region, RD, MK);
427 break;
428 case MK_Copy:
429 OS << "Moved-from object";
430 explainObject(State, OS, Region, RD, MK);
431 OS << " is copied";
432 break;
433 case MK_Move:
434 OS << "Moved-from object";
435 explainObject(State, OS, Region, RD, MK);
436 OS << " is moved";
437 break;
438 case MK_Dereference:
439 OS << "Dereference of null smart pointer";
440 explainObject(State, OS, Region, RD, MK);
441 break;
442 }
443
444 auto R = std::make_unique<PathSensitiveBugReport>(
445 BT, OS.str(), N, LocUsedForUniqueing,
446 MoveNode->getStackFrame()->getDecl());
447 R->addVisitor(std::make_unique<MovedBugVisitor>(*this, Region, RD, MK));
448 C.emitReport(std::move(R));
449 return N;
450 }
451 return nullptr;
452}
453
454void MoveChecker::checkPostCall(const CallEvent &Call,
455 CheckerContext &C) const {
456 const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
457 if (!AFC)
458 return;
459
460 ProgramStateRef State = C.getState();
461 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
462 if (!MethodDecl)
463 return;
464
465 // Check if an object became moved-from.
466 // Object can become moved from after a call to move assignment operator or
467 // move constructor .
468 const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
469 if (ConstructorDecl && !ConstructorDecl->isMoveConstructor())
470 return;
471
472 if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator())
473 return;
474
475 const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
476 if (!ArgRegion)
477 return;
478
479 // Skip moving the object to itself.
480 const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
481 if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion)
482 return;
483
484 if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
485 if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
486 return;
487
488 const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
489 // Skip temp objects because of their short lifetime.
490 if (BaseRegion->getAs<CXXTempObjectRegion>() ||
491 AFC->getArgExpr(0)->isPRValue())
492 return;
493 // If it has already been reported do not need to modify the state.
494
495 if (State->get<TrackedRegionMap>(ArgRegion))
496 return;
497
498 const CXXRecordDecl *RD = MethodDecl->getParent();
499 ObjectKind OK = classifyObject(State, ArgRegion, RD);
500 if (shouldBeTracked(OK)) {
501 // Mark object as moved-from.
502 State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
503 C.addTransition(State);
504 return;
505 }
506 assert(!C.isDifferent() && "Should not have made transitions on this path!");
507}
508
509bool MoveChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
510
511 const auto *CE = dyn_cast_if_present<CallExpr>(Call.getOriginExpr());
512 if (!CE)
513 return false;
514
515 ProgramStateRef State = C.getState();
516
517 if (!StdMoveCall.matches(Call))
518 return false;
519
520 const auto *POS = getIteratorPosition(State, Call.getArgSVal(0));
521 if (!POS)
522 return false;
523
524 const MemRegion *ContainerRegion = POS->getContainer();
525 if (!ContainerRegion)
526 return false;
527
528 const auto *TypedRegion = dyn_cast<TypedValueRegion>(ContainerRegion);
529
530 if (!TypedRegion)
531 return false;
532
533 QualType ObjTy = TypedRegion->getValueType();
534
535 const auto *RD = ObjTy->getAsCXXRecordDecl();
536 if (!RD)
537 return false;
538
539 ObjectKind OK = classifyObject(State, ContainerRegion, RD);
540
541 // FIXME: IteratorModeling does not handle output iterators like
542 // std::back_inserter. For this reason, we fall back to AST pattern matching
543 // for destination recovery. Once IteratorModeling handles output iterators
544 // like std::back_inserter, this can be replaced with getIteratorPosition().
545 const auto *BackInsCall = dyn_cast<CallExpr>(CE->getArg(2)->IgnoreImpCasts());
546 if (!BackInsCall)
547 return false;
548
549 const Expr *DestExpr = BackInsCall->getArg(0)->IgnoreImpCasts();
550 if (!DestExpr)
551 return false;
552
553 const auto *DestDRE = dyn_cast<DeclRefExpr>(DestExpr);
554 if (!DestDRE)
555 return false;
556
557 const auto *DestVD = dyn_cast<VarDecl>(DestDRE->getDecl());
558 if (!DestVD)
559 return false;
560
561 const MemRegion *DestRegion =
562 State->getLValue(DestVD, C.getStackFrame()).getAsRegion();
563 if (!DestRegion)
564 return false;
565
566 SValBuilder &SVB = State->getStateManager().getSValBuilder();
567 SVal ReturnVal = SVB.conjureSymbolVal(Call, C.blockCount());
568 State = State->BindExpr(CE, C.getStackFrame(), ReturnVal);
569
570 State = State->invalidateRegions({DestRegion}, Call.getCFGElementRef(),
571 C.blockCount(), C.getStackFrame(),
572 /*CausesPointerEscape=*/false);
573
574 if (shouldBeTracked(OK))
575 State = State->set<TrackedContentsMap>(ContainerRegion,
576 RegionState::getMoved());
577
578 C.addTransition(State);
579 return true;
580}
581
582bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const {
583 // We abandon the cases where bool/void/void* conversion happens.
584 if (const auto *ConversionDec =
585 dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
586 const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
587 if (!Tp)
588 return false;
589 if (Tp->isBooleanType() || Tp->isVoidType() || Tp->isVoidPointerType())
590 return true;
591 }
592 // Function call `empty` can be skipped.
593 return (MethodDec && MethodDec->getDeclName().isIdentifier() &&
594 (MethodDec->getName().lower() == "empty" ||
595 MethodDec->getName().lower() == "isempty"));
596}
597
598bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const {
599 if (!MethodDec)
600 return false;
601 if (MethodDec->hasAttr<ReinitializesAttr>())
602 return true;
603 if (MethodDec->getDeclName().isIdentifier()) {
604 std::string MethodName = MethodDec->getName().lower();
605 // TODO: Some of these methods (eg., resize) are not always resetting
606 // the state, so we should consider looking at the arguments.
607 if (MethodName == "assign" || MethodName == "clear" ||
608 MethodName == "destroy" || MethodName == "reset" ||
609 MethodName == "resize" || MethodName == "shrink")
610 return true;
611 }
612 return false;
613}
614
615// Don't report an error inside a move related operation.
616// We assume that the programmer knows what she does.
617bool MoveChecker::isInMoveSafeStackFrame(const CheckerContext &C) const {
618 return llvm::any_of(C.stackframes(), [this](const StackFrame &Frame) {
619 const auto *SFDec = Frame.getDecl();
620 auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(SFDec);
621 auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(SFDec);
622 auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(SFDec);
623 return DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()) ||
624 (MethodDec && MethodDec->isOverloadedOperator() &&
625 MethodDec->getOverloadedOperator() == OO_Equal) ||
626 isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec);
627 });
628}
629
630bool MoveChecker::belongsTo(const CXXRecordDecl *RD,
631 const llvm::StringSet<> &Set) const {
632 const IdentifierInfo *II = RD->getIdentifier();
633 return II && Set.count(II->getName());
634}
635
636MoveChecker::ObjectKind
637MoveChecker::classifyObject(ProgramStateRef State, const MemRegion *MR,
638 const CXXRecordDecl *RD) const {
639 // Local variables and local rvalue references are classified as "Local".
640 // For the purposes of this checker, we classify move-safe STL types
641 // as not-"STL" types, because that's how the checker treats them.
643 bool IsLocal =
644 isa_and_nonnull<VarRegion, CXXLifetimeExtendedObjectRegion>(MR) &&
645 MR->hasMemorySpace<StackSpaceRegion>(State);
646
647 if (!RD || !RD->getDeclContext()->isStdNamespace())
648 return { IsLocal, SK_NonStd };
649
650 if (belongsTo(RD, StdSmartPtrClasses))
651 return { IsLocal, SK_SmartPtr };
652
653 if (belongsTo(RD, StdSafeClasses))
654 return { IsLocal, SK_Safe };
655
656 return { IsLocal, SK_Unsafe };
657}
658
659void MoveChecker::explainObject(ProgramStateRef State, llvm::raw_ostream &OS,
660 const MemRegion *MR, const CXXRecordDecl *RD,
661 MisuseKind MK) const {
662 // We may need a leading space every time we actually explain anything,
663 // and we never know if we are to explain anything until we try.
664 if (const auto DR =
665 dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) {
666 const auto *RegionDecl = cast<NamedDecl>(DR->getDecl());
667 OS << " '" << RegionDecl->getDeclName() << "'";
668 }
669
670 ObjectKind OK = classifyObject(State, MR, RD);
671 switch (OK.StdKind) {
672 case SK_NonStd:
673 case SK_Safe:
674 break;
675 case SK_SmartPtr:
676 if (MK != MK_Dereference)
677 break;
678
679 // We only care about the type if it's a dereference.
680 [[fallthrough]];
681 case SK_Unsafe:
682 OS << " of type '" << RD->getQualifiedNameAsString() << "'";
683 break;
684 };
685}
686
687void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const {
688 ProgramStateRef State = C.getState();
689
690 // Remove the MemRegions from the map on which a ctor/dtor call or assignment
691 // happened.
692
693 // Checking constructor calls.
694 if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
695 State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
696 auto CtorDec = CC->getDecl();
697 // Check for copying a moved-from object and report the bug.
698 if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
699 const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
700 const CXXRecordDecl *RD = CtorDec->getParent();
701 MisuseKind MK = CtorDec->isMoveConstructor() ? MK_Move : MK_Copy;
702 modelUse(State, ArgRegion, RD, MK, C);
703 return;
704 }
705 }
706
707 const auto IC = dyn_cast<CXXInstanceCall>(&Call);
708 if (!IC)
709 return;
710
711 const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
712 if (!ThisRegion)
713 return;
714
715 // The remaining part is check only for method call on a moved-from object.
716 const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
717 if (!MethodDecl)
718 return;
719
720 // Calling a destructor on a moved object is fine.
721 if (isa<CXXDestructorDecl>(MethodDecl))
722 return;
723
724 // We want to investigate the whole object, not only sub-object of a parent
725 // class in which the encountered method defined.
726 ThisRegion = ThisRegion->getMostDerivedObjectRegion();
727
728 // Store class declaration as well, for bug reporting purposes.
729 const CXXRecordDecl *RD = MethodDecl->getParent();
730
731 if (MethodDecl->getOverloadedOperator() == OO_Star ||
732 MethodDecl->getOverloadedOperator() == OO_Arrow) {
733 SVal Val = IC->getCXXThisVal();
734
735 if (const auto *POS = getIteratorPosition(State, Val)) {
736 const MemRegion *ContainerRegion = POS->getContainer();
737 if (!ContainerRegion)
738 return;
739
740 const auto *TypedRegion = dyn_cast<TypedValueRegion>(ContainerRegion);
741 if (!TypedRegion)
742 return;
743
744 QualType ObjTy = TypedRegion->getValueType();
745 const auto *R = ObjTy->getAsCXXRecordDecl();
746 if (!R)
747 return;
748
749 if (State->get<TrackedContentsMap>(ContainerRegion)) {
750 ExplodedNode *N = tryToReportBug(ContainerRegion, R, C, MK_FunCall);
751 if (!N || N->isSink())
752 return;
753
754 State = State->set<TrackedContentsMap>(ContainerRegion,
755 RegionState::getReported());
756 C.addTransition(State, N);
757 return;
758 }
759 }
760 }
761
762 if (isStateResetMethod(MethodDecl)) {
763 State = removeFromState(State, ThisRegion);
764 C.addTransition(State);
765 return;
766 }
767
768 if (isMoveSafeMethod(MethodDecl))
769 return;
770
771 if (MethodDecl->isOverloadedOperator()) {
772 OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator();
773
774 if (OOK == OO_Equal) {
775 // Remove the tracked object for every assignment operator, but report bug
776 // only for move or copy assignment's argument.
777 State = removeFromState(State, ThisRegion);
778
779 if (MethodDecl->isCopyAssignmentOperator() ||
780 MethodDecl->isMoveAssignmentOperator()) {
781 const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
782 MisuseKind MK =
783 MethodDecl->isMoveAssignmentOperator() ? MK_Move : MK_Copy;
784 modelUse(State, ArgRegion, RD, MK, C);
785 return;
786 }
787 C.addTransition(State);
788 return;
789 }
790
791 if (OOK == OO_Star || OOK == OO_Arrow) {
792 modelUse(State, ThisRegion, RD, MK_Dereference, C);
793 return;
794 }
795 }
796
797 modelUse(State, ThisRegion, RD, MK_FunCall, C);
798}
799
800void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper,
801 CheckerContext &C) const {
802 ProgramStateRef State = C.getState();
803 TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
804 for (auto E : TrackedRegions) {
805 const MemRegion *Region = E.first;
806 bool IsRegDead = !SymReaper.isLiveRegion(Region);
807
808 // Remove the dead regions from the region map.
809 if (IsRegDead) {
810 State = State->remove<TrackedRegionMap>(Region);
811 }
812 }
813 C.addTransition(State);
814}
815
816ProgramStateRef MoveChecker::checkRegionChanges(
817 ProgramStateRef State, const InvalidatedSymbols *Invalidated,
818 ArrayRef<const MemRegion *> RequestedRegions,
819 ArrayRef<const MemRegion *> InvalidatedRegions, const StackFrame *SF,
820 const CallEvent *Call) const {
821 if (Call) {
822 // Relax invalidation upon function calls: only invalidate parameters
823 // that are passed directly via non-const pointers or non-const references
824 // or rvalue references.
825 // In case of an InstanceCall don't invalidate the this-region since
826 // it is fully handled in checkPreCall and checkPostCall, but do invalidate
827 // its strict subregions, as they are not handled.
828
829 // Requested ("explicit") regions are the regions passed into the call
830 // directly, but not all of them end up being invalidated.
831 // But when they do, they appear in the InvalidatedRegions array as well.
832 for (const auto *Region : RequestedRegions) {
833 if (llvm::is_contained(InvalidatedRegions, Region))
834 State = removeFromState(State, Region,
835 /*Strict=*/isa<CXXInstanceCall>(Call));
836 }
837 } else {
838 // For invalidations that aren't caused by calls, assume nothing. In
839 // particular, direct write into an object's field invalidates the status.
840 for (const auto *Region : InvalidatedRegions)
841 State = removeFromState(State, Region->getBaseRegion());
842 }
843
844 return State;
845}
846
847void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State,
848 const char *NL, const char *Sep) const {
849
850 TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
851
852 if (!RS.isEmpty()) {
853 Out << Sep << "Moved-from objects :" << NL;
854 for (auto I: RS) {
855 I.first->dumpToStream(Out);
856 if (I.second.isMoved())
857 Out << ": moved";
858 else
859 Out << ": moved and reported";
860 Out << NL;
861 }
862 }
863}
864void ento::registerMoveChecker(CheckerManager &mgr) {
865 MoveChecker *chk = mgr.registerChecker<MoveChecker>();
866 chk->setAggressiveness(
867 mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr);
868}
869
870bool ento::shouldRegisterMoveChecker(const CheckerManager &mgr) {
871 return true;
872}
Defines the clang::Expr interface and subclasses for C++ expressions.
#define X(type, name)
Definition Value.h:97
static bool isAnyBaseRegionReported(ProgramStateRef State, const MemRegion *Region)
static ProgramStateRef removeFromState(ProgramStateRef State, const MemRegion *Region, bool Strict=false)
static const MemRegion * unwrapRValueReferenceIndirection(const MemRegion *MR)
Defines an enumeration for C++ overloaded operators.
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
StringRef getCheckerStringOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Query an option's string value.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2113
bool isStdNamespace() const
DeclContext * getDeclContext()
Definition DeclBase.h:458
bool hasAttr() const
Definition DeclBase.h:587
bool isIdentifier() const
Predicate functions for querying what type of name this is.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1685
const Decl * getDecl() const
bool isVoidType() const
Definition TypeBase.h:9306
bool isBooleanType() const
Definition TypeBase.h:9447
bool isRValueReferenceType() const
Definition TypeBase.h:8949
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:845
const SourceManager & getSourceManager() const
bool matches(const CallEvent &Call) const
Returns true if the CallEvent is a call to a function that matches the CallDescription.
const AnalyzerOptions & getAnalyzerOptions() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
void reportInvalidCheckerOptionValue(const CheckerFrontend *Checker, StringRef OptionName, StringRef ExpectedValueDesc) const
Emits an error through a DiagnosticsEngine about an invalid user supplied checker option value.
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
bool hasMemorySpace(ProgramStateRef State) const
Definition MemRegion.h:148
virtual bool isSubRegionOf(const MemRegion *R) const
Check if the region is a subregion of the given region.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
const RegionTy * getAs() const
Definition MemRegion.h:1427
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getMostDerivedObjectRegion() const
Recursively retrieve the region of the most derived class instance of regions of C++ base class insta...
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const StackFrame *SF, unsigned count)
Create a new symbol with a unique 'name'.
virtual const MemRegion * getOriginRegion() const
Find the region from which this symbol originates.
Definition SymExpr.h:157
virtual QualType getType() const =0
bool isLiveRegion(const MemRegion *region)
const char *const CXXMoveSemantics
const IteratorPosition * getIteratorPosition(ProgramStateRef State, SVal Val)
Definition Iterator.cpp:184
bool isMovedFrom(ProgramStateRef State, const MemRegion *Region)
Returns true if the object is known to have been recently std::moved.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:166
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
Definition Address.h:327
#define false
Definition stdbool.h:26