Coverage Report

Created: 2020-10-24 06:27

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