Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
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 file defines a set of BugReporter "visitors" which can be used to
10
//  enhance the diagnostics reported for a bug.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/Decl.h"
17
#include "clang/AST/DeclBase.h"
18
#include "clang/AST/DeclCXX.h"
19
#include "clang/AST/Expr.h"
20
#include "clang/AST/ExprCXX.h"
21
#include "clang/AST/ExprObjC.h"
22
#include "clang/AST/Stmt.h"
23
#include "clang/AST/Type.h"
24
#include "clang/ASTMatchers/ASTMatchFinder.h"
25
#include "clang/Analysis/Analyses/Dominators.h"
26
#include "clang/Analysis/AnalysisDeclContext.h"
27
#include "clang/Analysis/CFG.h"
28
#include "clang/Analysis/CFGStmtMap.h"
29
#include "clang/Analysis/ProgramPoint.h"
30
#include "clang/Basic/IdentifierTable.h"
31
#include "clang/Basic/LLVM.h"
32
#include "clang/Basic/SourceLocation.h"
33
#include "clang/Basic/SourceManager.h"
34
#include "clang/Lex/Lexer.h"
35
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
36
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
37
#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
38
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
39
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
40
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
41
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
42
#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
43
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
44
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
45
#include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
46
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
47
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
48
#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
49
#include "llvm/ADT/ArrayRef.h"
50
#include "llvm/ADT/None.h"
51
#include "llvm/ADT/Optional.h"
52
#include "llvm/ADT/STLExtras.h"
53
#include "llvm/ADT/SmallPtrSet.h"
54
#include "llvm/ADT/SmallString.h"
55
#include "llvm/ADT/SmallVector.h"
56
#include "llvm/ADT/StringExtras.h"
57
#include "llvm/ADT/StringRef.h"
58
#include "llvm/Support/Casting.h"
59
#include "llvm/Support/ErrorHandling.h"
60
#include "llvm/Support/raw_ostream.h"
61
#include <cassert>
62
#include <deque>
63
#include <memory>
64
#include <string>
65
#include <utility>
66
67
using namespace clang;
68
using namespace ento;
69
70
//===----------------------------------------------------------------------===//
71
// Utility functions.
72
//===----------------------------------------------------------------------===//
73
74
82
static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
75
82
  if (B->isAdditiveOp() && 
B->getType()->isPointerType()61
) {
76
19
    if (B->getLHS()->getType()->isPointerType()) {
77
18
      return B->getLHS();
78
18
    } else 
if (1
B->getRHS()->getType()->isPointerType()1
) {
79
1
      return B->getRHS();
80
1
    }
81
63
  }
82
63
  return nullptr;
83
63
}
84
85
/// Given that expression S represents a pointer that would be dereferenced,
86
/// try to find a sub-expression from which the pointer came from.
87
/// This is used for tracking down origins of a null or undefined value:
88
/// "this is null because that is null because that is null" etc.
89
/// We wipe away field and element offsets because they merely add offsets.
90
/// We also wipe away all casts except lvalue-to-rvalue casts, because the
91
/// latter represent an actual pointer dereference; however, we remove
92
/// the final lvalue-to-rvalue cast before returning from this function
93
/// because it demonstrates more clearly from where the pointer rvalue was
94
/// loaded. Examples:
95
///   x->y.z      ==>  x (lvalue)
96
///   foo()->y.z  ==>  foo() (rvalue)
97
776
const Expr *bugreporter::getDerefExpr(const Stmt *S) {
98
776
  const auto *E = dyn_cast<Expr>(S);
99
776
  if (!E)
100
0
    return nullptr;
101
776
102
1.72k
  
while (776
true) {
103
1.72k
    if (const auto *CE = dyn_cast<CastExpr>(E)) {
104
781
      if (CE->getCastKind() == CK_LValueToRValue) {
105
680
        // This cast represents the load we're looking for.
106
680
        break;
107
680
      }
108
101
      E = CE->getSubExpr();
109
941
    } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
110
14
      // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
111
14
      if (const Expr *Inner = peelOffPointerArithmetic(B)) {
112
12
        E = Inner;
113
12
      } else {
114
2
        // Probably more arithmetic can be pattern-matched here,
115
2
        // but for now give up.
116
2
        break;
117
2
      }
118
927
    } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
119
712
      if (U->getOpcode() == UO_Deref || 
U->getOpcode() == UO_AddrOf8
||
120
712
          
(4
U->isIncrementDecrementOp()4
&&
U->getType()->isPointerType()4
)) {
121
712
        // Operators '*' and '&' don't actually mean anything.
122
712
        // We look at casts instead.
123
712
        E = U->getSubExpr();
124
712
      } else {
125
0
        // Probably more arithmetic can be pattern-matched here,
126
0
        // but for now give up.
127
0
        break;
128
0
      }
129
215
    }
130
215
    // Pattern match for a few useful cases: a[0], p->f, *p etc.
131
215
    else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
132
34
      E = ME->getBase();
133
181
    } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
134
16
      E = IvarRef->getBase();
135
165
    } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
136
27
      E = AE->getBase();
137
138
    } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
138
43
      E = PE->getSubExpr();
139
95
    } else if (const auto *FE = dyn_cast<FullExpr>(E)) {
140
1
      E = FE->getSubExpr();
141
94
    } else {
142
94
      // Other arbitrary stuff.
143
94
      break;
144
94
    }
145
1.72k
  }
146
776
147
776
  // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
148
776
  // deeper into the sub-expression. This way we return the lvalue from which
149
776
  // our pointer rvalue was loaded.
150
776
  if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
151
680
    if (CE->getCastKind() == CK_LValueToRValue)
152
680
      E = CE->getSubExpr();
153
776
154
776
  return E;
155
776
}
156
157
/// Comparing internal representations of symbolic values (via
158
/// SVal::operator==()) is a valid way to check if the value was updated,
159
/// unless it's a LazyCompoundVal that may have a different internal
160
/// representation every time it is loaded from the state. In this function we
161
/// do an approximate comparison for lazy compound values, checking that they
162
/// are the immediate snapshots of the tracked region's bindings within the
163
/// node's respective states but not really checking that these snapshots
164
/// actually contain the same set of bindings.
165
static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
166
28.7k
                             const ExplodedNode *RightNode, SVal RightVal) {
167
28.7k
  if (LeftVal == RightVal)
168
28.3k
    return true;
169
375
170
375
  const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
171
375
  if (!LLCV)
172
370
    return false;
173
5
174
5
  const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
175
5
  if (!RLCV)
176
0
    return false;
177
5
178
5
  return LLCV->getRegion() == RLCV->getRegion() &&
179
5
    LLCV->getStore() == LeftNode->getState()->getStore() &&
180
5
    RLCV->getStore() == RightNode->getState()->getStore();
181
5
}
182
183
static Optional<const llvm::APSInt *>
184
331
getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) {
185
331
  ProgramStateRef State = N->getState();
186
331
  const LocationContext *LCtx = N->getLocationContext();
187
331
188
331
  // The declaration of the value may rely on a pointer so take its l-value.
189
331
  if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(CondVarExpr)) {
190
271
    if (const auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl())) {
191
271
      SVal DeclSVal = State->getSVal(State->getLValue(VD, LCtx));
192
271
      if (auto DeclCI = DeclSVal.getAs<nonloc::ConcreteInt>())
193
73
        return &DeclCI->getValue();
194
258
    }
195
271
  }
196
258
197
258
  return {};
198
258
}
199
200
/// \return name of the macro inside the location \p Loc.
201
static StringRef getMacroName(SourceLocation Loc,
202
33
    BugReporterContext &BRC) {
203
33
  return Lexer::getImmediateMacroName(
204
33
      Loc,
205
33
      BRC.getSourceManager(),
206
33
      BRC.getASTContext().getLangOpts());
207
33
}
208
209
/// \return Whether given spelling location corresponds to an expansion
210
/// of a function-like macro.
211
static bool isFunctionMacroExpansion(SourceLocation Loc,
212
717
                                const SourceManager &SM) {
213
717
  if (!Loc.isMacroID())
214
537
    return false;
215
180
  while (SM.isMacroArgExpansion(Loc))
216
0
    Loc = SM.getImmediateExpansionRange(Loc).getBegin();
217
180
  std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
218
180
  SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
219
180
  const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
220
180
  return EInfo.isFunctionMacroExpansion();
221
180
}
222
223
/// \return Whether \c RegionOfInterest was modified at \p N,
224
/// where \p ValueAfter is \c RegionOfInterest's value at the end of the
225
/// stack frame.
226
static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest,
227
                                          const ExplodedNode *N,
228
27.0k
                                          SVal ValueAfter) {
229
27.0k
  ProgramStateRef State = N->getState();
230
27.0k
  ProgramStateManager &Mgr = N->getState()->getStateManager();
231
27.0k
232
27.0k
  if (!N->getLocationAs<PostStore>() && 
!N->getLocationAs<PostInitializer>()26.3k
&&
233
27.0k
      
!N->getLocationAs<PostStmt>()26.2k
)
234
10.4k
    return false;
235
16.5k
236
16.5k
  // Writing into region of interest.
237
16.5k
  if (auto PS = N->getLocationAs<PostStmt>())
238
16.4k
    if (auto *BO = PS->getStmtAs<BinaryOperator>())
239
1.50k
      if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
240
1.02k
                                      N->getSVal(BO->getLHS()).getAsRegion()))
241
336
        return true;
242
16.2k
243
16.2k
  // SVal after the state is possibly different.
244
16.2k
  SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
245
16.2k
  if (!Mgr.getSValBuilder()
246
16.2k
           .areEqual(State, ValueAtN, ValueAfter)
247
16.2k
           .isConstrainedTrue() &&
248
16.2k
      
(6.70k
!ValueAtN.isUndef()6.70k
||
!ValueAfter.isUndef()5.95k
))
249
1.63k
    return true;
250
14.5k
251
14.5k
  return false;
252
14.5k
}
253
254
//===----------------------------------------------------------------------===//
255
// Implementation of BugReporterVisitor.
256
//===----------------------------------------------------------------------===//
257
258
std::shared_ptr<PathDiagnosticPiece>
259
BugReporterVisitor::getEndPath(BugReporterContext &,
260
46.2k
                               const ExplodedNode *, BugReport &) {
261
46.2k
  return nullptr;
262
46.2k
}
263
264
void
265
BugReporterVisitor::finalizeVisitor(BugReporterContext &,
266
37.0k
                                    const ExplodedNode *, BugReport &) {}
267
268
std::shared_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
269
1.28k
    BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
270
1.28k
  PathDiagnosticLocation L =
271
1.28k
    PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
272
1.28k
273
1.28k
  const auto &Ranges = BR.getRanges();
274
1.28k
275
1.28k
  // Only add the statement itself as a range if we didn't specify any
276
1.28k
  // special ranges for this report.
277
1.28k
  auto P = std::make_shared<PathDiagnosticEventPiece>(
278
1.28k
      L, BR.getDescription(), Ranges.begin() == Ranges.end());
279
1.28k
  for (SourceRange Range : Ranges)
280
1.22k
    P->addRange(Range);
281
1.28k
282
1.28k
  return P;
283
1.28k
}
284
285
//===----------------------------------------------------------------------===//
286
// Implementation of NoStoreFuncVisitor.
287
//===----------------------------------------------------------------------===//
288
289
namespace {
290
291
/// Put a diagnostic on return statement of all inlined functions
292
/// for which  the region of interest \p RegionOfInterest was passed into,
293
/// but not written inside, and it has caused an undefined read or a null
294
/// pointer dereference outside.
295
class NoStoreFuncVisitor final : public BugReporterVisitor {
296
  const SubRegion *RegionOfInterest;
297
  MemRegionManager &MmrMgr;
298
  const SourceManager &SM;
299
  const PrintingPolicy &PP;
300
301
  /// Recursion limit for dereferencing fields when looking for the
302
  /// region of interest.
303
  /// The limit of two indicates that we will dereference fields only once.
304
  static const unsigned DEREFERENCE_LIMIT = 2;
305
306
  /// Frames writing into \c RegionOfInterest.
307
  /// This visitor generates a note only if a function does not write into
308
  /// a region of interest. This information is not immediately available
309
  /// by looking at the node associated with the exit from the function
310
  /// (usually the return statement). To avoid recomputing the same information
311
  /// many times (going up the path for each node and checking whether the
312
  /// region was written into) we instead lazily compute the
313
  /// stack frames along the path which write into the region of interest.
314
  llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
315
  llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
316
317
  using RegionVector = SmallVector<const MemRegion *, 5>;
318
319
public:
320
  NoStoreFuncVisitor(const SubRegion *R)
321
      : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()),
322
        SM(MmrMgr.getContext().getSourceManager()),
323
1.49k
        PP(MmrMgr.getContext().getPrintingPolicy()) {}
324
325
1.49k
  void Profile(llvm::FoldingSetNodeID &ID) const override {
326
1.49k
    static int Tag = 0;
327
1.49k
    ID.AddPointer(&Tag);
328
1.49k
    ID.AddPointer(RegionOfInterest);
329
1.49k
  }
330
331
1
  void *getTag() const {
332
1
    static int Tag = 0;
333
1
    return static_cast<void *>(&Tag);
334
1
  }
335
336
  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
337
                                                 BugReporterContext &BR,
338
                                                 BugReport &R) override;
339
340
private:
341
  /// Attempts to find the region of interest in a given record decl,
342
  /// by either following the base classes or fields.
343
  /// Dereferences fields up to a given recursion limit.
344
  /// Note that \p Vec is passed by value, leading to quadratic copying cost,
345
  /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
346
  /// \return A chain fields leading to the region of interest or None.
347
  const Optional<RegionVector>
348
  findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
349
                               const MemRegion *R, const RegionVector &Vec = {},
350
                               int depth = 0);
351
352
  /// Check and lazily calculate whether the region of interest is
353
  /// modified in the stack frame to which \p N belongs.
354
  /// The calculation is cached in FramesModifyingRegion.
355
862
  bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
356
862
    const LocationContext *Ctx = N->getLocationContext();
357
862
    const StackFrameContext *SCtx = Ctx->getStackFrame();
358
862
    if (!FramesModifyingCalculated.count(SCtx))
359
697
      findModifyingFrames(N);
360
862
    return FramesModifyingRegion.count(SCtx);
361
862
  }
362
363
  /// Write to \c FramesModifyingRegion all stack frames along
364
  /// the path in the current stack frame which modify \c RegionOfInterest.
365
  void findModifyingFrames(const ExplodedNode *N);
366
367
  /// Consume the information on the no-store stack frame in order to
368
  /// either emit a note or suppress the report enirely.
369
  /// \return Diagnostics piece for region not modified in the current function,
370
  /// if it decides to emit one.
371
  std::shared_ptr<PathDiagnosticPiece>
