Coverage Report

Created: 2020-09-22 08:39

/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.21k
  RegionState(Kind InK) : K(InK) {}
34
35
public:
36
316
  bool isReported() const { return K == Reported; }
37
16
  bool isMoved() const { return K == Moved; }
38
39
231
  static RegionState getReported() { return RegionState(Reported); }
40
1.98k
  static RegionState getMoved() { return RegionState(Moved); }
41
42
922
  bool operator==(const RegionState &X) const { return K == X.K; }
43
2.87k
  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
309
  static bool misuseCausesCrash(MisuseKind MK) {
78
309
    return MK == MK_Dereference;
79
309
  }
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.39k
  bool shouldBeTracked(ObjectKind OK) const {
117
    // In non-aggressive mode, only warn on use-after-move of local variables
118
    // (or local rvalue references) and of STL objects. The former is possible
119
    // because local variables (or local rvalue references) are not tempting
120
    // their user to re-use the storage. The latter is possible because STL
121
    // objects are known to end up in a valid but unspecified state after the
122
    // move and their state-reset methods are also known, which allows us to
123
    // predict precisely when use-after-move is invalid.
124
    // Some STL objects are known to conform to additional contracts after move,
125
    // so they are not tracked. However, smart pointers specifically are tracked
126
    // because we can perform extra checking over them.
127
    // In aggressive mode, warn on any use-after-move because the user has
128
    // intentionally asked us to completely eliminate use-after-move
129
    // in his code.
130
3.39k
    return (Aggressiveness == AK_All) ||
131
1.72k
           (Aggressiveness >= AK_KnownsAndLocals && 
OK.IsLocal1.01k
) ||
132
1.11k
           OK.StdKind == SK_Unsafe || 
OK.StdKind == SK_SmartPtr1.07k
;
133
3.39k
  }
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
357
  bool shouldWarnAbout(ObjectKind OK, MisuseKind MK) const {
138
    // Additionally, only warn on smart pointers when they are dereferenced (or
139
    // local or we are aggressive).
140
357
    return shouldBeTracked(OK) &&
141
357
           ((Aggressiveness == AK_All) ||
142
101
            (Aggressiveness >= AK_KnownsAndLocals && 
OK.IsLocal89
) ||
143
18
            OK.StdKind != SK_SmartPtr || 
MK == MK_Dereference14
);
144
357
  }
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
243
        : Chk(Chk), Region(R), RD(RD), MK(MK), Found(false) {}
162
163
243
    void Profile(llvm::FoldingSetNodeID &ID) const override {
164
243
      static int X = 0;
165
243
      ID.AddPointer(&X);
166
243
      ID.AddPointer(Region);
167
      // Don't add RD because it's, in theory, uniquely determined by
168
      // the region. In practice though, it's not always possible to obtain
169
      // the declaration directly from the region, that's why we store it
170
      // in the first place.
171
243
    }
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
70
  void setAggressiveness(StringRef Str, CheckerManager &Mgr) {
192
70
    Aggressiveness =
193
70
        llvm::StringSwitch<AggressivenessKind>(Str)
194
70
            .Case("KnownsOnly", AK_KnownsOnly)
195
70
            .Case("KnownsAndLocals", AK_KnownsAndLocals)
196
70
            .Case("All", AK_All)
197
70
            .Default(AK_Invalid);
198
199
70
    if (Aggressiveness == AK_Invalid)
200
1
      Mgr.reportInvalidCheckerOptionValue(this, "WarnOn",
201
1
          "either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value");
202
70
  };
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
17
bool isMovedFrom(ProgramStateRef State, const MemRegion *Region) {
236
17
  const RegionState *RS = State->get<TrackedRegionMap>(Region);
237
17
  return RS && 
(8
RS->isMoved()8
||
RS->isReported()0
);
238
17
}
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
57.1k
                                       const MemRegion *Region) {
246
57.1k
  if (!Region)
247
0
    return State;
248
57.1k
  for (auto &E : State->get<TrackedRegionMap>()) {
249
1.58k
    if (E.first->isSubRegionOf(Region))
250
612
      State = State->remove<TrackedRegionMap>(E.first);
251
1.58k
  }
252
57.1k
  return State;
253
57.1k
}
254
255
static bool isAnyBaseRegionReported(ProgramStateRef State,
256
309
                                    const MemRegion *Region) {
257
388
  for (auto &E : State->get<TrackedRegionMap>()) {
258
388
    if (Region->isSubRegionOf(E.first) && 
E.second.isReported()316
)
259
66
      return true;
260
388
  }
261
243
  return false;
262
309
}
263
264
20.3k
static const MemRegion *unwrapRValueReferenceIndirection(const MemRegion *MR) {
265
20.3k
  if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) {
266
3.21k
    SymbolRef Sym = SR->getSymbol();
267
3.21k
    if (Sym->getType()->isRValueReferenceType())
268
63
      if (const MemRegion *OriginMR = Sym->getOriginRegion())
269
56
        return OriginMR;
270
20.2k
  }
