Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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/ExprCXX.h"
16
#include "clang/Driver/DriverDiagnostic.h"
17
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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
#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
2.09k
  RegionState(Kind InK) : K(InK) {}
33
34
public:
35
319
  bool isReported() const { return K == Reported; }
36
23
  bool isMoved() const { return K == Moved; }
37
38
235
  static RegionState getReported() { return RegionState(Reported); }
39
1.86k
  static RegionState getMoved() { return RegionState(Moved); }
40
41
1.01k
  bool operator==(const RegionState &X) const { return K == X.K; }
42
2.75k
  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;
55
  ProgramStateRef
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
315
  static bool misuseCausesCrash(MisuseKind MK) {
77
315
    return MK == MK_Dereference;
78
315
  }
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
3.25k
  bool shouldBeTracked(ObjectKind OK) const {
116
3.25k
    // In non-aggressive mode, only warn on use-after-move of local variables
117
3.25k
    // (or local rvalue references) and of STL objects. The former is possible
118
3.25k
    // because local variables (or local rvalue references) are not tempting
119
3.25k
    // their user to re-use the storage. The latter is possible because STL
120
3.25k
    // objects are known to end up in a valid but unspecified state after the
121
3.25k
    // move and their state-reset methods are also known, which allows us to
122
3.25k
    // predict precisely when use-after-move is invalid.
123
3.25k
    // Some STL objects are known to conform to additional contracts after move,
124
3.25k
    // so they are not tracked. However, smart pointers specifically are tracked
125
3.25k
    // because we can perform extra checking over them.
126
3.25k
    // In aggressive mode, warn on any use-after-move because the user has
127
3.25k
    // intentionally asked us to completely eliminate use-after-move
128
3.25k
    // in his code.
129
3.25k
    return (Aggressiveness == AK_All) ||
130
3.25k
           
(1.61k
Aggressiveness >= AK_KnownsAndLocals1.61k
&&
OK.IsLocal920
) ||
131
3.25k
           
OK.StdKind == SK_Unsafe1.09k
||
OK.StdKind == SK_SmartPtr1.05k
;
132
3.25k
  }
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
363
  bool shouldWarnAbout(ObjectKind OK, MisuseKind MK) const {
137
363
    // Additionally, only warn on smart pointers when they are dereferenced (or
138
363
    // local or we are aggressive).
139
363
    return shouldBeTracked(OK) &&
140
363
           ((Aggressiveness == AK_All) ||
141
363
            
(111
Aggressiveness >= AK_KnownsAndLocals111
&&
OK.IsLocal99
) ||
142
363
            
OK.StdKind != SK_SmartPtr28
||
MK == MK_Dereference14
);
143
363
  }
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
247
        : Chk(Chk), Region(R), RD(RD), MK(MK), Found(false) {}