372
  maybeEmitNote(BugReport &R, const CallEvent &Call, const ExplodedNode *N,
373
                const RegionVector &FieldChain, const MemRegion *MatchedRegion,
374
                StringRef FirstElement, bool FirstIsReferenceType,
375
                unsigned IndirectionLevel);
376
377
  /// Pretty-print region \p MatchedRegion to \p os.
378
  /// \return Whether printing succeeded.
379
  bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
380
                             const MemRegion *MatchedRegion,
381
                             const RegionVector &FieldChain,
382
                             int IndirectionLevel,
383
                             llvm::raw_svector_ostream &os);
384
385
  /// Print first item in the chain, return new separator.
386
  static StringRef prettyPrintFirstElement(StringRef FirstElement,
387
                                           bool MoreItemsExpected,
388
                                           int IndirectionLevel,
389
                                           llvm::raw_svector_ostream &os);
390
};
391
392
} // end of anonymous namespace
393
394
/// \return Whether the method declaration \p Parent
395
/// syntactically has a binary operation writing into the ivar \p Ivar.
396
static bool potentiallyWritesIntoIvar(const Decl *Parent,
397
9
                                      const ObjCIvarDecl *Ivar) {
398
9
  using namespace ast_matchers;
399
9
  const char *IvarBind = "Ivar";
400
9
  if (!Parent || !Parent->hasBody())
401
0
    return false;
402
9
  StatementMatcher WriteIntoIvarM = binaryOperator(
403
9
      hasOperatorName("="),
404
9
      hasLHS(ignoringParenImpCasts(
405
9
          objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
406
9
  StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
407
9
  auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
408
9
  for (BoundNodes &Match : Matches) {
409
2
    auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
410
2
    if (IvarRef->isFreeIvar())
411
1
      return true;
412
1
413
1
    const Expr *Base = IvarRef->getBase();
414
1
    if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
415
1
      Base = ICE->getSubExpr();
416
1
417
1
    if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
418
1
      if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
419
1
        if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
420
1
          return true;
421
0
422
0
    return false;
423
0
  }
424
9
  
return false7
;
425
9
}
426
427
/// Get parameters associated with runtime definition in order
428
/// to get the correct parameter name.
429
575
static ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
430
575
  // Use runtime definition, if available.
431
575
  RuntimeDefinition RD = Call->getRuntimeDefinition();
432
575
  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
433
526
    return FD->parameters();
434
49
  if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
435
46
    return MD->parameters();
436
3
437
3
  return Call->parameters();
438
3
}
439
440
/// \return whether \p Ty points to a const type, or is a const reference.
441
42
static bool isPointerToConst(QualType Ty) {
442
42
  return !Ty->getPointeeType().isNull() &&
443
42
         Ty->getPointeeType().getCanonicalType().isConstQualified();
444
42
}
445
446
/// Attempts to find the region of interest in a given CXX decl,
447
/// by either following the base classes or fields.
448
/// Dereferences fields up to a given recursion limit.
449
/// Note that \p Vec is passed by value, leading to quadratic copying cost,
450
/// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
451
/// \return A chain fields leading to the region of interest or None.
452
const Optional<NoStoreFuncVisitor::RegionVector>
453
NoStoreFuncVisitor::findRegionOfInterestInRecord(
454
    const RecordDecl *RD, ProgramStateRef State, const MemRegion *R,
455
    const NoStoreFuncVisitor::RegionVector &Vec /* = {} */,
456
63
    int depth /* = 0 */) {
457
63
458
63
  if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
459
5
    return None;
460
58
461
58
  if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
462
57
    if (!RDX->hasDefinition())
463
0
      return None;
464
58
465
58
  // Recursively examine the base classes.
466
58
  // Note that following base classes does not increase the recursion depth.
467
58
  if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
468
57
    for (const auto II : RDX->bases())
469
1
      if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
470
1
        if (Optional<RegionVector> Out =
471
1
                findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
472
1
          return Out;
473
58
474
60
  
for (const FieldDecl *I : RD->fields())57
{
475
60
    QualType FT = I->getType();
476
60
    const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
477
60
    const SVal V = State->getSVal(FR);
478
60
    const MemRegion *VR = V.getAsRegion();
479
60
480
60
    RegionVector VecF = Vec;
481
60
    VecF.push_back(FR);
482
60
483
60
    if (RegionOfInterest == VR)
484
10
      return VecF;
485
50
486
50
    if (const RecordDecl *RRD = FT->getAsRecordDecl())
487
13
      if (auto Out =
488
1
              findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
489
1
        return Out;
490
49
491
49
    QualType PT = FT->getPointeeType();
492
49
    if (PT.isNull() || 
PT->isVoidType()8
||
!VR8
)
493
41
      continue;
494
8
495
8
    if (const RecordDecl *RRD = PT->getAsRecordDecl())
496
4
      if (Optional<RegionVector> Out =
497
3
              findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
498
3
        return Out;
499
8
  }
500
57
501
57
  
return None43
;
502
57
}
503
504
std::shared_ptr<PathDiagnosticPiece>
505
NoStoreFuncVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BR,
506
65.0k
                              BugReport &R) {
507
65.0k
508
65.0k
  const LocationContext *Ctx = N->getLocationContext();
509
65.0k
  const StackFrameContext *SCtx = Ctx->getStackFrame();
510
65.0k
  ProgramStateRef State = N->getState();
511
65.0k
  auto CallExitLoc = N->getLocationAs<CallExitBegin>();
512
65.0k
513
65.0k
  // No diagnostic if region was modified inside the frame.
514
65.0k
  if (!CallExitLoc || 
isRegionOfInterestModifiedInFrame(N)862
)
515
64.3k
    return nullptr;
516
711
517
711
  CallEventRef<> Call =
518
711
      BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
519
711
520
711
  // Region of interest corresponds to an IVar, exiting a method
521
711
  // which could have written into that IVar, but did not.
522
711
  if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
523
48
    if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
524
10
      const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
525
10
      if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
526
10
          potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
527
9
                                    IvarR->getDecl()))
528
2
        return maybeEmitNote(R, *Call, N, {}, SelfRegion, "self",
529
2
                             /*FirstIsReferenceType=*/false, 1);
530
709
    }
531
48
  }
532
709
533
709
  if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
534
134
    const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
535
134
    if (RegionOfInterest->isSubRegionOf(ThisR) &&
536
134
        
!CCall->getDecl()->isImplicit()49
)
537
27
      return maybeEmitNote(R, *Call, N, {}, ThisR, "this",
538
27
                           /*FirstIsReferenceType=*/false, 1);
539
107
540
107
    // Do not generate diagnostics for not modified parameters in
541
107
    // constructors.
542
107
    return nullptr;
543
107
  }
544
575
545
575
  ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
546
979
  for (unsigned I = 0; I < Call->getNumArgs() && 
I < parameters.size()455
;
++I404
) {
547
454
    const ParmVarDecl *PVD = parameters[I];
548
454
    SVal V = Call->getArgSVal(I);
549
454
    bool ParamIsReferenceType = PVD->getType()->isReferenceType();
550
454
    std::string ParamName = PVD->getNameAsString();
551
454
552
454
    int IndirectionLevel = 1;
553
454
    QualType T = PVD->getType();
554
516
    while (const MemRegion *MR = V.getAsRegion()) {
555
188
      if (RegionOfInterest->isSubRegionOf(MR) && 
!isPointerToConst(T)42
)
556
40
        return maybeEmitNote(R, *Call, N, {}, MR, ParamName,
557
40
                             ParamIsReferenceType, IndirectionLevel);
558
148
559
148
      QualType PT = T->getPointeeType();
560
148
      if (PT.isNull() || PT->isVoidType())
561
76
        break;
562
72
563
72
      if (const RecordDecl *RD = PT->getAsRecordDecl())
564
45
        if (Optional<RegionVector> P =
565
10
                findRegionOfInterestInRecord(RD, State, MR))
566
10
          return maybeEmitNote(R, *Call, N, *P, RegionOfInterest, ParamName,
567
10
                               ParamIsReferenceType, IndirectionLevel);
568
62
569
62
      V = State->getSVal(MR, PT);
570
62
      T = PT;
571
62
      IndirectionLevel++;
572
62
    }
573
454
  }
574
575
575
575
  
return nullptr525
;
576
575
}
577
578
697
void NoStoreFuncVisitor::findModifyingFrames(const ExplodedNode *N) {
579
697
  assert(N->getLocationAs<CallExitBegin>());
580
697
  ProgramStateRef LastReturnState = N->getState();
581
697
  SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
582
697
  const LocationContext *Ctx = N->getLocationContext();
583
697
  const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
584
697
585
15.7k
  do {
586
15.7k
    ProgramStateRef State = N->getState();
587
15.7k
    auto CallExitLoc = N->getLocationAs<CallExitBegin>();
588
15.7k
    if (CallExitLoc) {
589
846
      LastReturnState = State;
590
846
      ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
591
846
    }
592
15.7k
593
15.7k
    FramesModifyingCalculated.insert(N->getLocationContext()->getStackFrame());
594
15.7k
595
15.7k
    if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
596
1.30k
      const StackFrameContext *SCtx = N->getStackFrame();
597
1.47k
      while (!SCtx->inTopFrame()) {
598
1.33k
        auto p = FramesModifyingRegion.insert(SCtx);
599
1.33k
        if (!p.second)
600
1.16k
          break; // Frame and all its parents already inserted.
601
170
        SCtx = SCtx->getParent()->getStackFrame();
602
170
      }
603
1.30k
    }
604
15.7k
605
15.7k
    // Stop calculation at the call to the current function.
606
15.7k
    if (auto CE = N->getLocationAs<CallEnter>())
607
846
      if (CE->getCalleeContext() == OriginalSCtx)
608
697
        break;
609
15.0k
610
15.0k
    N = N->getFirstPred();
611
15.0k
  } while (N);
612
697
}
613
614
std::shared_ptr<PathDiagnosticPiece> NoStoreFuncVisitor::maybeEmitNote(
615
    BugReport &R, const CallEvent &Call, const ExplodedNode *N,
616
    const RegionVector &FieldChain, const MemRegion *MatchedRegion,
617
    StringRef FirstElement, bool FirstIsReferenceType,
618
79
    unsigned IndirectionLevel) {
619
79
  // Optimistically suppress uninitialized value bugs that result
620
79
  // from system headers having a chance to initialize the value
621
79
  // but failing to do so. It's too unlikely a system header's fault.
622
79
  // It's much more likely a situation in which the function has a failure
623
79
  // mode that the user decided not to check. If we want to hunt such
624
79
  // omitted checks, we should provide an explicit function-specific note
625
79
  // describing the precondition under which the function isn't supposed to
626
79
  // initialize its out-parameter, and additionally check that such
627
79
  // precondition can actually be fulfilled on the current path.
628
79
  if (Call.isInSystemHeader()) {
629
3
    // We make an exception for system header functions that have no branches.
630
3
    // Such functions unconditionally fail to initialize the variable.
631
3
    // If they call other functions that have more paths within them,
632
3
    // this suppression would still apply when we visit these inner functions.
633
3
    // One common example of a standard function that doesn't ever initialize
634
3
    // its out parameter is operator placement new; it's up to the follow-up
635
3
    // constructor (if any) to initialize the memory.
636
3
    if (!N->getStackFrame()->getCFG()->isLinear())
637
1
      R.markInvalid(getTag(), nullptr);
638
3
    return nullptr;
639
3
  }
640
76
641
76
  PathDiagnosticLocation L =
642
76
      PathDiagnosticLocation::create(N->getLocation(), SM);
643
76
644
76
  // For now this shouldn't trigger, but once it does (as we add more
645
76
  // functions to the body farm), we'll need to decide if these reports
646
76
  // are worth suppressing as well.
647
76
  if (!L.hasValidLocation())
648
0
    return nullptr;
649
76
650
76
  SmallString<256> sbuf;
651
76
  llvm::raw_svector_ostream os(sbuf);
652
76
  os << "Returning without writing to '";
653
76
654
76
  // Do not generate the note if failed to pretty-print.
655
76
  if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType, MatchedRegion,
656
76
                             FieldChain, IndirectionLevel, os))
657
1
    return nullptr;
658
75
659
75
  os << "'";
660
75
  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
661
75
}
662
663
bool NoStoreFuncVisitor::prettyPrintRegionName(StringRef FirstElement,
664
                                               bool FirstIsReferenceType,
665
                                               const MemRegion *MatchedRegion,
666
                                               const RegionVector &FieldChain,
667
                                               int IndirectionLevel,
668
76
                                               llvm::raw_svector_ostream &os) {
669
76
670
76
  if (FirstIsReferenceType)
671
21
    IndirectionLevel--;
672
76
673
76
  RegionVector RegionSequence;
674
76
675
76
  // Add the regions in the reverse order, then reverse the resulting array.
676
76
  assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
677
76
  const MemRegion *R = RegionOfInterest;
678
135
  while (R != MatchedRegion) {
679
59
    RegionSequence.push_back(R);
680
59
    R = cast<SubRegion>(R)->getSuperRegion();
681
59
  }
682
76
  std::reverse(RegionSequence.begin(), RegionSequence.end());
683
76
  RegionSequence.append(FieldChain.begin(), FieldChain.end());
684
76
685
76
  StringRef Sep;
686
76
  for (const MemRegion *R : RegionSequence) {
687
72
688
72
    // Just keep going up to the base region.
689
72
    // Element regions may appear due to casts.
690
72
    if (isa<CXXBaseObjectRegion>(R) || 
isa<CXXTempObjectRegion>(R)67
)
691
5
      continue;
692
67
693
67
    if (Sep.empty())
694
58
      Sep = prettyPrintFirstElement(FirstElement,
695
58
                                    /*MoreItemsExpected=*/true,
696
58
                                    IndirectionLevel, os);
697
67
698
67
    os << Sep;
699
67
700
67
    // Can only reasonably pretty-print DeclRegions.
701
67
    if (!isa<DeclRegion>(R))
702
1
      return false;
703
66
704
66
    const auto *DR = cast<DeclRegion>(R);
705
66
    Sep = DR->getValueType()->isAnyPointerType() ? 
"->"9
:
"."57
;
706
66
    DR->getDecl()->getDeclName().print(os, PP);
707
66
  }
708
76
709
76
  
if (75
Sep.empty()75
)
710
18
    prettyPrintFirstElement(FirstElement,
711
18
                            /*MoreItemsExpected=*/false, IndirectionLevel, os);
712
75
  return true;
713
76
}
714
715
StringRef NoStoreFuncVisitor::prettyPrintFirstElement(
716
    StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel,
717
76
    llvm::raw_svector_ostream &os) {
718
76
  StringRef Out = ".";
719
76
720
76
  if (IndirectionLevel > 0 && 
MoreItemsExpected56
) {
721
41
    IndirectionLevel--;
722
41
    Out = "->";
723
41
  }
724
76
725
76
  if (IndirectionLevel > 0 && 
MoreItemsExpected16
)
726
1
    os << "(";
727
76
728
93
  for (int i = 0; i < IndirectionLevel; 
i++17
)
729
17
    os << "*";
730
76
  os << FirstElement;
731
76
732
76
  if (IndirectionLevel > 0 && 
MoreItemsExpected16
)
733
1
    os << ")";
734
76
735
76
  return Out;
736
76
}
737
738
//===----------------------------------------------------------------------===//
739
// Implementation of MacroNullReturnSuppressionVisitor.
740
//===----------------------------------------------------------------------===//
741
742
namespace {
743
744
/// Suppress null-pointer-dereference bugs where dereferenced null was returned
745
/// the macro.
746
class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
747
  const SubRegion *RegionOfInterest;
748
  const SVal ValueAtDereference;
749
750
  // Do not invalidate the reports where the value was modified
751
  // after it got assigned to from the macro.
752
  bool WasModified = false;
753
754
public:
755
  MacroNullReturnSuppressionVisitor(const SubRegion *R,
756
                                    const SVal V) : RegionOfInterest(R),
757
914
                                                    ValueAtDereference(V) {}
758
759
  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
760
                                                 BugReporterContext &BRC,
761
32.8k
                                                 BugReport &BR) override {
762
32.8k
    if (WasModified)
763
21.3k
      return nullptr;
764
11.4k
765
11.4k
    auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
766
11.4k
    if (!BugPoint)
767
152
      return nullptr;
768
11.3k
769
11.3k
    const SourceManager &SMgr = BRC.getSourceManager();
770
11.3k
    if (auto Loc = matchAssignment(N)) {
771
717
      if (isFunctionMacroExpansion(*Loc, SMgr)) {
772
8
        std::string MacroName = getMacroName(*Loc, BRC);
773
8
        SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
774
8
        if (!BugLoc.isMacroID() || 
getMacroName(BugLoc, BRC) != MacroName3
)
775
5
          BR.markInvalid(getTag(), MacroName.c_str());
776
8
      }
777
717
    }
778
11.3k
779
11.3k
    if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
780
675
      WasModified = true;
781
11.3k
782
11.3k
    return nullptr;
783
11.3k
  }