271
20.2k
  return MR;
272
20.2k
}
273
274
PathDiagnosticPieceRef
275
MoveChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N,
276
                                        BugReporterContext &BRC,
277
136k
                                        PathSensitiveBugReport &BR) {
278
  // We need only the last move of the reported object's region.
279
  // The visitor walks the ExplodedGraph backwards.
280
136k
  if (Found)
281
133k
    return nullptr;
282
3.09k
  ProgramStateRef State = N->getState();
283
3.09k
  ProgramStateRef StatePrev = N->getFirstPred()->getState();
284
3.09k
  const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region);
285
3.09k
  const RegionState *TrackedObjectPrev =
286
3.09k
      StatePrev->get<TrackedRegionMap>(Region);
287
3.09k
  if (!TrackedObject)
288
0
    return nullptr;
289
3.09k
  if (TrackedObjectPrev && 
TrackedObject2.87k
)
290
2.87k
    return nullptr;
291
292
  // Retrieve the associated statement.
293
219
  const Stmt *S = N->getStmtForDiagnostics();
294
219
  if (!S)
295
0
    return nullptr;
296
219
  Found = true;
297
298
219
  SmallString<128> Str;
299
219
  llvm::raw_svector_ostream OS(Str);
300
301
219
  ObjectKind OK = Chk.classifyObject(Region, RD);
302
219
  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
311
      // If it's not a dereference, we don't care if it was reset to null
312
      // or that it is even a smart pointer.
313
17
      LLVM_FALLTHROUGH;
314
199
    case SK_NonStd:
315
199
    case SK_Safe:
316
199
      OS << "Object";
317
199
      Chk.explainObject(OS, Region, RD, MK);
318
199
      OS << " is moved";
319
199
      break;
320
8
    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
219
  }
326
327
  // Generate the extra diagnostic.
328
219
  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
329
219
                             N->getLocationContext());
330
219
  return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true);
331
219
}
332
333
const ExplodedNode *MoveChecker::getMoveLocation(const ExplodedNode *N,
334
                                                 const MemRegion *Region,
335
243
                                                 CheckerContext &C) const {
336
  // Walk the ExplodedGraph backwards and find the first node that referred to
337
  // the tracked region.
338
243
  const ExplodedNode *MoveNode = N;
339
340
3.90k
  while (N) {
341
3.90k
    ProgramStateRef State = N->getState();
342
3.90k
    if (!State->get<TrackedRegionMap>(Region))
343
243
      break;
344
3.65k
    MoveNode = N;
345
3.65k
    N = N->pred_empty() ? 
nullptr0
: *(N->pred_begin());
346
3.65k
  }
347
243
  return MoveNode;
348
243
}
349
350
void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region,
351
                           const CXXRecordDecl *RD, MisuseKind MK,