161
162
247
    void Profile(llvm::FoldingSetNodeID &ID) const override {
163
247
      static int X = 0;
164
247
      ID.AddPointer(&X);
165
247
      ID.AddPointer(Region);
166
247
      // Don't add RD because it's, in theory, uniquely determined by
167
247
      // the region. In practice though, it's not always possible to obtain
168
247
      // the declaration directly from the region, that's why we store it
169
247
      // in the first place.
170
247
    }
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
49
  void setAggressiveness(StringRef Str, CheckerManager &Mgr) {
191
49
    Aggressiveness =
192
49
        llvm::StringSwitch<AggressivenessKind>(Str)
193
49
            .Case("KnownsOnly", AK_KnownsOnly)
194
49
            .Case("KnownsAndLocals", AK_KnownsAndLocals)
195
49
            .Case("All", AK_All)
196
49
            .Default(AK_Invalid);
197
49
198
49
    if (Aggressiveness == AK_Invalid)
199
1
      Mgr.reportInvalidCheckerOptionValue(this, "WarnOn",
200
1
          "either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value");
201
49
  };
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 {
234
68
bool isMovedFrom(ProgramStateRef State, const MemRegion *Region) {
235
68
  const RegionState *RS = State->get<TrackedRegionMap>(Region);
236
68
  return RS && 
(15
RS->isMoved()15
||
RS->isReported()0
);
237
68
}
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.
243
static ProgramStateRef removeFromState(ProgramStateRef State,
244
44.0k
                                       const MemRegion *Region) {
245
44.0k
  if (!Region)
246
0
    return State;
247
44.0k
  for (auto &E : State->get<TrackedRegionMap>()) {
248
1.58k
    if (E.first->isSubRegionOf(Region))
249
596
      State = State->remove<TrackedRegionMap>(E.first);
250
1.58k
  }
251
44.0k
  return State;
252
44.0k
}
253
254
static bool isAnyBaseRegionReported(ProgramStateRef State,
255
315
                                    const MemRegion *Region) {
256
395
  for (auto &E : State->get<TrackedRegionMap>()) {
257
395
    if (Region->isSubRegionOf(E.first) && 
E.second.isReported()319
)
258
68
      return true;
259
395
  }
260
315
  
return false247
;
261
315
}
262
263
15.8k
static const MemRegion *unwrapRValueReferenceIndirection(const MemRegion *MR) {
264
15.8k
  if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) {
265
846
    SymbolRef Sym = SR->getSymbol();
266
846
    if (Sym->getType()->isRValueReferenceType())
267
59
      if (const MemRegion *OriginMR = Sym->getOriginRegion())
268
56
        return OriginMR;
269
15.7k
  }
270
15.7k
  return MR;
271
15.7k
}
272
273
std::shared_ptr<PathDiagnosticPiece>
274
MoveChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
275
136k
                                        BugReporterContext &BRC, BugReport &BR) {
276
136k
  // We need only the last move of the reported object's region.
277
136k
  // The visitor walks the ExplodedGraph backwards.
278
136k
  if (Found)
279
133k
    return nullptr;
280
3.09k
  ProgramStateRef State = N->getState();
281
3.09k
  ProgramStateRef StatePrev = N->getFirstPred()->getState();
282
3.09k
  const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
283
3.09k
  const RegionState *TrackedObjectPrev =
284
3.09k
      StatePrev->get<TrackedRegionMap>(Region);
285
3.09k
  if (!TrackedObject)
286
0
    return nullptr;
287
3.09k
  if (TrackedObjectPrev && 
TrackedObject2.86k
)
288
2.86k
    return nullptr;
289
223
290
223
  // Retrieve the associated statement.
291
223
  const Stmt *S = PathDiagnosticLocation::getStmt(N);
292
223
  if (!S)
293
0
    return nullptr;
294
223
  Found = true;
295
223
296
223
  SmallString<128> Str;
297
223
  llvm::raw_svector_ostream OS(Str);
298
223
299
223
  ObjectKind OK = Chk.classifyObject(Region, RD);
300
223
  switch (OK.StdKind) {
301
223
    case SK_SmartPtr:
302
29
      if (MK == MK_Dereference) {
303
12
        OS << "Smart pointer";
304
12
        Chk.explainObject(OS, Region, RD, MK);
305
12
        OS << " is reset to null when moved from";
306
12
        break;
307
12
      }
308
17
309
17
      // If it's not a dereference, we don't care if it was reset to null
310
17
      // or that it is even a smart pointer.
311
17
      LLVM_FALLTHROUGH;
312
195
    case SK_NonStd:
313
195
    case SK_Safe:
314
195
      OS << "Object";
315
195
      Chk.explainObject(OS, Region, RD, MK);
316
195
      OS << " is moved";
317
195
      break;
318
195
    case SK_Unsafe:
319
16
      OS << "Object";
320
16
      Chk.explainObject(OS, Region, RD, MK);
321
16
      OS << " is left in a valid but unspecified state after move";
322
16
      break;
323
223
  }
324
223
325
223
  // Generate the extra diagnostic.
326
223
  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
327
223
                             N->getLocationContext());
328
223
  return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true);