784
785
  static void addMacroVisitorIfNecessary(
786
        const ExplodedNode *N, const MemRegion *R,
787
        bool EnableNullFPSuppression, BugReport &BR,
788
1.49k
        const SVal V) {
789
1.49k
    AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
790
1.49k
    if (EnableNullFPSuppression &&
791
1.49k
        
Options.ShouldSuppressNullReturnPaths1.35k
&&
V.getAs<Loc>()1.24k
)
792
914
      BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
793
914
              R->getAs<SubRegion>(), V));
794
1.49k
  }
795
796
919
  void* getTag() const {
797
919
    static int Tag = 0;
798
919
    return static_cast<void *>(&Tag);
799
919
  }
800
801
914
  void Profile(llvm::FoldingSetNodeID &ID) const override {
802
914
    ID.AddPointer(getTag());
803
914
  }
804
805
private:
806
  /// \return Source location of right hand side of an assignment
807
  /// into \c RegionOfInterest, empty optional if none found.
808
11.3k
  Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
809
11.3k
    const Stmt *S = PathDiagnosticLocation::getStmt(N);
810
11.3k
    ProgramStateRef State = N->getState();
811
11.3k
    auto *LCtx = N->getLocationContext();
812
11.3k
    if (!S)
813
870
      return None;
814
10.4k
815
10.4k
    if (const auto *DS = dyn_cast<DeclStmt>(S)) {
816
916
      if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
817
916
        if (const Expr *RHS = VD->getInit())
818
890
          if (RegionOfInterest->isSubRegionOf(
819
890
                  State->getLValue(VD, LCtx).getAsRegion()))
820
646
            return RHS->getBeginLoc();
821
9.51k
    } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
822
833
      const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
823
833
      const Expr *RHS = BO->getRHS();
824
833
      if (BO->isAssignmentOp() && 
RegionOfInterest->isSubRegionOf(R)615
) {
825
71
        return RHS->getBeginLoc();
826
71
      }
827
9.71k
    }
828
9.71k
    return None;
829
9.71k
  }
830
};
831
832
} // end of anonymous namespace
833
834
namespace {
835
836
/// Emits an extra note at the return statement of an interesting stack frame.
837
///
838
/// The returned value is marked as an interesting value, and if it's null,
839
/// adds a visitor to track where it became null.
840
///
841
/// This visitor is intended to be used when another visitor discovers that an
842
/// interesting value comes from an inlined function call.
843
class ReturnVisitor : public BugReporterVisitor {
844
  const StackFrameContext *StackFrame;
845
  enum {
846
    Initial,
847
    MaybeUnsuppress,
848
    Satisfied
849
  } Mode = Initial;
850
851
  bool EnableNullFPSuppression;
852
  bool ShouldInvalidate = true;
853
  AnalyzerOptions& Options;
854
855
public:
856
  ReturnVisitor(const StackFrameContext *Frame,
857
                bool Suppressed,
858
                AnalyzerOptions &Options)
859
      : StackFrame(Frame), EnableNullFPSuppression(Suppressed),
860
410
        Options(Options) {}
861
862
575
  static void *getTag() {
863
575
    static int Tag = 0;
864
575
    return static_cast<void *>(&Tag);
865
575
  }
866
867
410
  void Profile(llvm::FoldingSetNodeID &ID) const override {
868
410
    ID.AddPointer(ReturnVisitor::getTag());
869
410
    ID.AddPointer(StackFrame);
870
410
    ID.AddBoolean(EnableNullFPSuppression);
871
410
  }
872
873
  /// Adds a ReturnVisitor if the given statement represents a call that was
874
  /// inlined.
875
  ///
876
  /// This will search back through the ExplodedGraph, starting from the given
877
  /// node, looking for when the given statement was processed. If it turns out
878
  /// the statement is a call that was inlined, we add the visitor to the
879
  /// bug report, so it can print a note later.
880
  static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
881
                                    BugReport &BR,
882
2.60k
                                    bool InEnableNullFPSuppression) {
883
2.60k
    if (!CallEvent::isCallStmt(S))
884
2.08k
      return;
885
519
886
519
    // First, find when we processed the statement.
887
519
    // If we work with a 'CXXNewExpr' that is going to be purged away before
888
519
    // its call take place. We would catch that purge in the last condition
889
519
    // as a 'StmtPoint' so we have to bypass it.
890
519
    const bool BypassCXXNewExprEval = isa<CXXNewExpr>(S);
891
519
892
519
    // This is moving forward when we enter into another context.
893
519
    const StackFrameContext *CurrentSFC = Node->getStackFrame();
894
519
895
1.34k
    do {
896
1.34k
      // If that is satisfied we found our statement as an inlined call.
897
1.34k
      if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
898
418
        if (CEE->getCalleeContext()->getCallSite() == S)
899
410
          break;
900
931
901
931
      // Try to move forward to the end of the call-chain.
902
931
      Node = Node->getFirstPred();
903
931
      if (!Node)
904
0
        break;
905
931
906
931
      const StackFrameContext *PredSFC = Node->getStackFrame();
907
931
908
931
      // If that is satisfied we found our statement.
909
931
      // FIXME: This code currently bypasses the call site for the
910
931
      //        conservatively evaluated allocator.
911
931
      if (!BypassCXXNewExprEval)
912
764
        if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
913
621
          // See if we do not enter into another context.
914
621
          if (SP->getStmt() == S && 
CurrentSFC == PredSFC109
)
915
109
            break;
916
822
917
822
      CurrentSFC = PredSFC;
918
822
    } while (Node->getStackFrame() == CurrentSFC);
919
519
920
519
    // Next, step over any post-statement checks.
921
582
    while (Node && Node->getLocation().getAs<PostStmt>())
922
63
      Node = Node->getFirstPred();
923
519
    if (!Node)
924
0
      return;
925
519
926
519
    // Finally, see if we inlined the call.
927
519
    Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
928
519
    if (!CEE)
929
109
      return;
930
410
931
410
    const StackFrameContext *CalleeContext = CEE->getCalleeContext();
932
410
    if (CalleeContext->getCallSite() != S)
933
0
      return;
934
410
935
410
    // Check the return value.
936
410
    ProgramStateRef State = Node->getState();
937
410
    SVal RetVal = Node->getSVal(S);
938
410
939
410
    // Handle cases where a reference is returned and then immediately used.
940
410
    if (cast<Expr>(S)->isGLValue())
941
18
      if (Optional<Loc> LValue = RetVal.getAs<Loc>())
942
18
        RetVal = State->getSVal(*LValue);
943
410
944
410
    // See if the return value is NULL. If so, suppress the report.
945
410
    AnalyzerOptions &Options = State->getAnalysisManager().options;
946
410
947
410
    bool EnableNullFPSuppression = false;
948
410
    if (InEnableNullFPSuppression &&
949
410
        
Options.ShouldSuppressNullReturnPaths342
)
950
237
      if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
951
176
        EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
952
410
953
410
    BR.markInteresting(CalleeContext);
954
410
    BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
955
410
                                                   EnableNullFPSuppression,
956
410
                                                   Options));
957
410
  }
958
959
  std::shared_ptr<PathDiagnosticPiece>
960
  visitNodeInitial(const ExplodedNode *N,
961
2.80k
                   BugReporterContext &BRC, BugReport &BR) {
962
2.80k
    // Only print a message at the interesting return statement.
963
2.80k
    if (N->getLocationContext() != StackFrame)
964
1.97k
      return nullptr;
965
832
966
832
    Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
967
832
    if (!SP)
968
8
      return nullptr;
969
824
970
824
    const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
971
824
    if (!Ret)
972
406
      return nullptr;
973
418
974
418
    // Okay, we're at the right return statement, but do we have the return
975
418
    // value available?
976
418
    ProgramStateRef State = N->getState();
977
418
    SVal V = State->getSVal(Ret, StackFrame);
978
418
    if (V.isUnknownOrUndef())
979
10
      return nullptr;
980
408
981
408
    // Don't print any more notes after this one.
982
408
    Mode = Satisfied;
983
408
984
408
    const Expr *RetE = Ret->getRetValue();
985
408
    assert(RetE && "Tracking a return value for a void function");
986
408
987
408
    // Handle cases where a reference is returned and then immediately used.
988
408
    Optional<Loc> LValue;
989
408
    if (RetE->isGLValue()) {
990
18
      if ((LValue = V.getAs<Loc>())) {
991
18
        SVal RValue = State->getRawSVal(*LValue, RetE->getType());
992
18
        if (RValue.getAs<DefinedSVal>())
993
16
          V = RValue;
994
18
      }
995
18
    }
996
408
997
408
    // Ignore aggregate rvalues.
998
408
    if (V.getAs<nonloc::LazyCompoundVal>() ||
999
408
        
V.getAs<nonloc::CompoundVal>()406
)
1000
2
      return nullptr;
1001
406
1002
406
    RetE = RetE->IgnoreParenCasts();
1003
406
1004
406
    // If we're returning 0, we should track where that 0 came from.
1005
406
    bugreporter::trackExpressionValue(N, RetE, BR, EnableNullFPSuppression);
1006
406
1007
406
    // Build an appropriate message based on the return value.
1008
406
    SmallString<64> Msg;
1009
406
    llvm::raw_svector_ostream Out(Msg);
1010
406
1011
406
    if (State->isNull(V).isConstrainedTrue()) {
1012
387
      if (V.getAs<Loc>()) {
1013
324
1014
324
        // If we have counter-suppression enabled, make sure we keep visiting
1015
324
        // future nodes. We want to emit a path note as well, in case
1016
324
        // the report is resurrected as valid later on.
1017
324
        if (EnableNullFPSuppression &&
1018
324
            
Options.ShouldAvoidSuppressingNullArgumentPaths174
)
1019
52
          Mode = MaybeUnsuppress;
1020
324
1021
324
        if (RetE->getType()->isObjCObjectPointerType()) {
1022
0
          Out << "Returning nil";
1023
324
        } else {
1024
324
          Out << "Returning null pointer";
1025
324
        }
1026
324
      } else {
1027
63
        Out << "Returning zero";
1028
63
      }
1029
387
1030
387
    } else {
1031
19
      if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1032
6
        Out << "Returning the value " << CI->getValue();
1033
13
      } else if (V.getAs<Loc>()) {
1034
5
        Out << "Returning pointer";
1035
8
      } else {
1036
8
        Out << "Returning value";
1037
8
      }
1038
19
    }
1039
406
1040
406
    if (LValue) {
1041
18
      if (const MemRegion *MR = LValue->getAsRegion()) {
1042
18
        if (MR->canPrintPretty()) {
1043
12
          Out << " (reference to ";
1044
12
          MR->printPretty(Out);
1045
12
          Out << ")";
1046
12
        }
1047
18
      }
1048
388
    } else {
1049
388
      // FIXME: We should have a more generalized location printing mechanism.
1050
388
      if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
1051
39
        if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
1052
39
          Out << " (loaded from '" << *DD << "')";
1053
388
    }
1054
406
1055
406
    PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
1056
406
    if (!L.isValid() || !L.asLocation().isValid())
1057
4
      return nullptr;
1058
402
1059
402
    return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1060
402
  }
1061
1062
  std::shared_ptr<PathDiagnosticPiece>
1063
  visitNodeMaybeUnsuppress(const ExplodedNode *N,
1064
825
                           BugReporterContext &BRC, BugReport &BR) {
1065
#ifndef NDEBUG
1066
    assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
1067
#endif
1068
1069
825
    // Are we at the entry node for this call?
1070
825
    Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
1071
825
    if (!CE)
1072
771
      return nullptr;
1073
54
1074
54
    if (CE->getCalleeContext() != StackFrame)
1075
2
      return nullptr;
1076
52
1077
52
    Mode = Satisfied;
1078
52
1079
52
    // Don't automatically suppress a report if one of the arguments is
1080
52
    // known to be a null pointer. Instead, start tracking /that/ null
1081
52
    // value back to its origin.
1082
52
    ProgramStateManager &StateMgr = BRC.getStateManager();
1083
52
    CallEventManager &CallMgr = StateMgr.getCallEventManager();
1084
52
1085
52
    ProgramStateRef State = N->getState();
1086
52
    CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
1087
76
    for (unsigned I = 0, E = Call->getNumArgs(); I != E; 
++I24
) {
1088
24
      Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
1089
24
      if (!ArgV)
1090
4
        continue;
1091
20
1092
20
      const Expr *ArgE = Call->getArgExpr(I);
1093
20
      if (!ArgE)
1094
0
        continue;
1095
20
1096
20
      // Is it possible for this argument to be non-null?
1097
20
      if (!State->isNull(*ArgV).isConstrainedTrue())
1098
12
        continue;
1099
8
1100
8
      if (bugreporter::trackExpressionValue(N, ArgE, BR, EnableNullFPSuppression))
1101
8
        ShouldInvalidate = false;
1102
8
1103
8
      // If we /can't/ track the null pointer, we should err on the side of
1104
8
      // false negatives, and continue towards marking this report invalid.
1105
8
      // (We will still look at the other arguments, though.)
1106
8
    }
1107
52
1108
52
    return nullptr;
1109
52
  }
