Coverage Report

Created: 2020-02-15 09:57

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