352
16.1k
                           CheckerContext &C) const {
353
16.1k
  assert(!C.isDifferent() && "No transitions should have been made by now");
354
16.1k
  const RegionState *RS = State->get<TrackedRegionMap>(Region);
355
16.1k
  ObjectKind OK = classifyObject(Region, RD);
356
357
  // Just in case: if it's not a smart pointer but it does have operator *,
358
  // we shouldn't call the bug a dereference.
359
16.1k
  if (MK == MK_Dereference && 
OK.StdKind != SK_SmartPtr108
)
360
64
    MK = MK_FunCall;
361
362
16.1k
  if (!RS || 
!shouldWarnAbout(OK, MK)357
363
15.8k
          || 
isInMoveSafeContext(C.getLocationContext())349
) {
364
    // Finalize changes made by the caller.
365
15.8k
    C.addTransition(State);
366
15.8k
    return;
367
15.8k
  }
368
369
  // Don't report it in case if any base region is already reported.
370
  // But still generate a sink in case of UB.
371
  // And still finalize changes made by the caller.
372
309
  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
381
243
  ExplodedNode *N = reportBug(Region, RD, C, MK);
382
383
  // If the program has already crashed on this path, don't bother.
384
243
  if (N->isSink())
385
12
    return;
386
387
231
  State = State->set<TrackedRegionMap>(Region, RegionState::getReported());
388
231
  C.addTransition(State, N);
389
231
}
390
391
ExplodedNode *MoveChecker::reportBug(const MemRegion *Region,
392
                                     const CXXRecordDecl *RD, CheckerContext &C,
393
243
                                     MisuseKind MK) const {
394
243
  if (ExplodedNode *N = misuseCausesCrash(MK) ? C.generateErrorNode()
395
243
                                              : C.generateNonFatalErrorNode()) {
396
397
243
    if (!BT)
398
9
      BT.reset(new BugType(this, "Use-after-move",
399
9
                           "C++ move semantics"));
400
401
    // Uniqueing report to the same object.
402
243
    PathDiagnosticLocation LocUsedForUniqueing;
403
243
    const ExplodedNode *MoveNode = getMoveLocation(N, Region, C);
404
405
243
    if (const Stmt *MoveStmt = MoveNode->getStmtForDiagnostics())
406
243
      LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
407
243
          MoveStmt, C.getSourceManager(), MoveNode->getLocationContext());
408
409
    // Creating the error message.
410
243
    llvm::SmallString<128> Str;
411
243
    llvm::raw_svector_ostream OS(Str);
412
243
    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
22
      case MK_Move:
423
22
        OS << "Moved-from object";
424
22
        explainObject(OS, Region, RD, MK);
425
22
        OS << " is moved";
426
22
        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
243
    }
432
433
243
    auto R = std::make_unique<PathSensitiveBugReport>(
434
243
        *BT, OS.str(), N, LocUsedForUniqueing,
435
243
        MoveNode->getLocationContext()->getDecl());
436
243
    R->addVisitor(std::make_unique<MovedBugVisitor>(*this, Region, RD, MK));
437
243
    C.emitReport(std::move(R));
438
243
    return N;
439
243
  }
440
0
  return nullptr;
441
0
}
442
443
void MoveChecker::checkPostCall(const CallEvent &Call,
444
49.7k
                                CheckerContext &C) const {
445
49.7k
  const auto *AFC = dyn_cast<AnyFunctionCall>(&Call);
446
49.7k
  if (!AFC)
447
3
    return;
448
449
49.7k
  ProgramStateRef State = C.getState();
450
49.7k
  const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl());
451
49.7k
  if (!MethodDecl)
452
27.5k
    return;
453
454
  // Check if an object became moved-from.
455
  // Object can become moved from after a call to move assignment operator or
456
  // move constructor .
457
22.1k
  const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl);
458
22.1k
  if (ConstructorDecl && 
!ConstructorDecl->isMoveConstructor()13.7k
)
459
11.6k
    return;
460
461
10.5k
  if (!ConstructorDecl && 
!MethodDecl->isMoveAssignmentOperator()8.48k
)
462
7.10k
    return;
463
464
3.40k
  const auto ArgRegion = AFC->getArgSVal(0).getAsRegion();
465
3.40k
  if (!ArgRegion)
466
0
    return;
467
468
  // Skip moving the object to itself.
469
3.40k
  const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call);
470
3.40k
  if (CC && 
CC->getCXXThisVal().getAsRegion() == ArgRegion2.02k
)
471
0
    return;
472
473
3.40k
  if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC))
474
1.37k
    if (IC->getCXXThisVal().getAsRegion() == ArgRegion)
475
0
      return;
476
477
3.40k
  const MemRegion *BaseRegion = ArgRegion->getBaseRegion();