329
223
}
330
331
const ExplodedNode *MoveChecker::getMoveLocation(const ExplodedNode *N,
332
                                                 const MemRegion *Region,
333
247
                                                 CheckerContext &C) const {
334
247
  // Walk the ExplodedGraph backwards and find the first node that referred to
335
247
  // the tracked region.
336
247
  const ExplodedNode *MoveNode = N;
337
247
338
3.91k
  while (N) {
339
3.91k
    ProgramStateRef State = N->getState();
340
3.91k
    if (!State->get<TrackedRegionMap>(Region))
341
247
      break;
342
3.66k
    MoveNode = N;
343
3.66k
    N = N->pred_empty() ? 
nullptr0
: *(N->pred_begin());
344
3.66k
  }
345
247
  return MoveNode;
346
247
}
347
348
void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region,
349
                           const CXXRecordDecl *RD, MisuseKind MK,
350
11.7k
                           CheckerContext &C) const {
351
11.7k
  assert(!C.isDifferent() && "No transitions should have been made by now");
352
11.7k
  const RegionState *RS = State->get<TrackedRegionMap>(Region);
353
11.7k
  ObjectKind OK = classifyObject(Region, RD);
354
11.7k
355
11.7k
  // Just in case: if it's not a smart pointer but it does have operator *,
356
11.7k
  // we shouldn't call the bug a dereference.
357
11.7k
  if (MK == MK_Dereference && 
OK.StdKind != SK_SmartPtr254
)
358
238
    MK = MK_FunCall;
359
11.7k
360
11.7k
  if (!RS || 
!shouldWarnAbout(OK, MK)363
361
11.7k
          || 
isInMoveSafeContext(C.getLocationContext())355
) {
362
11.4k
    // Finalize changes made by the caller.
363
11.4k
    C.addTransition(State);
364
11.4k
    return;
365
11.4k
  }
366
315
367
315
  // Don't report it in case if any base region is already reported.
368
315
  // But still generate a sink in case of UB.
369
315
  // And still finalize changes made by the caller.
370
315
  if (isAnyBaseRegionReported(State, Region)) {
371
68
    if (misuseCausesCrash(MK)) {
372
4
      C.generateSink(State, C.getPredecessor());
373
64
    } else {
374
64
      C.addTransition(State);
375
64
    }
376
68
    return;
377
68
  }
378
247
379
247
  ExplodedNode *N = reportBug(Region, RD, C, MK);
380
247
381
247
  // If the program has already crashed on this path, don't bother.
382
247
  if (N->isSink())
383
12
    return;
384
235
385
235
  State = State->set<TrackedRegionMap>(Region, RegionState::getReported());
386
235
  C.addTransition(State, N);
387
235
}
388
389
ExplodedNode *MoveChecker::reportBug(const MemRegion *Region,
390
                                     const CXXRecordDecl *RD, CheckerContext &C,
391
247
                                     MisuseKind MK) const {
392
247
  if (ExplodedNode *N = misuseCausesCrash(MK) ? C.generateErrorNode()
393
247
                                              : C.generateNonFatalErrorNode()) {
394
247
395
247
    if (!BT)
396
11
      BT.reset(new BugType(this, "Use-after-move",
397
11
                           "C++ move semantics"));
398
247
399
247
    // Uniqueing report to the same object.
400
247
    PathDiagnosticLocation LocUsedForUniqueing;
401
247
    const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
402
247
403
247
    if (const Stmt *MoveStmt = PathDiagnosticLocation::getStmt(MoveNode))
404
247
      LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
405
247
          MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
406
247
407
247
    // Creating the error message.
408
247
    llvm::SmallString<128> Str;
409
247
    llvm::raw_svector_ostream OS(Str);
410
247
    switch(MK) {
411
247
      case MK_FunCall:
412
199
        OS << "Method called on moved-from object";
413
199
        explainObject(OS, Region, RD, MK);
414
199
        break;
415
247
      case MK_Copy:
416
18
        OS << "Moved-from object";
417
18
        explainObject(OS, Region, RD, MK);
418
18
        OS << " is copied";
419
18
        break;
420
247
      case MK_Move:
421
18
        OS << "Moved-from object";
422
18
        explainObject(OS, Region, RD, MK);
423
18
        OS << " is moved";
424
18
        break;
425
247
      case MK_Dereference:
426
12
        OS << "Dereference of null smart pointer";
427
12
        explainObject(OS, Region, RD, MK);
428
12
        break;
429
247
    }
430
247
431
247
    auto R =
432
247
        llvm::make_unique<BugReport>(*BT, OS.str(), N, LocUsedForUniqueing,
433
247
                                     MoveNode->getLocationContext()->getDecl());
434
247
    R->addVisitor(llvm::make_unique<MovedBugVisitor>(*this, Region, RD, MK));
435
247
    C.emitReport(std::move(R));
436
247
    return N;
437
247
  }
438
0
  return nullptr;
439
0
}
440
441
void MoveChecker::checkPostCall(const CallEvent &Call,
442
33.7k
                                CheckerContext &C) const {
443
33.7k
  const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
444
33.7k
  if (!AFC)
445
1
    return;
446
33.7k
447
33.7k
  ProgramStateRef State = C.getState();
448
33.7k
  const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
449
33.7k
  if (!MethodDecl)
450
17.6k
    return;
451
16.1k
452
16.1k
  // Check if an object became moved-from.
453
16.1k
  // Object can become moved from after a call to move assignment operator or
454
16.1k
  // move constructor .
455
16.1k
  const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
456
16.1k
  if (ConstructorDecl && 
!ConstructorDecl->isMoveConstructor()11.1k
)
457
9.19k
    return;
458
6.91k
459
6.91k
  if (!ConstructorDecl && 
!MethodDecl->isMoveAssignmentOperator()4.98k
)
460
3.64k
    return;
461
3.26k
462
3.26k
  const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
463
3.26k
  if (!ArgRegion)
464
0
    return;
465
3.26k
466
3.26k
  // Skip moving the object to itself.
467
3.26k
  const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
468
3.26k
  if (CC && 
CC->getCXXThisVal().getAsRegion() == ArgRegion1.93k
)
469
0
    return;
470
3.26k
471
3.26k
  if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
472
1.33k
    if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
473
0
      return;
474
3.26k
475
3.26k
  const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
476
3.26k
  // Skip temp objects because of their short lifetime.
477
3.26k
  if (BaseRegion->getAs<CXXTempObjectRegion>() ||
478
3.26k
      
AFC->getArgExpr(0)->isRValue()2.95k
)
479
310
    return;
480
2.95k
  // If it has already been reported do not need to modify the state.
481
2.95k
482
2.95k
  if (State->get<TrackedRegionMap>(ArgRegion))
483
60
    return;
484
2.89k
485
2.89k
  const CXXRecordDecl *RD = MethodDecl->getParent();
486
2.89k
  ObjectKind OK = classifyObject(ArgRegion, RD);
487
2.89k
  if (shouldBeTracked(OK)) {
488
1.86k
    // Mark object as moved-from.
489
1.86k
    State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
490
1.86k
    C.addTransition(State);
491
1.86k
    return;
492
1.86k
  }
493
1.03k
  assert(!C.isDifferent() && "Should not have made transitions on this path!");
494
1.03k
}
495
496
4.84k
bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const {
497
4.84k
  // We abandon the cases where bool/void/void* conversion happens.
498
4.84k
  if (const auto *ConversionDec =
499
90
          dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
500
90
    const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
501
90
    if (!Tp)
502
0
      return false;
503
90
    if (Tp->isBooleanType() || 
Tp->isVoidType()22
||
Tp->isVoidPointerType()22
)
504
68
      return true;
505
4.78k
  }
506
4.78k
  // Function call `empty` can be skipped.
507
4.78k
  return (MethodDec && 
MethodDec->getDeclName().isIdentifier()4.48k
&&
508
4.78k
      
(2.53k
MethodDec->getName().lower() == "empty"2.53k
||
509
2.53k
       
MethodDec->getName().lower() == "isempty"2.52k
));
510
4.78k
}
511
512
4.92k
bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const {
513
4.92k
  if (!MethodDec)
514
297
      return false;
515
4.62k
  if (MethodDec->hasAttr<ReinitializesAttr>())
516
8
      return true;
517
4.61k
  if (MethodDec->getDeclName().isIdentifier()) {
518
2.59k
    std::string MethodName = MethodDec->getName().lower();
519
2.59k
    // TODO: Some of these methods (eg., resize) are not always resetting
520
2.59k
    // the state, so we should consider looking at the arguments.
521
2.59k
    if (MethodName == "assign" || 
MethodName == "clear"2.57k
||
522
2.59k
        
MethodName == "destroy"2.55k
||
MethodName == "reset"2.54k
||
523
2.59k
        
MethodName == "resize"2.53k
||
MethodName == "shrink"2.53k
)
524
64
      return true;
525
4.55k
  }
526
4.55k
  return false;
527
4.55k
}
528
529
// Don't report an error inside a move related operation.
530
// We assume that the programmer knows what she does.
531
355
bool MoveChecker::isInMoveSafeContext(const LocationContext *LC) const {
532
369
  do {
533
369
    const auto *CtxDec = LC->getDecl();
534
369
    auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
535
369
    auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
536
369
    auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
537
369
    if (DtorDec || (CtorDec && 
CtorDec->isCopyOrMoveConstructor()32
) ||
538
369
        
(337
MethodDec337
&&
MethodDec->isOverloadedOperator()40
&&
539
337
         
MethodDec->getOverloadedOperator() == OO_Equal8
) ||
540
369
        
isStateResetMethod(MethodDec)329
||
isMoveSafeMethod(MethodDec)329
)
541
40
      return true;
542
329
  } while ((LC = LC->getParent()));
543
355
  
return false315
;
544
355
}
545
546
bool MoveChecker::belongsTo(const CXXRecordDecl *RD,
547
1.64k
                            const llvm::StringSet<> &Set) const {
548
1.64k
  const IdentifierInfo *II = RD->getIdentifier();
549
1.64k
  return II && Set.count(II->getName());
550
1.64k
}
551
552
MoveChecker::ObjectKind
553
MoveChecker::classifyObject(const MemRegion *MR,
554
15.3k
                            const CXXRecordDecl *RD) const {
555
15.3k
  // Local variables and local rvalue references are classified as "Local".
556
15.3k
  // For the purposes of this checker, we classify move-safe STL types
557
15.3k
  // as not-"STL" types, because that's how the checker treats them.
558
15.3k
  MR = unwrapRValueReferenceIndirection(MR);
559
15.3k
  bool IsLocal =
560
15.3k
      MR && isa<VarRegion>(MR) && 
isa<StackSpaceRegion>(MR->getMemorySpace())6.06k
;
561
15.3k
562
15.3k
  if (!RD || !RD->getDeclContext()->isStdNamespace())
563
14.4k
    return { IsLocal, SK_NonStd };
564
919
565
919
  if (belongsTo(RD, StdSmartPtrClasses))
566
195
    return { IsLocal, SK_SmartPtr };
567
724
568
724
  if (belongsTo(RD, StdSafeClasses))
569
0
    return { IsLocal, SK_Safe };
570
724
571
724
  return { IsLocal, SK_Unsafe };
572
724
}
573
574
void MoveChecker::explainObject(llvm::raw_ostream &OS, const MemRegion *MR,
575
470
                                const CXXRecordDecl *RD, MisuseKind MK) const {
576
470
  // We may need a leading space every time we actually explain anything,
577
470
  // and we never know if we are to explain anything until we try.
578
470
  if (const auto DR =
579
430
          dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) {
580
430
    const auto *RegionDecl = cast<NamedDecl>(DR->getDecl());
581
430
    OS << " '" << RegionDecl->getNameAsString() << "'";
582
430
  }
583
470
584
470
  ObjectKind OK = classifyObject(MR, RD);
585
470
  switch (OK.StdKind) {
586
470
    case SK_NonStd:
587
380
    case SK_Safe:
588
380
      break;
589
380
    case SK_SmartPtr:
590
58
      if (MK != MK_Dereference)
591
34
        break;
592
24
593
24
      // We only care about the type if it's a dereference.
594
24
      LLVM_FALLTHROUGH;
595
56
    case SK_Unsafe:
596
56
      OS << " of type '" << RD->getQualifiedNameAsString() << "'";
597
56
      break;
598
470
  };
599
470
}
600
601
32.4k
void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const {
602
32.4k
  ProgramStateRef State = C.getState();
603
32.4k
604
32.4k
  // Remove the MemRegions from the map on which a ctor/dtor call or assignment
605
32.4k
  // happened.
606
32.4k
607
32.4k
  // Checking constructor calls.
608
32.4k
  if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
609
11.1k
    State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
610
11.1k
    auto CtorDec = CC->getDecl();
611
11.1k
    // Check for copying a moved-from object and report the bug.
612
11.1k
    if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
613
7.36k
      const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
614
7.36k
      const CXXRecordDecl *RD = CtorDec->getParent();
615
7.36k
      MisuseKind MK = CtorDec->isMoveConstructor() ? 
MK_Move1.94k
:
MK_Copy5.42k
;
616
7.36k
      modelUse(State, ArgRegion, RD, MK, C);
617
7.36k
      return;
618
7.36k
    }