1110
1111
  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1112
                                                 BugReporterContext &BRC,
1113
35.5k
                                                 BugReport &BR) override {
1114
35.5k
    switch (Mode) {
1115
35.5k
    case Initial:
1116
2.80k
      return visitNodeInitial(N, BRC, BR);
1117
35.5k
    case MaybeUnsuppress:
1118
825
      return visitNodeMaybeUnsuppress(N, BRC, BR);
1119
35.5k
    case Satisfied:
1120
31.9k
      return nullptr;
1121
0
    }
1122
0
1123
0
    llvm_unreachable("Invalid visit mode!");
1124
0
  }
1125
1126
  void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
1127
409
                       BugReport &BR) override {
1128
409
    if (EnableNullFPSuppression && 
ShouldInvalidate173
)
1129
165
      BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
1130
409
  }
1131
};
1132
1133
} // end of anonymous namespace
1134
1135
//===----------------------------------------------------------------------===//
1136
// Implementation of FindLastStoreBRVisitor.
1137
//===----------------------------------------------------------------------===//
1138
1139
1.58k
void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1140
1.58k
  static int tag = 0;
1141
1.58k
  ID.AddPointer(&tag);
1142
1.58k
  ID.AddPointer(R);
1143
1.58k
  ID.Add(V);
1144
1.58k
  ID.AddBoolean(EnableNullFPSuppression);
1145
1.58k
}
1146
1147
/// Returns true if \p N represents the DeclStmt declaring and initializing
1148
/// \p VR.
1149
24.7k
static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
1150
24.7k
  Optional<PostStmt> P = N->getLocationAs<PostStmt>();
1151
24.7k
  if (!P)
1152
7.09k
    return false;
1153
17.6k
1154
17.6k
  const DeclStmt *DS = P->getStmtAs<DeclStmt>();
1155
17.6k
  if (!DS)
1156
16.5k
    return false;
1157
1.16k
1158
1.16k
  if (DS->getSingleDecl() != VR->getDecl())
1159
390
    return false;
1160
772
1161
772
  const MemSpaceRegion *VarSpace = VR->getMemorySpace();
1162
772
  const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
1163
772
  if (!FrameSpace) {
1164
4
    // If we ever directly evaluate global DeclStmts, this assertion will be
1165
4
    // invalid, but this still seems preferable to silently accepting an
1166
4
    // initialization that may be for a path-sensitive variable.
1167
4
    assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
1168
4
    return true;
1169
4
  }
1170
768
1171
768
  assert(VR->getDecl()->hasLocalStorage());
1172
768
  const LocationContext *LCtx = N->getLocationContext();
1173
768
  return FrameSpace->getStackFrame() == LCtx->getStackFrame();
1174
768
}
1175
1176
/// Show diagnostics for initializing or declaring a region \p R with a bad value.
1177
static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
1178
773
                              const MemRegion *R, SVal V, const DeclStmt *DS) {
1179
773
  if (R->canPrintPretty()) {
1180
772
    R->printPretty(os);
1181
772
    os << " ";
1182
772
  }
1183
773
1184
773
  if (V.getAs<loc::ConcreteInt>()) {
1185
505
    bool b = false;
1186
505
    if (R->isBoundable()) {
1187
505
      if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1188
505
        if (TR->getValueType()->isObjCObjectPointerType()) {
1189
70
          os << action << "nil";
1190
70
          b = true;
1191
70
        }
1192
505
      }
1193
505
    }
1194
505
    if (!b)
1195
435
      os << action << "a null pointer value";
1196
505
1197
505
  } else 
if (auto 268
CVal268
= V.getAs<nonloc::ConcreteInt>()) {
1198
61
    os << action << CVal->getValue();
1199
207
  } else if (DS) {
1200
207
    if (V.isUndef()) {
1201
142
      if (isa<VarRegion>(R)) {
1202
142
        const auto *VD = cast<VarDecl>(DS->getSingleDecl());
1203
142
        if (VD->getInit()) {
1204
0
          os << (R->canPrintPretty() ? "initialized" : "Initializing")
1205
0
            << " to a garbage value";
1206
142
        } else {
1207
142
          os << (R->canPrintPretty() ? "declared" : 
"Declaring"0
)
1208
142
            << " without an initial value";
1209
142
        }
1210
142
      }
1211
142
    } else {
1212
65
      os << (R->canPrintPretty() ? "initialized" : 
"Initialized"0
)
1213
65
        << " here";
1214
65
    }
1215
207
  }
1216
773
}
1217
1218
/// Display diagnostics for passing bad region as a parameter.
1219
static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
1220
    const VarRegion *VR,
1221
107
    SVal V) {
1222
107
  const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1223
107
1224
107
  os << "Passing ";
1225
107
1226
107
  if (V.getAs<loc::ConcreteInt>()) {
1227
77
    if (Param->getType()->isObjCObjectPointerType())
1228
5
      os << "nil object reference";
1229
72
    else
1230
72
      os << "null pointer value";
1231
77
  } else 
if (30
V.isUndef()30
) {
1232
0
    os << "uninitialized value";
1233
30
  } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1234
14
    os << "the value " << CI->getValue();
1235
16
  } else {
1236
16
    os << "value";
1237
16
  }
1238
107
1239
107
  // Printed parameter indexes are 1-based, not 0-based.
1240
107
  unsigned Idx = Param->getFunctionScopeIndex() + 1;
1241
107
  os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1242
107
  if (VR->canPrintPretty()) {
1243
107
    os << " ";
1244
107
    VR->printPretty(os);
1245
107
  }
1246
107
}
1247
1248
/// Show default diagnostics for storing bad region.
1249
static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
1250
    const MemRegion *R,
1251
310
    SVal V) {
1252
310
  if (V.getAs<loc::ConcreteInt>()) {
1253
217
    bool b = false;
1254
217
    if (R->isBoundable()) {
1255
217
      if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1256
202
        if (TR->getValueType()->isObjCObjectPointerType()) {
1257
21
          os << "nil object reference stored";
1258
21
          b = true;
1259
21
        }
1260
202
      }
1261
217
    }
1262
217
    if (!b) {
1263
196
      if (R->canPrintPretty())
1264
175
        os << "Null pointer value stored";
1265
21
      else
1266
21
        os << "Storing null pointer value";
1267
196
    }
1268
217
1269
217
  } else 
if (93
V.isUndef()93
) {
1270
8
    if (R->canPrintPretty())
1271
4
      os << "Uninitialized value stored";
1272
4
    else
1273
4
      os << "Storing uninitialized value";
1274
8
1275
85
  } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1276
46
    if (R->canPrintPretty())
1277
40
      os << "The value " << CV->getValue() << " is assigned";
1278
6
    else
1279
6
      os << "Assigning " << CV->getValue();
1280
46
1281
46
  } else {
1282
39
    if (R->canPrintPretty())
1283
39
      os << "Value assigned";
1284
0
    else
1285
0
      os << "Assigning value";
1286
39
  }
1287
310
1288
310
  if (R->canPrintPretty()) {
1289
279
    os << " to ";
1290
279
    R->printPretty(os);
1291
279
  }
1292
310
}
1293
1294
std::shared_ptr<PathDiagnosticPiece>
1295
FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1296
69.1k
                                  BugReporterContext &BRC, BugReport &BR) {
1297
69.1k
  if (Satisfied)
1298
38.0k
    return nullptr;
1299
31.1k
1300
31.1k
  const ExplodedNode *StoreSite = nullptr;
1301
31.1k
  const ExplodedNode *Pred = Succ->getFirstPred();
1302
31.1k
  const Expr *InitE = nullptr;
1303
31.1k
  bool IsParam = false;
1304
31.1k
1305
31.1k
  // First see if we reached the declaration of the region.
1306
31.1k
  if (const auto *VR = dyn_cast<VarRegion>(R)) {
1307
24.7k
    if (isInitializationOfVar(Pred, VR)) {
1308
766
      StoreSite = Pred;
1309
766
      InitE = VR->getDecl()->getInit();
1310
766
    }
1311
24.7k
  }
1312
31.1k
1313
31.1k
  // If this is a post initializer expression, initializing the region, we
1314
31.1k
  // should track the initializer expression.
1315
31.1k
  if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1316
74
    const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1317
74
    if (FieldReg && 
FieldReg == R50
) {
1318
6
      StoreSite = Pred;
1319
6
      InitE = PIP->getInitializer()->getInit();
1320
6
    }
1321
74
  }
1322
31.1k
1323
31.1k
  // Otherwise, see if this is the store site:
1324
31.1k
  // (1) Succ has this binding and Pred does not, i.e. this is
1325
31.1k
  //     where the binding first occurred.
1326
31.1k
  // (2) Succ has this binding and is a PostStore node for this region, i.e.
1327
31.1k
  //     the same binding was re-assigned here.
1328
31.1k
  if (!StoreSite) {
1329
30.3k
    if (Succ->getState()->getSVal(R) != V)
1330
1.59k
      return nullptr;
1331
28.7k
1332
28.7k
    if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
1333
28.3k
      Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1334
28.3k
      if (!PS || 
PS->getLocationValue() != R499
)
1335
28.3k
        return nullptr;
1336
418
    }
1337
418
1338
418
    StoreSite = Succ;
1339
418
1340
418
    // If this is an assignment expression, we can track the value
1341
418
    // being assigned.
1342
418
    if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1343
305
      if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1344
267
        if (BO->isAssignmentOp())
1345
267
          InitE = BO->getRHS();
1346
418
1347
418
    // If this is a call entry, the variable should be a parameter.
1348
418
    // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1349
418
    // 'this' should never be NULL, but this visitor isn't just for NULL and
1350
418
    // UndefinedVal.)
1351
418
    if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1352
107
      if (const auto *VR = dyn_cast<VarRegion>(R)) {
1353
107
1354
107
        const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1355
107
1356
107
        ProgramStateManager &StateMgr = BRC.getStateManager();
1357
107
        CallEventManager &CallMgr = StateMgr.getCallEventManager();
1358
107
1359
107
        CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1360
107
                                                Succ->getState());
1361
107
        InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1362
107
        IsParam = true;
1363
107
      }
1364
107
    }
1365
418
1366
418
    // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1367
418
    // is wrapped inside of it.
1368
418
    if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1369
6
      InitE = TmpR->getExpr();
1370
418
  }
1371
31.1k
1372
31.1k
  
if (1.19k
!StoreSite1.19k
)
1373
0
    return nullptr;
1374
1.19k
  Satisfied = true;
1375
1.19k
1376
1.19k
  // If we have an expression that provided the value, try to track where it
1377
1.19k
  // came from.
1378
1.19k
  if (InitE) {
1379
999
    if (V.isUndef() ||
1380
999
        
V.getAs<loc::ConcreteInt>()996
||
V.getAs<nonloc::ConcreteInt>()211
) {
1381
902
      if (!IsParam)
1382
811
        InitE = InitE->IgnoreParenCasts();
1383
902
      bugreporter::trackExpressionValue(StoreSite, InitE, BR,
1384
902
                                   EnableNullFPSuppression);
1385
902
    }
1386
999
    ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
1387
999
                                         BR, EnableNullFPSuppression);
1388
999
  }
1389
1.19k
1390
1.19k
  // Okay, we've found the binding. Emit an appropriate message.
1391
1.19k
  SmallString<256> sbuf;
1392
1.19k
  llvm::raw_svector_ostream os(sbuf);
1393
1.19k
1394
1.19k
  if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1395
1.07k
    const Stmt *S = PS->getStmt();
1396
1.07k
    const char *action = nullptr;
1397
1.07k
    const auto *DS = dyn_cast<DeclStmt>(S);
1398
1.07k
    const auto *VR = dyn_cast<VarRegion>(R);
1399
1.07k
1400
1.07k
    if (DS) {
1401
769
      action = R->canPrintPretty() ? 
"initialized to "768
:
1402
769
                                     
"Initializing to "1
;
1403
769
    } else 
if (302
isa<BlockExpr>(S)302
) {
1404
4
      action = R->canPrintPretty() ? "captured by block as " :
1405
4
                                     
"Captured by block as "0
;
1406
4
      if (VR) {
1407
4
        // See if we can get the BlockVarRegion.
1408
4
        ProgramStateRef State = StoreSite->getState();
1409
4
        SVal V = StoreSite->getSVal(S);
1410
4
        if (const auto *BDR =
1411
4
              dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1412
4
          if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1413
4
            if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
1414
4
              BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1415
4
                  *KV, OriginalR, EnableNullFPSuppression));
1416
4
          }
1417
4
        }
1418
4
      }
1419
4
    }
1420
1.07k
    if (action)
1421
773
      showBRDiagnostics(action, os, R, V, DS);
1422
1.07k
1423
1.07k
  } else 
if (119
StoreSite->getLocation().getAs<CallEnter>()119
) {
1424
107
    if (const auto *VR = dyn_cast<VarRegion>(R))
1425
107
      showBRParamDiagnostics(os, VR, V);
1426
107
  }
1427
1.19k
1428
1.19k
  if (os.str().empty())
1429
310
    showBRDefaultDiagnostics(os, R, V);
1430
1.19k
1431
1.19k
  // Construct a new PathDiagnosticPiece.
1432
1.19k
  ProgramPoint P = StoreSite->getLocation();
1433
1.19k
  PathDiagnosticLocation L;
1434
1.19k
  if (P.getAs<CallEnter>() && 
InitE107
)
1435
107
    L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1436
107
                               P.getLocationContext());
1437
1.19k
1438
1.19k
  if (!L.isValid() || 
!L.asLocation().isValid()107
)
1439
1.08k
    L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1440
1.19k
1441
1.19k
  if (!L.isValid() || !L.asLocation().isValid())
1442
1
    return nullptr;
1443
1.18k
1444
1.18k
  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1445
1.18k
}
1446
1447
//===----------------------------------------------------------------------===//
1448
// Implementation of TrackConstraintBRVisitor.
1449
//===----------------------------------------------------------------------===//
1450
1451
281
void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1452
281
  static int tag = 0;
1453
281
  ID.AddPointer(&tag);
1454
281
  ID.AddBoolean(Assumption);
1455
281
  ID.Add(Constraint);