478
  // Skip temp objects because of their short lifetime.
479
3.40k
  if (BaseRegion->getAs<CXXTempObjectRegion>() ||
480
3.10k
      AFC->getArgExpr(0)->isRValue())
481
300
    return;
482
  // If it has already been reported do not need to modify the state.
483
484
3.10k
  if (State->get<TrackedRegionMap>(ArgRegion))
485
64
    return;
486
487
3.03k
  const CXXRecordDecl *RD = MethodDecl->getParent();
488
3.03k
  ObjectKind OK = classifyObject(ArgRegion, RD);
489
3.03k
  if (shouldBeTracked(OK)) {
490
    // Mark object as moved-from.
491
1.98k
    State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved());
492
1.98k
    C.addTransition(State);
493
1.98k
    return;
494
1.98k
  }
495
1.04k
  assert(!C.isDifferent() && "Should not have made transitions on this path!");
496
1.04k
}
497
498
8.25k
bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const {
499
  // We abandon the cases where bool/void/void* conversion happens.
500
8.25k
  if (const auto *ConversionDec =
501
110
          dyn_cast_or_null<CXXConversionDecl>(MethodDec)) {
502
110
    const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull();
503
110
    if (!Tp)
504
0
      return false;
505
110
    if (Tp->isBooleanType() || 
Tp->isVoidType()22
||
Tp->isVoidPointerType()22
)
506
88
      return true;
507
8.16k
  }
508
  // Function call `empty` can be skipped.
509
8.16k
  return (MethodDec && 
MethodDec->getDeclName().isIdentifier()7.87k
&&
510
5.17k
      (MethodDec->getName().lower() == "empty" ||
511
5.16k
       MethodDec->getName().lower() == "isempty"));
512
8.16k
}
513
514
8.37k
bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const {
515
8.37k
  if (!MethodDec)
516
287
      return false;
517
8.08k
  if (MethodDec->hasAttr<ReinitializesAttr>())
518
8
      return true;
519
8.07k
  if (MethodDec->getDeclName().isIdentifier()) {
520
5.28k
    std::string MethodName = MethodDec->getName().lower();
521
    // TODO: Some of these methods (eg., resize) are not always resetting
522
    // the state, so we should consider looking at the arguments.
523
5.28k
    if (MethodName == "assign" || 
MethodName == "clear"5.25k
||
524
5.21k
        MethodName == "destroy" || 
MethodName == "reset"5.20k
||
525
5.18k
        MethodName == "resize" || 
MethodName == "shrink"5.17k
)
526
112
      return true;
527
7.96k
  }
528
7.96k
  return false;
529
7.96k
}
530
531
// Don't report an error inside a move related operation.
532
// We assume that the programmer knows what she does.
533
349
bool MoveChecker::isInMoveSafeContext(const LocationContext *LC) const {
534
363
  do {
535
363
    const auto *CtxDec = LC->getDecl();
536
363
    auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec);
537
363
    auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec);
538
363
    auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec);
539
363
    if (DtorDec || (CtorDec && 
CtorDec->isCopyOrMoveConstructor()32
) ||
540
331
        (MethodDec && 
MethodDec->isOverloadedOperator()44
&&
541
8
         MethodDec->getOverloadedOperator() == OO_Equal) ||
542
323
        isStateResetMethod(MethodDec) || isMoveSafeMethod(MethodDec))
543
40
      return true;
544
323
  } while ((LC = LC->getParent()));
545
309
  return false;