619
25.0k
  }
620
25.0k
621
25.0k
  const auto IC = dyn_cast<CXXInstanceCall>(&Call);
622
25.0k
  if (!IC)
623
19.9k
    return;
624
5.11k
625
5.11k
  // Calling a destructor on a moved object is fine.
626
5.11k
  if (isa<CXXDestructorCall>(IC))
627
518
    return;
628
4.59k
629
4.59k
  const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
630
4.59k
  if (!ThisRegion)
631
0
    return;
632
4.59k
633
4.59k
  // The remaining part is check only for method call on a moved-from object.
634
4.59k
  const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
635
4.59k
  if (!MethodDecl)
636
1
    return;
637
4.59k
638
4.59k
  // We want to investigate the whole object, not only sub-object of a parent
639
4.59k
  // class in which the encountered method defined.
640
4.59k
  ThisRegion = ThisRegion->getMostDerivedObjectRegion();
641
4.59k
642
4.59k
  if (isStateResetMethod(MethodDecl)) {
643
72
    State = removeFromState(State, ThisRegion);
644
72
    C.addTransition(State);
645
72
    return;
646
72
  }
647
4.52k
648
4.52k
  if (isMoveSafeMethod(MethodDecl))
649
84
    return;
650
4.43k
651
4.43k
  // Store class declaration as well, for bug reporting purposes.