1456
281
}
1457
1458
/// Return the tag associated with this visitor.  This tag will be used
1459
/// to make all PathDiagnosticPieces created by this visitor.
1460
1.17k
const char *TrackConstraintBRVisitor::getTag() {
1461
1.17k
  return "TrackConstraintBRVisitor";
1462
1.17k
}
1463
1464
5.75k
bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1465
5.75k
  if (IsZeroCheck)
1466
5.72k
    return N->getState()->isNull(Constraint).isUnderconstrained();
1467
22
  return (bool)N->getState()->assume(Constraint, !Assumption);
1468
22
}
1469
1470
std::shared_ptr<PathDiagnosticPiece>
1471
TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
1472
7.94k
                                    BugReporterContext &BRC, BugReport &) {
1473
7.94k
  const ExplodedNode *PrevN = N->getFirstPred();
1474
7.94k
  if (IsSatisfied)
1475
2.47k
    return nullptr;
1476
5.47k
1477
5.47k
  // Start tracking after we see the first state in which the value is
1478
5.47k
  // constrained.
1479
5.47k
  if (!IsTrackingTurnedOn)
1480
643
    if (!isUnderconstrained(N))
1481
276
      IsTrackingTurnedOn = true;
1482
5.47k
  if (!IsTrackingTurnedOn)
1483
367
    return nullptr;
1484
5.10k
1485
5.10k
  // Check if in the previous state it was feasible for this constraint
1486
5.10k
  // to *not* be true.
1487
5.10k
  if (isUnderconstrained(PrevN)) {
1488
276
    IsSatisfied = true;
1489
276
1490
276
    // As a sanity check, make sure that the negation of the constraint
1491
276
    // was infeasible in the current state.  If it is feasible, we somehow
1492
276
    // missed the transition point.
1493
276
    assert(!isUnderconstrained(N));
1494
276
1495
276
    // We found the transition point for the constraint.  We now need to
1496
276
    // pretty-print the constraint. (work-in-progress)
1497
276
    SmallString<64> sbuf;
1498
276
    llvm::raw_svector_ostream os(sbuf);
1499
276
1500
276
    if (Constraint.getAs<Loc>()) {
1501
274
      os << "Assuming pointer value is ";
1502
274
      os << (Assumption ? 
"non-null"0
: "null");
1503
274
    }
1504
276
1505
276
    if (os.str().empty())
1506
2
      return nullptr;
1507
274
1508
274
    // Construct a new PathDiagnosticPiece.
1509
274
    ProgramPoint P = N->getLocation();
1510
274
    PathDiagnosticLocation L =
1511
274
      PathDiagnosticLocation::create(P, BRC.getSourceManager());
1512
274
    if (!L.isValid())
1513
0
      return nullptr;
1514
274
1515
274
    auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1516
274
    X->setTag(getTag());
1517
274
    return std::move(X);
1518
274
  }
1519
4.83k
1520
4.83k
  return nullptr;
1521
4.83k
}
1522
1523
//===----------------------------------------------------------------------===//
1524
// Implementation of SuppressInlineDefensiveChecksVisitor.
1525
//===----------------------------------------------------------------------===//
1526
1527
SuppressInlineDefensiveChecksVisitor::
1528
SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1529
268
    : V(Value) {
1530
268
  // Check if the visitor is disabled.
1531
268
  AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1532
268
  if (!Options.ShouldSuppressInlinedDefensiveChecks)
1533
0
    IsSatisfied = true;
1534
268
1535
268
  assert(N->getState()->isNull(V).isConstrainedTrue() &&
1536
268
         "The visitor only tracks the cases where V is constrained to 0");
1537
268
}
1538
1539
void SuppressInlineDefensiveChecksVisitor::Profile(
1540
268
    llvm::FoldingSetNodeID &ID) const {
1541
268
  static int id = 0;
1542
268
  ID.AddPointer(&id);
1543
268
  ID.Add(V);
1544
268
}
1545
1546
0
const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1547
0
  return "IDCVisitor";
1548
0
}
1549
1550
std::shared_ptr<PathDiagnosticPiece>
1551
SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1552
                                                BugReporterContext &BRC,
1553
7.32k
                                                BugReport &BR) {
1554
7.32k
  const ExplodedNode *Pred = Succ->getFirstPred();
1555
7.32k
  if (IsSatisfied)
1556
2.23k
    return nullptr;
1557
5.09k
1558
5.09k
  // Start tracking after we see the first state in which the value is null.
1559
5.09k
  if (!IsTrackingTurnedOn)
1560
564
    if (Succ->getState()->isNull(V).isConstrainedTrue())
1561
264
      IsTrackingTurnedOn = true;
1562
5.09k
  if (!IsTrackingTurnedOn)
1563
300
    return nullptr;
1564
4.79k
1565
4.79k
  // Check if in the previous state it was feasible for this value
1566
4.79k
  // to *not* be null.
1567
4.79k
  if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1568
264
    IsSatisfied = true;
1569
264
1570
264
    assert(Succ->getState()->isNull(V).isConstrainedTrue());
1571
264
1572
264
    // Check if this is inlined defensive checks.
1573
264
    const LocationContext *CurLC =Succ->getLocationContext();
1574
264
    const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1575
264
    if (CurLC != ReportLC && 
!CurLC->isParentOf(ReportLC)54
) {
1576
49
      BR.markInvalid("Suppress IDC", CurLC);
1577
49
      return nullptr;
1578
49
    }
1579
215
1580
215
    // Treat defensive checks in function-like macros as if they were an inlined
1581
215
    // defensive check. If the bug location is not in a macro and the
1582
215
    // terminator for the current location is in a macro then suppress the
1583
215
    // warning.
1584
215
    auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1585
215
1586
215
    if (!BugPoint)
1587
0
      return nullptr;
1588
215
1589
215
    ProgramPoint CurPoint = Succ->getLocation();
1590
215
    const Stmt *CurTerminatorStmt = nullptr;
1591
215
    if (auto BE = CurPoint.getAs<BlockEdge>()) {
1592
131
      CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1593
131
    } else 
if (auto 84
SP84
= CurPoint.getAs<StmtPoint>()) {
1594
84
      const Stmt *CurStmt = SP->getStmt();
1595
84
      if (!CurStmt->getBeginLoc().isMacroID())
1596
45
        return nullptr;
1597
39
1598
39
      CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1599
39
      CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
1600
39
    } else {
1601
0
      return nullptr;
1602
0
    }
1603
170
1604
170
    if (!CurTerminatorStmt)
1605
2
      return nullptr;
1606
168
1607
168
    SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1608
168
    if (TerminatorLoc.isMacroID()) {
1609
38
      SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1610
38
1611
38
      // Suppress reports unless we are in that same macro.
1612
38
      if (!BugLoc.isMacroID() ||
1613
38
          
getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)11
) {
1614
30
        BR.markInvalid("Suppress Macro IDC", CurLC);
1615
30
      }
1616
38
      return nullptr;
1617
38
    }
1618
4.66k
  }
1619
4.66k
  return nullptr;
1620
4.66k
}
1621
1622
//===----------------------------------------------------------------------===//
1623
// TrackControlDependencyCondBRVisitor.
1624
//===----------------------------------------------------------------------===//
1625
1626
namespace {
1627
/// Tracks the expressions that are a control dependency of the node that was
1628
/// supplied to the constructor.
1629
/// For example:
1630
///
1631
///   cond = 1;
1632
///   if (cond)
1633
///     10 / 0;
1634
///
1635
/// An error is emitted at line 3. This visitor realizes that the branch
1636
/// on line 2 is a control dependency of line 3, and tracks it's condition via
1637
/// trackExpressionValue().
1638
class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
1639
  const ExplodedNode *Origin;
1640
  ControlDependencyCalculator ControlDeps;
1641
  llvm::SmallSet<const CFGBlock *, 32> VisitedBlocks;
1642
1643
public:
1644
  TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
1645
90
  : Origin(O), ControlDeps(&O->getCFG()) {}
1646
1647
90
  void Profile(llvm::FoldingSetNodeID &ID) const override {
1648
90
    static int x = 0;
1649
90
    ID.AddPointer(&x);
1650
90
  }
1651
1652
  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1653
                                                 BugReporterContext &BRC,
1654
                                                 BugReport &BR) override;
1655
};
1656
} // end of anonymous namespace
1657
1658
2.25k
static CFGBlock *GetRelevantBlock(const ExplodedNode *Node) {
1659
2.25k
  if (auto SP = Node->getLocationAs<StmtPoint>()) {
1660
1.93k
    const Stmt *S = SP->getStmt();
1661
1.93k
    assert(S);
1662
1.93k
1663
1.93k
    return const_cast<CFGBlock *>(Node->getLocationContext()
1664
1.93k
        ->getAnalysisDeclContext()->getCFGStmtMap()->getBlock(S));
1665
1.93k
  }
1666
318
1667
318
  return nullptr;
1668
318
}
1669
1670
static std::shared_ptr<PathDiagnosticEventPiece>
1671
constructDebugPieceForTrackedCondition(const Expr *Cond,
1672
                                       const ExplodedNode *N,
1673
28
                                       BugReporterContext &BRC) {
1674
28
1675
28
  if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE ||
1676
28
      !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
1677
14
    return nullptr;
1678
14
1679
14
  std::string ConditionText = Lexer::getSourceText(
1680
14
      CharSourceRange::getTokenRange(Cond->getSourceRange()),
1681
14
                                     BRC.getSourceManager(),
1682
14
                                     BRC.getASTContext().getLangOpts());
1683
14
1684
14
  return std::make_shared<PathDiagnosticEventPiece>(
1685
14
      PathDiagnosticLocation::createBegin(
1686
14
          Cond, BRC.getSourceManager(), N->getLocationContext()),
1687
14
          (Twine() + "Tracking condition '" + ConditionText + "'").str());
1688
14
}
1689
1690
std::shared_ptr<PathDiagnosticPiece>
1691
TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
1692
                                               BugReporterContext &BRC,
1693
3.14k
                                               BugReport &BR) {
1694
3.14k
  // We can only reason about control dependencies within the same stack frame.
1695
3.14k
  if (Origin->getStackFrame() != N->getStackFrame())
1696
1.11k
    return nullptr;
1697
2.03k
1698
2.03k
  CFGBlock *NB = GetRelevantBlock(N);
1699
2.03k
1700
2.03k
  // Skip if we already inspected this block.
1701
2.03k
  if (!VisitedBlocks.insert(NB).second)
1702
1.80k
    return nullptr;
1703
224
1704
224
  CFGBlock *OriginB = GetRelevantBlock(Origin);
1705
224
1706
224
  // TODO: Cache CFGBlocks for each ExplodedNode.
1707
224
  if (!OriginB || !NB)
1708
88
    return nullptr;
1709
136
1710
136
  if (ControlDeps.isControlDependent(OriginB, NB)) {
1711
30
    if (const Expr *Condition = NB->getLastCondition()) {
1712
30
      // Keeping track of the already tracked conditions on a visitor level
1713
30
      // isn't sufficient, because a new visitor is created for each tracked
1714
30
      // expression, hence the BugReport level set.
1715
30
      if (BR.addTrackedCondition(N)) {
1716
28
        bugreporter::trackExpressionValue(
1717
28
            N, Condition, BR, /*EnableNullFPSuppression=*/false);
1718
28
        return constructDebugPieceForTrackedCondition(Condition, N, BRC);
1719
28
      }
1720
108
    }
1721
30
  }
1722
108
1723
108
  return nullptr;
1724
108
}
1725
1726
//===----------------------------------------------------------------------===//
1727
// Implementation of trackExpressionValue.
1728
//===----------------------------------------------------------------------===//
1729
1730
static const MemRegion *getLocationRegionIfReference(const Expr *E,
1731
1.49k
                                                     const ExplodedNode *N) {
1732
1.49k
  if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1733
1.37k
    if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1734
1.37k
      if (!VD->getType()->isReferenceType())
1735
1.33k
        return nullptr;
1736
34
      ProgramStateManager &StateMgr = N->getState()->getStateManager();
1737
34
      MemRegionManager &MRMgr = StateMgr.getRegionManager();
1738
34
      return MRMgr.getVarRegion(VD, N->getLocationContext());
1739
34
    }
1740
1.37k
  }
1741
123
1742
123
  // FIXME: This does not handle other kinds of null references,
1743
123
  // for example, references from FieldRegions:
1744
123
  //   struct Wrapper { int &ref; };
1745
123
  //   Wrapper w = { *(int *)0 };
1746
123
  //   w.ref = 1;
1747
123
1748
123
  return nullptr;
1749
123
}
1750
1751
/// \return A subexpression of {@code Ex} which represents the
1752
/// expression-of-interest.
1753
static const Expr *peelOffOuterExpr(const Expr *Ex,
1754
3.23k
                                    const ExplodedNode *N) {
1755
3.23k
  Ex = Ex->IgnoreParenCasts();
1756
3.23k
  if (const auto *FE = dyn_cast<FullExpr>(Ex))
1757
0
    return peelOffOuterExpr(FE->getSubExpr(), N);
1758
3.23k
  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1759
28
    return peelOffOuterExpr(OVE->getSourceExpr(), N);
1760
3.20k
  if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1761
24
    const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1762
24
    if (PropRef && PropRef->isMessagingGetter()) {
1763
24
      const Expr *GetterMessageSend =
1764
24
          POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1765
24
      assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1766
24
      return peelOffOuterExpr(GetterMessageSend, N);
1767
24
    }
1768
3.18k
  }
1769
3.18k
1770
3.18k
  // Peel off the ternary operator.
1771
3.18k
  if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1772
49
    // Find a node where the branching occurred and find out which branch
1773
49
    // we took (true/false) by looking at the ExplodedGraph.
1774
49
    const ExplodedNode *NI = N;
1775
1.17k
    do {
1776
1.17k
      ProgramPoint ProgPoint = NI->getLocation();
1777
1.17k
      if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1778
192
        const CFGBlock *srcBlk = BE->getSrc();
1779
192
        if (const Stmt *term = srcBlk->getTerminatorStmt()) {
1780
56
          if (term == CO) {
1781
48
            bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1782
48
            if (TookTrueBranch)
1783
24
              return peelOffOuterExpr(CO->getTrueExpr(), N);
1784
24
            else
1785
24
              return peelOffOuterExpr(CO->getFalseExpr(), N);
1786
1.13k
          }
1787
56
        }
1788
192
      }
1789
1.13k
      NI = NI->getFirstPred();
1790
1.13k
    } while (NI);
1791
49
  }
1792
3.18k
1793
3.18k
  
if (auto *3.13k
BO3.13k
= dyn_cast<BinaryOperator>(Ex))
1794
68
    if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1795
7
      return peelOffOuterExpr(SubEx, N);
1796
3.12k
1797
3.12k
  if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
1798
48
    if (UO->getOpcode() == UO_LNot)
1799
9
      return peelOffOuterExpr(UO->getSubExpr(), N);