546
349
}
547
548
bool MoveChecker::belongsTo(const CXXRecordDecl *RD,
549
6.54k
                            const llvm::StringSet<> &Set) const {
550
6.54k
  const IdentifierInfo *II = RD->getIdentifier();
551
6.54k
  return II && Set.count(II->getName());
552
6.54k
}
553
554
MoveChecker::ObjectKind
555
MoveChecker::classifyObject(const MemRegion *MR,
556
19.8k
                            const CXXRecordDecl *RD) const {
557
  // Local variables and local rvalue references are classified as "Local".
558
  // For the purposes of this checker, we classify move-safe STL types
559
  // as not-"STL" types, because that's how the checker treats them.
560
19.8k
  MR = unwrapRValueReferenceIndirection(MR);
561
19.8k
  bool IsLocal =
562
19.8k
      MR && isa<VarRegion>(MR) && 
isa<StackSpaceRegion>(MR->getMemorySpace())7.41k
;
563
564
19.8k
  if (!RD || !RD->getDeclContext()->isStdNamespace())
565
16.4k
    return { IsLocal, SK_NonStd };
566
567
3.42k
  if (belongsTo(RD, StdSmartPtrClasses))
568
302
    return { IsLocal, SK_SmartPtr };
569
570
3.12k
  if (belongsTo(RD, StdSafeClasses))
571
40
    return { IsLocal, SK_Safe };
572
573
3.08k
  return { IsLocal, SK_Unsafe };
574
3.08k
}
575
576
void MoveChecker::explainObject(llvm::raw_ostream &OS, const MemRegion *MR,
577
462
                                const CXXRecordDecl *RD, MisuseKind MK) const {
578
  // We may need a leading space every time we actually explain anything,
579
  // and we never know if we are to explain anything until we try.
580
462
  if (const auto DR =
581
438
          dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) {
582
438
    const auto *RegionDecl = cast<NamedDecl>(DR->getDecl());
583
438
    OS << " '" << RegionDecl->getDeclName() << "'";
584
438
  }
585
586
462
  ObjectKind OK = classifyObject(MR, RD);
587
462
  switch (OK.StdKind) {
588
388
    case SK_NonStd:
589
388
    case SK_Safe:
590
388
      break;
591
58
    case SK_SmartPtr:
592
58
      if (MK != MK_Dereference)
593
34
        break;
594
595
      // 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
462
  };
601
462
}
602
603
48.3k
void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const {
604
48.3k
  ProgramStateRef State = C.getState();
605
606
  // Remove the MemRegions from the map on which a ctor/dtor call or assignment
607
  // happened.
608
609
  // Checking constructor calls.
610
48.3k
  if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) {
611
13.7k
    State = removeFromState(State, CC->getCXXThisVal().getAsRegion());
612
13.7k
    auto CtorDec = CC->getDecl();
613
    // Check for copying a moved-from object and report the bug.
614
13.7k
    if (CtorDec && CtorDec->isCopyOrMoveConstructor()) {
615
8.31k
      const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion();
616
8.31k
      const CXXRecordDecl *RD = CtorDec->getParent();
617
6.27k
      MisuseKind MK = CtorDec->isMoveConstructor() ? 
MK_Move2.03k
: MK_Copy;
618
8.31k
      modelUse(State, ArgRegion, RD, MK, C);
619
8.31k
      return;
620
8.31k
    }
621
40.0k
  }
622
623
40.0k
  const auto IC = dyn_cast<CXXInstanceCall>(&Call);
624
40.0k
  if (!IC)
625
31.5k
    return;
626
627
  // Calling a destructor on a moved object is fine.
628
8.55k
  if (isa<CXXDestructorCall>(IC))
629
499
    return;
630
631
8.05k
  const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
632
8.05k
  if (!ThisRegion)
633
2
    return;
634
635
  // The remaining part is check only for method call on a moved-from object.
636
8.05k
  const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl());
637
8.05k
  if (!MethodDecl)
638
1
    return;
639
640
  // We want to investigate the whole object, not only sub-object of a parent
641
  // class in which the encountered method defined.
642
8.05k
  ThisRegion = ThisRegion->getMostDerivedObjectRegion();
643
644
8.05k
  if (isStateResetMethod(MethodDecl)) {
645
120
    State = removeFromState(State, ThisRegion);
646
120
    C.addTransition(State);
647
120
    return;
648
120
  }
649
650
7.93k
  if (isMoveSafeMethod(MethodDecl))
651
104
    return;
652
653
  // Store class declaration as well, for bug reporting purposes.
654
7.82k
  const CXXRecordDecl *RD = MethodDecl->getParent();