652
4.43k
  const CXXRecordDecl *RD = MethodDecl->getParent();
653
4.43k
654
4.43k
  if (MethodDecl->isOverloadedOperator()) {
655
1.93k
    OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator();
656
1.93k
657
1.93k
    if (OOK == OO_Equal) {
658
1.39k
      // Remove the tracked object for every assignment operator, but report bug
659
1.39k
      // only for move or copy assignment's argument.
660
1.39k
      State = removeFromState(State, ThisRegion);
661
1.39k
662
1.39k
      if (MethodDecl->isCopyAssignmentOperator() ||
663
1.39k
          
MethodDecl->isMoveAssignmentOperator()1.34k
) {
664
1.38k
        const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
665
1.38k
        MisuseKind MK =
666
1.38k
            MethodDecl->isMoveAssignmentOperator() ? 
MK_Move1.34k
:
MK_Copy42
;
667
1.38k
        modelUse(State, ArgRegion, RD, MK, C);
668
1.38k
        return;
669
1.38k
      }
670
4
      C.addTransition(State);
671
4
      return;
672
4
    }
673
540
674
540
    if (OOK == OO_Star || 
OOK == OO_Arrow294
) {
675
254
      modelUse(State, ThisRegion, RD, MK_Dereference, C);
676
254
      return;
677
254
    }
678
2.79k
  }