1800
39
1801
39
    // FIXME: There's a hack in our Store implementation that always computes
1802
39
    // field offsets around null pointers as if they are always equal to 0.
1803
39
    // The idea here is to report accesses to fields as null dereferences
1804
39
    // even though the pointer value that's being dereferenced is actually
1805
39
    // the offset of the field rather than exactly 0.
1806
39
    // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1807
39
    // This code interacts heavily with this hack; otherwise the value
1808
39
    // would not be null at all for most fields, so we'd be unable to track it.
1809
39
    if (UO->getOpcode() == UO_AddrOf && 
UO->getSubExpr()->isLValue()12
)
1810
12
      if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
1811
12
        return peelOffOuterExpr(DerefEx, N);
1812
3.10k
  }
1813
3.10k
1814
3.10k
  return Ex;
1815
3.10k
}
1816
1817
/// Find the ExplodedNode where the lvalue (the value of 'Ex')
1818
/// was computed.
1819
static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1820
3.10k
                                                 const Expr *Inner) {
1821
29.4k
  while (N) {
1822
29.4k
    if (PathDiagnosticLocation::getStmt(N) == Inner)
1823
3.09k
      return N;
1824
26.3k
    N = N->getFirstPred();
1825
26.3k
  }
1826
3.10k
  
return N12
;
1827
3.10k
}
1828
1829
bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
1830
                                       const Expr *E, BugReport &report,
1831
3.10k
                                       bool EnableNullFPSuppression) {
1832
3.10k
  if (!E || !InputNode)
1833
0
    return false;
1834
3.10k
1835
3.10k
  const Expr *Inner = peelOffOuterExpr(E, InputNode);
1836
3.10k
  const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
1837
3.10k
  if (!LVNode)
1838
12
    return false;
1839
3.09k
1840
3.09k
  ProgramStateRef LVState = LVNode->getState();
1841
3.09k
1842
3.09k
  // We only track expressions if we believe that they are important. Chances
1843
3.09k
  // are good that control dependencies to the tracking point are also improtant
1844
3.09k
  // because of this, let's explain why we believe control reached this point.
1845
3.09k
  // TODO: Shouldn't we track control dependencies of every bug location, rather
1846
3.09k
  // than only tracked expressions?
1847
3.09k
  if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions)
1848
90
    report.addVisitor(llvm::make_unique<TrackControlDependencyCondBRVisitor>(
1849
90
          InputNode));
1850
3.09k
1851
3.09k
  // The message send could be nil due to the receiver being nil.
1852
3.09k
  // At this point in the path, the receiver should be live since we are at the
1853
3.09k
  // message send expr. If it is nil, start tracking it.
1854
3.09k
  if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
1855
38
    trackExpressionValue(LVNode, Receiver, report, EnableNullFPSuppression);
1856
3.09k
1857
3.09k
  // Track the index if this is an array subscript.
1858
3.09k
  if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
1859
22
    trackExpressionValue(
1860
22
        LVNode, Arr->getIdx(), report, /*EnableNullFPSuppression*/ false);
1861
3.09k
1862
3.09k
  // See if the expression we're interested refers to a variable.
1863
3.09k
  // If so, we can track both its contents and constraints on its value.
1864
3.09k
  if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1865
1.49k
    SVal LVal = LVNode->getSVal(Inner);
1866
1.49k
1867
1.49k
    const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
1868
1.49k
    bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1869
1.49k
1870
1.49k
    // If this is a C++ reference to a null pointer, we are tracking the
1871
1.49k
    // pointer. In addition, we should find the store at which the reference
1872
1.49k
    // got initialized.
1873
1.49k
    if (RR && 
!LVIsNull34
)
1874
27
      if (auto KV = LVal.getAs<KnownSVal>())
1875
27
        report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1876
27
              *KV, RR, EnableNullFPSuppression));
1877
1.49k
1878
1.49k
    // In case of C++ references, we want to differentiate between a null
1879
1.49k
    // reference and reference to null pointer.
1880
1.49k
    // If the LVal is null, check if we are dealing with null reference.
1881
1.49k
    // For those, we want to track the location of the reference.
1882
1.49k
    const MemRegion *R = (RR && 
LVIsNull34
) ?
RR7
:
1883
1.49k
        
LVNode->getSVal(Inner).getAsRegion()1.48k
;
1884
1.49k
1885
1.49k
    if (R) {
1886
1.49k
1887
1.49k
      // Mark both the variable region and its contents as interesting.
1888
1.49k
      SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1889
1.49k
      report.addVisitor(
1890
1.49k
          llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
1891
1.49k
1892
1.49k
      MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1893
1.49k
          LVNode, R, EnableNullFPSuppression, report, V);
1894
1.49k
1895
1.49k
      report.markInteresting(V);
1896
1.49k
      report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1897
1.49k
1898
1.49k
      // If the contents are symbolic, find out when they became null.
1899
1.49k
      if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1900
273
        report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1901
273
              V.castAs<DefinedSVal>(), false));
1902
1.49k
1903
1.49k
      // Add visitor, which will suppress inline defensive checks.
1904
1.49k
      if (auto DV = V.getAs<DefinedSVal>())
1905
1.29k
        if (!DV->isZeroConstant() && 
LVState->isNull(*DV).isConstrainedTrue()387
&&
1906
1.29k
            
EnableNullFPSuppression286
)
1907
268
          report.addVisitor(
1908
268
              llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1909
268
                                                                      LVNode));
1910
1.49k
1911
1.49k
      if (auto KV = V.getAs<KnownSVal>())
1912
1.49k
        report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1913
1.49k
              *KV, R, EnableNullFPSuppression));
1914
1.49k
      return true;
1915
1.49k
    }
1916
1.60k
  }
1917
1.60k
1918
1.60k
  // If the expression is not an "lvalue expression", we can still
1919
1.60k
  // track the constraints on its contents.
1920
1.60k
  SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
1921
1.60k
1922
1.60k
  ReturnVisitor::addVisitorIfNecessary(
1923
1.60k
    LVNode, Inner, report, EnableNullFPSuppression);
1924
1.60k
1925
1.60k
  // Is it a symbolic value?
1926
1.60k
  if (auto L = V.getAs<loc::MemRegionVal>()) {
1927
59
    report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1928
59
1929
59
    // FIXME: this is a hack for fixing a later crash when attempting to
1930
59
    // dereference a void* pointer.
1931
59
    // We should not try to dereference pointers at all when we don't care
1932
59
    // what is written inside the pointer.
1933
59
    bool CanDereference = true;
1934
59
    if (const auto *SR = dyn_cast<SymbolicRegion>(L->getRegion()))
1935
16
      if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
1936
1
        CanDereference = false;
1937
59
1938
59
    // At this point we are dealing with the region's LValue.
1939
59
    // However, if the rvalue is a symbolic region, we should track it as well.
1940
59
    // Try to use the correct type when looking up the value.
1941
59
    SVal RVal;
1942
59
    if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1943
0
      RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
1944
59
    } else if (CanDereference) {
1945
58
      RVal = LVState->getSVal(L->getRegion());
1946
58
    }
1947
59
1948
59
    if (CanDereference)
1949
58
      if (auto KV = RVal.getAs<KnownSVal>())
1950
58
        report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1951
58
            *KV, L->getRegion(), EnableNullFPSuppression));
1952
59
1953
59
    const MemRegion *RegionRVal = RVal.getAsRegion();
1954
59
    if (RegionRVal && 
isa<SymbolicRegion>(RegionRVal)8
) {
1955
8
      report.markInteresting(RegionRVal);
1956
8
      report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1957
8
            loc::MemRegionVal(RegionRVal), /*assumption=*/false));
1958
8
    }
1959
59
  }
1960
1.60k
  return true;
1961
1.60k
}
1962
1963
//===----------------------------------------------------------------------===//
1964
// Implementation of NulReceiverBRVisitor.
1965
//===----------------------------------------------------------------------===//
1966
1967
const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1968
22.7k
                                                 const ExplodedNode *N) {
1969
22.7k
  const auto *ME = dyn_cast<ObjCMessageExpr>(S);
1970
22.7k
  if (!ME)
1971
22.5k
    return nullptr;
1972
225
  if (const Expr *Receiver = ME->getInstanceReceiver()) {
1973
164
    ProgramStateRef state = N->getState();
1974
164
    SVal V = N->getSVal(Receiver);
1975
164
    if (state->isNull(V).isConstrainedTrue())
1976
86
      return Receiver;
1977
139
  }
1978
139
  return nullptr;
1979
139
}
1980
1981
std::shared_ptr<PathDiagnosticPiece>
1982
NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1983
992k
                                BugReporterContext &BRC, BugReport &BR) {
1984
992k
  Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1985
992k
  if (!P)
1986
972k
    return nullptr;
1987
19.6k
1988
19.6k
  const Stmt *S = P->getStmt();
1989
19.6k
  const Expr *Receiver = getNilReceiver(S, N);
1990
19.6k
  if (!Receiver)
1991
19.6k
    return nullptr;
1992
48
1993
48
  llvm::SmallString<256> Buf;
1994
48
  llvm::raw_svector_ostream OS(Buf);
1995
48
1996
48
  if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1997
48
    OS << "'";
1998
48
    ME->getSelector().print(OS);
1999
48
    OS << "' not called";
2000
48
  }
2001
0
  else {
2002
0
    OS << "No method is called";
2003
0
  }
2004
48
  OS << " because the receiver is nil";
2005
48
2006
48
  // The receiver was nil, and hence the method was skipped.
2007
48
  // Register a BugReporterVisitor to issue a message telling us how
2008
48
  // the receiver was null.
2009
48
  bugreporter::trackExpressionValue(N, Receiver, BR,
2010
48
                               /*EnableNullFPSuppression*/ false);
2011
48
  // Issue a message saying that the method was skipped.
2012
48
  PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
2013
48
                                     N->getLocationContext());
2014
48
  return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
2015
48
}
2016
2017
//===----------------------------------------------------------------------===//
2018
// Implementation of FindLastStoreBRVisitor.
2019
//===----------------------------------------------------------------------===//
2020
2021
// Registers every VarDecl inside a Stmt with a last store visitor.
2022
void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
2023
                                                const Stmt *S,
2024
0
                                                bool EnableNullFPSuppression) {
2025
0
  const ExplodedNode *N = BR.getErrorNode();
2026
0
  std::deque<const Stmt *> WorkList;
2027
0
  WorkList.push_back(S);
2028
0
2029
0
  while (!WorkList.empty()) {
2030
0
    const Stmt *Head = WorkList.front();
2031
0
    WorkList.pop_front();
2032
0
2033
0
    ProgramStateManager &StateMgr = N->getState()->getStateManager();
2034
0
2035
0
    if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
2036
0
      if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2037
0
        const VarRegion *R =
2038
0
        StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
2039
0
2040
0
        // What did we load?
2041
0
        SVal V = N->getSVal(S);
2042
0
2043
0
        if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
2044
0
          // Register a new visitor with the BugReport.
2045
0
          BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
2046
0
              V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
2047
0
        }
2048
0
      }
2049
0
    }
2050
0
2051
0
    for (const Stmt *SubStmt : Head->children())
2052
0
      WorkList.push_back(SubStmt);
2053
0
  }
2054
0
}
2055
2056
//===----------------------------------------------------------------------===//
2057
// Visitor that tries to report interesting diagnostics from conditions.
2058
//===----------------------------------------------------------------------===//
2059
2060
/// Return the tag associated with this visitor.  This tag will be used
2061
/// to make all PathDiagnosticPieces created by this visitor.
2062
5.04k
const char *ConditionBRVisitor::getTag() {
2063
5.04k
  return "ConditionBRVisitor";
2064
5.04k
}
2065
2066
std::shared_ptr<PathDiagnosticPiece>
2067
ConditionBRVisitor::VisitNode(const ExplodedNode *N,
2068
992k
                              BugReporterContext &BRC, BugReport &BR) {
2069
992k
  auto piece = VisitNodeImpl(N, BRC, BR);
2070
992k
  if (piece) {
2071
4.14k
    piece->setTag(getTag());
2072
4.14k
    if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
2073
3.30k
      ev->setPrunable(true, /* override */ false);
2074
4.14k
  }
2075
992k
  return piece;
2076
992k
}
2077
2078
std::shared_ptr<PathDiagnosticPiece>
2079
ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
2080
992k
                                  BugReporterContext &BRC, BugReport &BR) {
2081
992k
  ProgramPoint ProgPoint = N->getLocation();
2082
992k
  const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
2083
992k
      ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
2084
992k
2085
992k
  // If an assumption was made on a branch, it should be caught
2086
992k
  // here by looking at the state transition.
2087
992k
  if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2088
49.4k
    const CFGBlock *SrcBlock = BE->getSrc();
2089
49.4k
    if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
2090
6.54k
      // If the tag of the previous node is 'Eagerly Assume...' the current
2091
6.54k
      // 'BlockEdge' has the same constraint information. We do not want to
2092
6.54k
      // report the value as it is just an assumption on the predecessor node
2093
6.54k
      // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
2094
6.54k
      const ProgramPointTag *PreviousNodeTag =
2095
6.54k
          N->getFirstPred()->getLocation().getTag();
2096
6.54k
      if (PreviousNodeTag == Tags.first || 
PreviousNodeTag == Tags.second6.16k
)
2097
731
        return nullptr;
2098
5.81k
2099
5.81k
      return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
2100
5.81k
    }
2101
42.9k
    return nullptr;
2102
42.9k
  }
2103
943k
2104
943k
  if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
2105
663k
    const ProgramPointTag *CurrentNodeTag = PS->getTag();
2106
663k
    if (CurrentNodeTag != Tags.first && 
CurrentNodeTag != Tags.second662k
)
2107
662k
      return nullptr;
2108
848
2109
848
    bool TookTrue = CurrentNodeTag == Tags.first;
2110
848
    return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
2111
848
  }
2112
280k
2113
280k
  return nullptr;
2114
280k
}
2115
2116
std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
2117
    const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
2118
5.81k
    const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
2119
5.81k
  const Expr *Cond = nullptr;
2120
5.81k
2121
5.81k
  // In the code below, Term is a CFG terminator and Cond is a branch condition
2122
5.81k
  // expression upon which the decision is made on this terminator.
2123
5.81k
  //
2124
5.81k
  // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
2125
5.81k
  // and "x == 0" is the respective condition.
2126
5.81k
  //
2127
5.81k
  // Another example: in "if (x && y)", we've got two terminators and two
2128
5.81k
  // conditions due to short-circuit nature of operator "&&":
2129
5.81k
  // 1. The "if (x && y)" statement is a terminator,
2130
5.81k
  //    and "y" is the respective condition.
2131
5.81k
  // 2. Also "x && ..." is another terminator,
2132
5.81k
  //    and "x" is its condition.