655
656
7.82k
  if (MethodDecl->isOverloadedOperator()) {
657
2.67k
    OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator();
658
659
2.67k
    if (OOK == OO_Equal) {
660
      // Remove the tracked object for every assignment operator, but report bug
661
      // only for move or copy assignment's argument.
662
1.43k
      State = removeFromState(State, ThisRegion);
663
664
1.43k
      if (MethodDecl->isCopyAssignmentOperator() ||
665
1.42k
          
MethodDecl->isMoveAssignmentOperator()1.38k
) {
666
1.42k
        const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion();
667
1.42k
        MisuseKind MK =
668
1.37k
            MethodDecl->isMoveAssignmentOperator() ? MK_Move : 
MK_Copy50
;
669
1.42k
        modelUse(State, ArgRegion, RD, MK, C);
670
1.42k
        return;
671
1.42k
      }
672
9
      C.addTransition(State);
673
9
      return;
674
9
    }
675
676
1.24k
    if (OOK == OO_Star || 
OOK == OO_Arrow1.17k
) {
677
108
      modelUse(State, ThisRegion, RD, MK_Dereference, C);
678
108
      return;
679
108
    }
680
6.28k
  }
681
682
6.28k
  modelUse(State, ThisRegion, RD, MK_FunCall, C);
683
6.28k
}
684
685
void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper,
686
166k
                                   CheckerContext &C) const {
687
166k
  ProgramStateRef State = C.getState();
688
166k
  TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
689
8.68k
  for (auto E : TrackedRegions) {
690
8.68k
    const MemRegion *Region = E.first;
691
8.68k
    bool IsRegDead = !SymReaper.isLiveRegion(Region);
692
693
    // Remove the dead regions from the region map.
694
8.68k
    if (IsRegDead) {
695
1.26k
      State = State->remove<TrackedRegionMap>(Region);
696
1.26k
    }
697
8.68k
  }
698
166k
  C.addTransition(State);
699
166k
}
700
701
ProgramStateRef MoveChecker::checkRegionChanges(
702
    ProgramStateRef State, const InvalidatedSymbols *Invalidated,
703
    ArrayRef<const MemRegion *> RequestedRegions,
704
    ArrayRef<const MemRegion *> InvalidatedRegions,
705
46.8k
    const LocationContext *LCtx, const CallEvent *Call) const {
706
46.8k
  if (Call) {
707
    // Relax invalidation upon function calls: only invalidate parameters
708
    // that are passed directly via non-const pointers or non-const references
709
    // or rvalue references.
710
    // In case of an InstanceCall don't invalidate the this-region since
711
    // it is fully handled in checkPreCall and checkPostCall.
712
12.9k
    const MemRegion *ThisRegion = nullptr;
713
12.9k
    if (const auto *IC = dyn_cast<CXXInstanceCall>(Call))
714
5.45k
      ThisRegion = IC->getCXXThisVal().getAsRegion();
715
716
    // Requested ("explicit") regions are the regions passed into the call
717
    // directly, but not all of them end up being invalidated.
718
    // But when they do, they appear in the InvalidatedRegions array as well.
719
13.7k
    for (const auto *Region : RequestedRegions) {
720
13.7k
      if (ThisRegion != Region) {
721
9.82k
        if (llvm::find(InvalidatedRegions, Region) !=
722
7.91k
            std::end(InvalidatedRegions)) {
723
7.91k
          State = removeFromState(State, Region);
724
7.91k
        }
725
9.82k
      }
726
13.7k
    }
727
33.9k
  } else {
728
    // For invalidations that aren't caused by calls, assume nothing. In
729
    // particular, direct write into an object's field invalidates the status.
730
33.9k
    for (const auto *Region : InvalidatedRegions)
731
33.9k
      State = removeFromState(State, Region->getBaseRegion());
732
33.9k
  }
733
734
46.8k
  return State;
735
46.8k
}
736
737
void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State,
738
40
                             const char *NL, const char *Sep) const {
739
740
40
  TrackedRegionMapTy RS = State->get<TrackedRegionMap>();
741
742
40
  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
40
}
754
70
void ento::registerMoveChecker(CheckerManager &mgr) {
755
70
  MoveChecker *chk = mgr.registerChecker<MoveChecker>();
756
70
  chk->setAggressiveness(
757
70
      mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr);
758
70
}
759
760
140
bool ento::shouldRegisterMoveChecker(const CheckerManager &mgr) {
761
140
  return true;
762
140
}