679
2.79k
680
2.79k
  modelUse(State, ThisRegion, RD, MK_FunCall, C);
681
2.79k
}
682
683
void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper,
684
130k
                                   CheckerContext &C) const {
685
130k
  ProgramStateRef State = C.getState();
686
130k
  TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
687
130k
  for (TrackedRegionMapTy::value_type E : TrackedRegions) {
688
8.36k
    const MemRegion *Region = E.first;
689
8.36k
    bool IsRegDead = !SymReaper.isLiveRegion(Region);
690
8.36k
691
8.36k
    // Remove the dead regions from the region map.
692
8.36k
    if (IsRegDead) {
693
1.16k
      State = State->remove<TrackedRegionMap>(Region);
694
1.16k
    }
695
8.36k
  }
696
130k
  C.addTransition(State);
697
130k
}
698
699
ProgramStateRef MoveChecker::checkRegionChanges(
700
    ProgramStateRef State, const InvalidatedSymbols *Invalidated,
701
    ArrayRef<const MemRegion *> RequestedRegions,
702
    ArrayRef<const MemRegion *> InvalidatedRegions,
703
38.7k
    const LocationContext *LCtx, const CallEvent *Call) const {
704
38.7k
  if (Call) {
705
8.15k
    // Relax invalidation upon function calls: only invalidate parameters
706
8.15k
    // that are passed directly via non-const pointers or non-const references
707
8.15k
    // or rvalue references.
708
8.15k
    // In case of an InstanceCall don't invalidate the this-region since
709
8.15k
    // it is fully handled in checkPreCall and checkPostCall.
710
8.15k
    const MemRegion *ThisRegion = nullptr;
711
8.15k
    if (const auto *IC = dyn_cast<CXXInstanceCall>(Call))
712
2.50k
      ThisRegion = IC->getCXXThisVal().getAsRegion();
713
8.15k
714
8.15k
    // Requested ("explicit") regions are the regions passed into the call
715
8.15k
    // directly, but not all of them end up being invalidated.
716
8.15k
    // But when they do, they appear in the InvalidatedRegions array as well.
717
8.15k
    for (const auto *Region : RequestedRegions) {
718
3.25k
      if (ThisRegion != Region) {
719
1.13k
        if (llvm::find(InvalidatedRegions, Region) !=
720
1.13k
            std::end(InvalidatedRegions)) {
721
804
          State = removeFromState(State, Region);
722
804
        }
723
1.13k
      }
724
3.25k
    }
725
30.6k
  } else {
726
30.6k
    // For invalidations that aren't caused by calls, assume nothing. In
727
30.6k
    // particular, direct write into an object's field invalidates the status.
728
30.6k
    for (const auto *Region : InvalidatedRegions)
729
30.6k
      State = removeFromState(State, Region->getBaseRegion());
730
30.6k
  }
731
38.7k
732
38.7k
  return State;
733
38.7k
}
734
735
void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State,
736
4
                             const char *NL, const char *Sep) const {
737
4
738
4
  TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
739
4
740
4
  if (!RS.isEmpty()) {
741
4
    Out << Sep << "Moved-from objects :" << NL;
742
8
    for (auto I: RS) {
743
8
      I.first->dumpToStream(Out);
744
8
      if (I.second.isMoved())
745
8
        Out << ": moved";
746
0
      else
747
0
        Out << ": moved and reported";
748
8
      Out << NL;
749
8
    }
750
4
  }
751
4
}
752
49
void ento::registerMoveChecker(CheckerManager &mgr) {
753
49
  MoveChecker *chk = mgr.registerChecker<MoveChecker>();
754
49
  chk->setAggressiveness(
755
49
      mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr);
756
49
}
757
758
49
bool ento::shouldRegisterMoveChecker(const LangOptions &LO) {
759
49
  return true;
760
49
}