2133
5.81k
2134
5.81k
  switch (Term->getStmtClass()) {
2135
5.81k
  // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
2136
5.81k
  // more tricky because there are more than two branches to account for.
2137
5.81k
  default:
2138
2.11k
    return nullptr;
2139
5.81k
  case Stmt::IfStmtClass:
2140
2.27k
    Cond = cast<IfStmt>(Term)->getCond();
2141
2.27k
    break;
2142
5.81k
  case Stmt::ConditionalOperatorClass:
2143
1.07k
    Cond = cast<ConditionalOperator>(Term)->getCond();
2144
1.07k
    break;
2145
5.81k
  case Stmt::BinaryOperatorClass:
2146
338
    // When we encounter a logical operator (&& or ||) as a CFG terminator,
2147
338
    // then the condition is actually its LHS; otherwise, we'd encounter
2148
338
    // the parent, such as if-statement, as a terminator.
2149
338
    const auto *BO = cast<BinaryOperator>(Term);
2150
338
    assert(BO->isLogicalOp() &&
2151
338
           "CFG terminator is not a short-circuit operator!");
2152
338
    Cond = BO->getLHS();
2153
338
    break;
2154
3.69k
  }
2155
3.69k
2156
3.69k
  Cond = Cond->IgnoreParens();
2157
3.69k
2158
3.69k
  // However, when we encounter a logical operator as a branch condition,
2159
3.69k
  // then the condition is actually its RHS, because LHS would be
2160
3.69k
  // the condition for the logical operator terminator.
2161
3.81k
  while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
2162
2.13k
    if (!InnerBO->isLogicalOp())
2163
2.01k
      break;
2164
122
    Cond = InnerBO->getRHS()->IgnoreParens();
2165
122
  }
2166
3.69k
2167
3.69k
  assert(Cond);
2168
3.69k
  assert(srcBlk->succ_size() == 2);
2169
3.69k
  const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
2170
3.69k
  return VisitTrueTest(Cond, BRC, R, N, TookTrue);
2171
3.69k
}
2172
2173
std::shared_ptr<PathDiagnosticPiece>
2174
ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC,
2175
                                  BugReport &R, const ExplodedNode *N,
2176
4.54k
                                  bool TookTrue) {
2177
4.54k
  ProgramStateRef CurrentState = N->getState();
2178
4.54k
  ProgramStateRef PrevState = N->getFirstPred()->getState();
2179
4.54k
  const LocationContext *LCtx = N->getLocationContext();
2180
4.54k
2181
4.54k
  // If the constraint information is changed between the current and the
2182
4.54k
  // previous program state we assuming the newly seen constraint information.
2183
4.54k
  // If we cannot evaluate the condition (and the constraints are the same)
2184
4.54k
  // the analyzer has no information about the value and just assuming it.
2185
4.54k
  bool IsAssuming =
2186
4.54k
      !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
2187
4.54k
      
CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef()1.28k
;
2188
4.54k
2189
4.54k
  // These will be modified in code below, but we need to preserve the original
2190
4.54k
  //  values in case we want to throw the generic message.
2191
4.54k
  const Expr *CondTmp = Cond;
2192
4.54k
  bool TookTrueTmp = TookTrue;
2193
4.54k
2194
4.83k
  while (true) {
2195
4.83k
    CondTmp = CondTmp->IgnoreParenCasts();
2196
4.83k
    switch (CondTmp->getStmtClass()) {
2197
4.83k
      default:
2198
492
        break;
2199
4.83k
      case Stmt::BinaryOperatorClass:
2200
2.80k
        if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
2201
1.30k
                                   BRC, R, N, TookTrueTmp, IsAssuming))
2202
1.30k
          return P;
2203
1.50k
        break;
2204
1.50k
      case Stmt::DeclRefExprClass:
2205
1.10k
        if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
2206
1.09k
                                   BRC, R, N, TookTrueTmp, IsAssuming))
2207
1.09k
          return P;
2208
10
        break;
2209
128
      case Stmt::MemberExprClass:
2210
128
        if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
2211
87
                                   BRC, R, N, TookTrueTmp, IsAssuming))
2212
87
          return P;
2213
41
        break;
2214
307
      case Stmt::UnaryOperatorClass: {
2215
307
        const auto *UO = cast<UnaryOperator>(CondTmp);
2216
307
        if (UO->getOpcode() == UO_LNot) {
2217
296
          TookTrueTmp = !TookTrueTmp;
2218
296
          CondTmp = UO->getSubExpr();
2219
296
          continue;
2220
296
        }
2221
11
        break;
2222
11
      }
2223
2.05k
    }
2224
2.05k
    break;
2225
2.05k
  }
2226
4.54k
2227
4.54k
  // Condition too complex to explain? Just say something so that the user
2228
4.54k
  // knew we've made some path decision at this point.
2229
4.54k
  // If it is too complex and we know the evaluation of the condition do not
2230
4.54k
  // repeat the note from 'BugReporter.cpp'
2231
4.54k
  
if (2.05k
!IsAssuming2.05k
)
2232
394
    return nullptr;
2233
1.66k
2234
1.66k
  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2235
1.66k
  if (!Loc.isValid() || !Loc.asLocation().isValid())
2236
4
    return nullptr;
2237
1.65k
2238
1.65k
  return std::make_shared<PathDiagnosticEventPiece>(
2239
1.65k
      Loc, TookTrue ? 
GenericTrueMessage1.21k
:
GenericFalseMessage441
);
2240
1.65k
}
2241
2242
bool ConditionBRVisitor::patternMatch(const Expr *Ex,
2243
                                      const Expr *ParentEx,
2244
                                      raw_ostream &Out,
2245
                                      BugReporterContext &BRC,
2246
                                      BugReport &report,
2247
                                      const ExplodedNode *N,
2248
                                      Optional<bool> &prunable,
2249
5.60k
                                      bool IsSameFieldName) {
2250
5.60k
  const Expr *OriginalExpr = Ex;
2251
5.60k
  Ex = Ex->IgnoreParenCasts();
2252
5.60k
2253
5.60k
  if (isa<GNUNullExpr>(Ex) || 
isa<ObjCBoolLiteralExpr>(Ex)5.60k
||
2254
5.60k
      
isa<CXXBoolLiteralExpr>(Ex)5.60k
||
isa<IntegerLiteral>(Ex)5.60k
||
2255
5.60k
      
isa<FloatingLiteral>(Ex)4.11k
) {
2256
1.49k
    // Use heuristics to determine if the expression is a macro
2257
1.49k
    // expanding to a literal and if so, use the macro's name.
2258
1.49k
    SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
2259
1.49k
    SourceLocation EndLoc = OriginalExpr->getEndLoc();
2260
1.49k
    if (BeginLoc.isMacroID() && 
EndLoc.isMacroID()89
) {
2261
89
      SourceManager &SM = BRC.getSourceManager();
2262
89
      const LangOptions &LO = BRC.getASTContext().getLangOpts();
2263
89
      if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
2264
89
          
Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)14
) {
2265
14
        CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
2266
14
        Out << Lexer::getSourceText(R, SM, LO);
2267
14
        return false;
2268
14
      }
2269
5.59k
    }
2270
1.49k
  }
2271
5.59k
2272
5.59k
  if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
2273
2.30k
    const bool quotes = isa<VarDecl>(DR->getDecl());
2274
2.30k
    if (quotes) {
2275
2.29k
      Out << '\'';
2276
2.29k
      const LocationContext *LCtx = N->getLocationContext();
2277
2.29k
      const ProgramState *state = N->getState().get();
2278
2.29k
      if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
2279
2.29k
                                                LCtx).getAsRegion()) {
2280
2.29k
        if (report.isInteresting(R))
2281
0
          prunable = false;
2282
2.29k
        else {
2283
2.29k
          const ProgramState *state = N->getState().get();
2284
2.29k
          SVal V = state->getSVal(R);
2285
2.29k
          if (report.isInteresting(V))
2286
92
            prunable = false;
2287
2.29k
        }
2288
2.29k
      }
2289
2.29k
    }
2290
2.30k
    Out << DR->getDecl()->getDeclName().getAsString();
2291
2.30k
    if (quotes)
2292
2.29k
      Out << '\'';
2293
2.30k
    return quotes;
2294
2.30k
  }
2295
3.28k
2296
3.28k
  if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2297
1.47k
    QualType OriginalTy = OriginalExpr->getType();
2298
1.47k
    if (OriginalTy->isPointerType()) {
2299
126
      if (IL->getValue() == 0) {
2300
126
        Out << "null";
2301
126
        return false;
2302
126
      }
2303
1.34k
    }
2304
1.34k
    else if (OriginalTy->isObjCObjectPointerType()) {
2305
4
      if (IL->getValue() == 0) {
2306
4
        Out << "nil";
2307
4
        return false;
2308
4
      }
2309
1.34k
    }
2310
1.34k
2311
1.34k
    Out << IL->getValue();
2312
1.34k
    return false;
2313
1.34k
  }
2314
1.81k
2315
1.81k
  if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
2316
201
    if (!IsSameFieldName)
2317
193
      Out << "field '" << ME->getMemberDecl()->getName() << '\'';
2318
8
    else
2319
8
      Out << '\''
2320
8
          << Lexer::getSourceText(
2321
8
                 CharSourceRange::getTokenRange(Ex->getSourceRange()),
2322
8
                 BRC.getSourceManager(), BRC.getASTContext().getLangOpts(), 0)
2323
8
          << '\'';
2324
201
  }
2325
1.81k
2326
1.81k
  return false;
2327
1.81k
}
2328
2329
std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTrueTest(
2330
    const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
2331
2.80k
    BugReport &R, const ExplodedNode *N, bool TookTrue, bool IsAssuming) {
2332
2.80k
  bool shouldInvert = false;
2333
2.80k
  Optional<bool> shouldPrune;
2334
2.80k
2335
2.80k
  // Check if the field name of the MemberExprs is ambiguous. Example:
2336
2.80k
  // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
2337
2.80k
  bool IsSameFieldName = false;
2338
2.80k
  if (const auto *LhsME =
2339
197
          dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts()))
2340
197
    if (const auto *RhsME =
2341
4
            dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts()))
2342
4
      IsSameFieldName = LhsME->getMemberDecl()->getName() ==
2343
4
                        RhsME->getMemberDecl()->getName();
2344
2.80k
2345
2.80k
  SmallString<128> LhsString, RhsString;
2346
2.80k
  {
2347
2.80k
    llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
2348
2.80k
    const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
2349
2.80k
                                       N, shouldPrune, IsSameFieldName);
2350
2.80k
    const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
2351
2.80k
                                       N, shouldPrune, IsSameFieldName);
2352
2.80k
2353
2.80k
    shouldInvert = !isVarLHS && 
isVarRHS667
;
2354
2.80k
  }
2355
2.80k
2356
2.80k
  BinaryOperator::Opcode Op = BExpr->getOpcode();
2357
2.80k
2358
2.80k
  if (BinaryOperator::isAssignmentOp(Op)) {
2359
7
    // For assignment operators, all that we care about is that the LHS
2360
7
    // evaluates to "true" or "false".
2361
7
    return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
2362
7
                                  TookTrue);
2363
7
  }
2364
2.79k
2365
2.79k
  // For non-assignment operations, we require that we can understand
2366
2.79k
  // both the LHS and RHS.
2367
2.79k
  if (LhsString.empty() || 
RhsString.empty()2.33k
||
2368
2.79k
      
!BinaryOperator::isComparisonOp(Op)1.30k
||
Op == BO_Cmp1.29k
)
2369
1.50k
    return nullptr;
2370
1.29k
2371
1.29k
  // Should we invert the strings if the LHS is not a variable name?
2372
1.29k
  SmallString<256> buf;
2373
1.29k
  llvm::raw_svector_ostream Out(buf);
2374
1.29k
  Out << (IsAssuming ? 
"Assuming "899
:
""396
)
2375
1.29k
      << (shouldInvert ? 
RhsString9
:
LhsString1.28k
) << " is ";
2376
1.29k
2377
1.29k
  // Do we need to invert the opcode?
2378
1.29k
  if (shouldInvert)
2379
9
    switch (Op) {
2380
9
      default: break;
2381
9
      
case BO_LT: Op = BO_GT; break0
;
2382
9
      
case BO_GT: Op = BO_LT; break0
;
2383
9
      
case BO_LE: Op = BO_GE; break0
;
2384
9
      
case BO_GE: Op = BO_LE; break0
;
2385
1.29k
    }
2386
1.29k
2387
1.29k
  if (!TookTrue)
2388
785
    switch (Op) {
2389
785
      
case BO_EQ: Op = BO_NE; break246
;
2390
785
      
case BO_NE: Op = BO_EQ; break343
;
2391
785
      
case BO_LT: Op = BO_GE; break75
;
2392
785
      
case BO_GT: Op = BO_LE; break84
;
2393
785
      
case BO_LE: Op = BO_GT; break12
;
2394
785
      
case BO_GE: Op = BO_LT; break25
;
2395
785
      default:
2396
0
        return nullptr;
2397
1.29k
    }
2398
1.29k
2399
1.29k
  switch (Op) {
2400
1.29k
    case BO_EQ:
2401
633
      Out << "equal to ";
2402
633
      break;
2403
1.29k
    case BO_NE:
2404
299
      Out << "not equal to ";
2405
299
      break;
2406
1.29k
    default:
2407
363
      Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2408
363
      break;
2409
1.29k
  }
2410
1.29k
2411
1.29k
  Out << (shouldInvert ? 
LhsString9
:
RhsString1.28k
);
2412
1.29k
  const LocationContext *LCtx = N->getLocationContext();
2413
1.29k
  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2414
1.29k
2415
1.29k
  // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
2416
1.29k
  std::string Message = Out.str();
2417
1.29k
  Message[0] = toupper(Message[0]);
2418
1.29k
2419
1.29k
  // If we know the value create a pop-up note.
2420
1.29k
  if (!IsAssuming)
2421
396
    return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
2422
899
2423
899
  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
2424
899
  if (shouldPrune.hasValue())
2425
79
    event->setPrunable(shouldPrune.getValue());
2426
899
  return event;
2427
899
}
2428
2429
std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
2430
    StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
2431
7
    BugReport &report, const ExplodedNode *N, bool TookTrue) {
2432
7
  // FIXME: If there's already a constraint tracker for this variable,
2433
7
  // we shouldn't emit anything here (c.f. the double note in
2434
7
  // test/Analysis/inlining/path-notes.c)
2435
7
  SmallString<256> buf;
2436
7
  llvm::raw_svector_ostream Out(buf);
2437
7
  Out << "Assuming " << LhsString << " is ";
2438
7
2439
7
  if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
2440
0
    return nullptr;
2441
7
2442
7
  const LocationContext *LCtx = N->getLocationContext();
2443
7
  PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2444
7
  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2445
7
2446
7
  if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
2447
7
    if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2448
7
      const ProgramState *state = N->getState().get();
2449
7
      if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2450
7
        if (report.isInteresting(R))
2451
0
          event->setPrunable(false);
2452
7
      }
2453
7
    }
2454
7
  }
2455
7
2456
7
  return event;
2457
7
}
2458
2459
std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTrueTest(
2460
    const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
2461
1.10k
    BugReport &report, const ExplodedNode *N, bool TookTrue, bool IsAssuming) {
2462
1.10k
  const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
2463
1.10k
  if (!VD)
2464
4
    return nullptr;
2465
1.10k
2466
1.10k
  SmallString<256> Buf;
2467
1.10k
  llvm::raw_svector_ostream Out(Buf);
2468
1.10k
2469
1.10k
  Out << (IsAssuming ? 
"Assuming '"721
:
"'"382
) << VD->getDeclName() << "' is ";
2470
1.10k
2471
1.10k
  if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
2472
6
    return nullptr;
2473
1.09k
2474
1.09k
  const LocationContext *LCtx = N->getLocationContext();
2475
1.09k
  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2476
1.09k
2477
1.09k
  // If we know the value create a pop-up note.
2478
1.09k
  if (!IsAssuming)
2479
382
    return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2480
715
2481
715
  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2482
715
  const ProgramState *state = N->getState().get();
2483
715
  if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2484
715
    if (report.isInteresting(R))
2485
0
      event->setPrunable(false);
2486
715
    else {
2487
715
      SVal V = state->getSVal(R);
2488
715
      if (report.isInteresting(V))
2489
210
        event->setPrunable(false);
2490
715
    }
2491
715
  }
2492
715
  return std::move(event);
2493
715
}
2494
2495
std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTrueTest(
2496
    const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
2497
128
    BugReport &report, const ExplodedNode *N, bool TookTrue, bool IsAssuming) {
2498
128
  SmallString<256> Buf;
2499
128
  llvm::raw_svector_ostream Out(Buf);
2500
128
2501
128
  Out << (IsAssuming ? 
"Assuming field '"29
:
"Field '"99
)
2502
128
      << ME->getMemberDecl()->getName() << "' is ";
2503
128
2504
128
  if (!printValue(ME, Out, N, TookTrue, IsAssuming))
2505
0
    return nullptr;
2506
128
2507
128
  const LocationContext *LCtx = N->getLocationContext();
2508
128
  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2509
128
  if (!Loc.isValid() || !Loc.asLocation().isValid())
2510
41
    return nullptr;
2511
87
2512
87
  // If we know the value create a pop-up note.
2513
87
  if (!IsAssuming)
2514
58
    return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2515
29
2516
29
  return std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2517
29
}
2518
2519
bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
2520
                                    const ExplodedNode *N, bool TookTrue,
2521
1.23k
                                    bool IsAssuming) {
2522
1.23k
  QualType Ty = CondVarExpr->getType();
2523
1.23k
2524
1.23k
  if (Ty->isPointerType()) {
2525
457
    Out << (TookTrue ? 
"non-null"117
:
"null"340
);
2526
457
    return true;
2527
457
  }
2528
781
2529
781
  if (Ty->isObjCObjectPointerType()) {
2530
65
    Out << (TookTrue ? 
"non-nil"24
:
"nil"41
);
2531
65
    return true;
2532
65
  }
2533
716
2534
716
  if (!Ty->isIntegralOrEnumerationType())
2535
6
    return false;
2536
710
2537
710
  Optional<const llvm::APSInt *> IntValue;
2538
710
  if (!IsAssuming)
2539
331
    IntValue = getConcreteIntegerValue(CondVarExpr, N);
2540
710
2541
710
  if (IsAssuming || 
!IntValue.hasValue()331
) {
2542
637
    if (Ty->isBooleanType())
2543
69
      Out << (TookTrue ? 
"true"39
:
"false"30
);
2544
568
    else
2545
568
      Out << (TookTrue ? 
"not equal to 0"268
:
"0"300
);
2546
637
  } else {
2547
73
    if (Ty->isBooleanType())
2548
11
      Out << (IntValue.getValue()->getBoolValue() ? 
"true"3
:
"false"8
);
2549
62
    else
2550
62
      Out << *IntValue.getValue();
2551
73
  }
2552
710
2553
710
  return true;
2554
710
}
2555
2556
const char *const ConditionBRVisitor::GenericTrueMessage =
2557
    "Assuming the condition is true";
2558
const char *const ConditionBRVisitor::GenericFalseMessage =
2559
    "Assuming the condition is false";
2560
2561
bool ConditionBRVisitor::isPieceMessageGeneric(
2562
88
    const PathDiagnosticPiece *Piece) {
2563
88
  return Piece->getString() == GenericTrueMessage ||
2564
88
         
Piece->getString() == GenericFalseMessage85
;
2565
88
}
2566
2567
//===----------------------------------------------------------------------===//
2568
// Implementation of LikelyFalsePositiveSuppressionBRVisitor.
2569
//===----------------------------------------------------------------------===//
2570
2571
void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
2572
9.93k
    BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
2573
9.93k
  // Here we suppress false positives coming from system headers. This list is
2574
9.93k
  // based on known issues.
2575
9.93k
  AnalyzerOptions &Options = BRC.getAnalyzerOptions();
2576
9.93k
  const Decl *D = N->getLocationContext()->getDecl();
2577
9.93k
2578
9.93k
  if (AnalysisDeclContext::isInStdNamespace(D)) {
2579
15
    // Skip reports within the 'std' namespace. Although these can sometimes be
2580
15
    // the user's fault, we currently don't report them very well, and
2581
15
    // Note that this will not help for any other data structure libraries, like
2582
15
    // TR1, Boost, or llvm/ADT.
2583
15
    if (Options.ShouldSuppressFromCXXStandardLibrary) {
2584
14
      BR.markInvalid(getTag(), nullptr);
2585
14
      return;
2586
14
    } else {
2587
1
      // If the complete 'std' suppression is not enabled, suppress reports
2588
1
      // from the 'std' namespace that are known to produce false positives.
2589
1
2590
1
      // The analyzer issues a false use-after-free when std::list::pop_front
2591
1
      // or std::list::pop_back are called multiple times because we cannot
2592
1
      // reason about the internal invariants of the data structure.
2593
1
      if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2594
0
        const CXXRecordDecl *CD = MD->getParent();
2595
0
        if (CD->getName() == "list") {
2596
0
          BR.markInvalid(getTag(), nullptr);
2597
0
          return;
2598
0
        }
2599
1
      }
2600
1
2601
1
      // The analyzer issues a false positive when the constructor of
2602
1
      // std::__independent_bits_engine from algorithms is used.
2603
1
      if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2604
0
        const CXXRecordDecl *CD = MD->getParent();
2605
0
        if (CD->getName() == "__independent_bits_engine") {
2606
0
          BR.markInvalid(getTag(), nullptr);
2607
0
          return;
2608
0
        }
2609
1
      }
2610
1
2611
4
      
for (const LocationContext *LCtx = N->getLocationContext(); 1
LCtx;
2612
3
           LCtx = LCtx->getParent()) {
2613
3
        const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2614
3
        if (!MD)
2615
3
          continue;
2616
0
2617
0
        const CXXRecordDecl *CD = MD->getParent();
2618
0
        // The analyzer issues a false positive on
2619
0
        //   std::basic_string<uint8_t> v; v.push_back(1);
2620
0
        // and
2621
0
        //   std::u16string s; s += u'a';
2622
0
        // because we cannot reason about the internal invariants of the
2623
0
        // data structure.
2624
0
        if (CD->getName() == "basic_string") {
2625
0
          BR.markInvalid(getTag(), nullptr);
2626
0
          return;
2627
0
        }
2628
0
2629
0
        // The analyzer issues a false positive on
2630
0
        //    std::shared_ptr<int> p(new int(1)); p = nullptr;
2631
0
        // because it does not reason properly about temporary destructors.
2632
0
        if (CD->getName() == "shared_ptr") {
2633
0
          BR.markInvalid(getTag(), nullptr);
2634
0
          return;
2635
0
        }
2636
0
      }
2637
1
    }
2638
15
  }
2639
9.93k
2640
9.93k
  // Skip reports within the sys/queue.h macros as we do not have the ability to
2641
9.93k
  // reason about data structure shapes.
2642
9.93k
  SourceManager &SM = BRC.getSourceManager();
2643
9.91k
  FullSourceLoc Loc = BR.getLocation(SM).asLocation();
2644
10.2k
  while (Loc.isMacroID()) {
2645
378
    Loc = Loc.getSpellingLoc();
2646
378
    if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2647
2
      BR.markInvalid(getTag(), nullptr);
2648
2
      return;
2649
2
    }
2650
378
  }
2651
9.91k
}
2652
2653
//===----------------------------------------------------------------------===//
2654
// Implementation of UndefOrNullArgVisitor.
2655
//===----------------------------------------------------------------------===//
2656
2657
std::shared_ptr<PathDiagnosticPiece>
2658
UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
2659
67.7k
                                 BugReporterContext &BRC, BugReport &BR) {
2660
67.7k
  ProgramStateRef State = N->getState();
2661
67.7k
  ProgramPoint ProgLoc = N->getLocation();
2662
67.7k
2663
67.7k
  // We are only interested in visiting CallEnter nodes.
2664
67.7k
  Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2665
67.7k
  if (!CEnter)
2666
66.5k
    return nullptr;
2667
1.11k
2668
1.11k
  // Check if one of the arguments is the region the visitor is tracking.
2669
1.11k
  CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2670
1.11k
  CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2671
1.11k
  unsigned Idx = 0;
2672
1.11k
  ArrayRef<ParmVarDecl *> parms = Call->parameters();
2673
1.11k
2674
1.11k
  for (const auto ParamDecl : parms) {
2675
872
    const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2676
872
    ++Idx;
2677
872
2678
872
    // Are we tracking the argument or its subregion?
2679
872
    if ( !ArgReg || 
!R->isSubRegionOf(ArgReg->StripCasts())335
)
2680
739
      continue;
2681
133
2682
133
    // Check the function parameter type.
2683
133
    assert(ParamDecl && "Formal parameter has no decl?");
2684
133
    QualType T = ParamDecl->getType();
2685
133
2686
133
    if (!(T->isAnyPointerType() || 
T->isReferenceType()64
)) {
2687
6
      // Function can only change the value passed in by address.
2688
6
      continue;
2689
6
    }
2690
127
2691
127
    // If it is a const pointer value, the function does not intend to
2692
127
    // change the value.
2693
127
    if (T->getPointeeType().isConstQualified())
2694
21
      continue;
2695
106
2696
106
    // Mark the call site (LocationContext) as interesting if the value of the
2697
106
    // argument is undefined or '0'/'NULL'.
2698
106
    SVal BoundVal = State->getSVal(R);
2699
106
    if (BoundVal.isUndef() || 
BoundVal.isZeroConstant()18
) {
2700
97
      BR.markInteresting(CEnter->getCalleeContext());
2701
97
      return nullptr;
2702
97
    }
2703
106
  }
2704
1.11k
  
return nullptr1.01k
;
2705
1.11k
}
2706
2707
//===----------------------------------------------------------------------===//
2708
// Implementation of FalsePositiveRefutationBRVisitor.
2709
//===----------------------------------------------------------------------===//
2710
2711
FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
2712
0
    : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
2713
2714
void FalsePositiveRefutationBRVisitor::finalizeVisitor(
2715
0
    BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
2716
0
  // Collect new constraints
2717
0
  VisitNode(EndPathNode, BRC, BR);
2718
0
2719
0
  // Create a refutation manager
2720
0
  llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
2721
0
  ASTContext &Ctx = BRC.getASTContext();
2722
0
2723
0
  // Add constraints to the solver
2724
0
  for (const auto &I : Constraints) {
2725
0
    const SymbolRef Sym = I.first;
2726
0
    auto RangeIt = I.second.begin();
2727
0
2728
0
    llvm::SMTExprRef Constraints = SMTConv::getRangeExpr(
2729
0
        RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
2730
0
        /*InRange=*/true);
2731
0
    while ((++RangeIt) != I.second.end()) {
2732
0
      Constraints = RefutationSolver->mkOr(
2733
0
          Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
2734
0
                                             RangeIt->From(), RangeIt->To(),
2735
0
                                             /*InRange=*/true));
2736
0
    }
2737
0
2738
0
    RefutationSolver->addConstraint(Constraints);
2739
0
  }
2740
0
2741
0
  // And check for satisfiability
2742
0
  Optional<bool> isSat = RefutationSolver->check();
2743
0
  if (!isSat.hasValue())
2744
0
    return;
2745
0
2746
0
  if (!isSat.getValue())
2747
0
    BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
2748
0
}
2749
2750
std::shared_ptr<PathDiagnosticPiece>
2751
FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
2752
                                            BugReporterContext &,
2753
0
                                            BugReport &) {
2754
0
  // Collect new constraints
2755
0
  const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
2756
0
  ConstraintRangeTy::Factory &CF =
2757
0
      N->getState()->get_context<ConstraintRange>();
2758
0
2759
0
  // Add constraints if we don't have them yet
2760
0
  for (auto const &C : NewCs) {
2761
0
    const SymbolRef &Sym = C.first;
2762
0
    if (!Constraints.contains(Sym)) {
2763
0
      Constraints = CF.add(Constraints, Sym, C.second);
2764
0
    }
2765
0
  }
2766
0
2767
0
  return nullptr;
2768
0
}
2769
2770
void FalsePositiveRefutationBRVisitor::Profile(
2771
0
    llvm::FoldingSetNodeID &ID) const {
2772
0
  static int Tag = 0;
2773
0
  ID.AddPointer(&Tag);
2774
0
}
2775
2776
//===----------------------------------------------------------------------===//
2777
// Implementation of TagVisitor.
2778
//===----------------------------------------------------------------------===//
2779
2780
int NoteTag::Kind = 0;
2781
2782
10.0k
void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
2783
10.0k
  static int Tag = 0;
2784
10.0k
  ID.AddPointer(&Tag);
2785
10.0k
}
2786
2787
std::shared_ptr<PathDiagnosticPiece>
2788
TagVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2789
992k
                      BugReport &R) {
2790
992k
  ProgramPoint PP = N->getLocation();
2791
992k
  const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
2792
992k
  if (!T)
2793
992k
    return nullptr;
2794
156
2795
156
  if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
2796
155
    PathDiagnosticLocation Loc =
2797
155
        PathDiagnosticLocation::create(PP, BRC.getSourceManager());
2798
155
    auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
2799
155
    Piece->setPrunable(T->isPrunable());
2800
155
    return Piece;
2801
155
  }
2802
1
2803
1
  return nullptr;
2804
1
}