BugReporterVisitors.cpp revision ea7b481aa8298f1e59c4cfb64e53b38f86dec92d
1// BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- C++ -*--//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines a set of BugReporter "visitors" which can be used to
11//  enhance the diagnostics reported for a bug.
12//
13//===----------------------------------------------------------------------===//
14#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprObjC.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/raw_ostream.h"
26
27using namespace clang;
28using namespace ento;
29
30using llvm::FoldingSetNodeID;
31
32//===----------------------------------------------------------------------===//
33// Utility functions.
34//===----------------------------------------------------------------------===//
35
36bool bugreporter::isDeclRefExprToReference(const Expr *E) {
37  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
38    return DRE->getDecl()->getType()->isReferenceType();
39  }
40  return false;
41}
42
43const Expr *bugreporter::getDerefExpr(const Stmt *S) {
44  // Pattern match for a few useful cases (do something smarter later):
45  //   a[0], p->f, *p
46  const Expr *E = dyn_cast<Expr>(S);
47  if (!E)
48    return 0;
49  E = E->IgnoreParenCasts();
50
51  while (true) {
52    if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
53      assert(B->isAssignmentOp());
54      E = B->getLHS()->IgnoreParenCasts();
55      continue;
56    }
57    else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
58      if (U->getOpcode() == UO_Deref)
59        return U->getSubExpr()->IgnoreParenCasts();
60    }
61    else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
62      if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
63        return ME->getBase()->IgnoreParenCasts();
64      }
65    }
66    else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
67      return IvarRef->getBase()->IgnoreParenCasts();
68    }
69    else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
70      return AE->getBase();
71    }
72    break;
73  }
74
75  return NULL;
76}
77
78const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
79  const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
80  if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
81    return BE->getRHS();
82  return NULL;
83}
84
85const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
86  const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
87  if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
88    return RS->getRetValue();
89  return NULL;
90}
91
92//===----------------------------------------------------------------------===//
93// Definitions for bug reporter visitors.
94//===----------------------------------------------------------------------===//
95
96PathDiagnosticPiece*
97BugReporterVisitor::getEndPath(BugReporterContext &BRC,
98                               const ExplodedNode *EndPathNode,
99                               BugReport &BR) {
100  return 0;
101}
102
103PathDiagnosticPiece*
104BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
105                                      const ExplodedNode *EndPathNode,
106                                      BugReport &BR) {
107  PathDiagnosticLocation L =
108    PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
109
110  BugReport::ranges_iterator Beg, End;
111  llvm::tie(Beg, End) = BR.getRanges();
112
113  // Only add the statement itself as a range if we didn't specify any
114  // special ranges for this report.
115  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
116      BR.getDescription(),
117      Beg == End);
118  for (; Beg != End; ++Beg)
119    P->addRange(*Beg);
120
121  return P;
122}
123
124
125namespace {
126/// Emits an extra note at the return statement of an interesting stack frame.
127///
128/// The returned value is marked as an interesting value, and if it's null,
129/// adds a visitor to track where it became null.
130///
131/// This visitor is intended to be used when another visitor discovers that an
132/// interesting value comes from an inlined function call.
133class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
134  const StackFrameContext *StackFrame;
135  enum {
136    Initial,
137    MaybeUnsuppress,
138    Satisfied
139  } Mode;
140
141  bool EnableNullFPSuppression;
142
143public:
144  ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
145    : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
146
147  static void *getTag() {
148    static int Tag = 0;
149    return static_cast<void *>(&Tag);
150  }
151
152  virtual void Profile(llvm::FoldingSetNodeID &ID) const {
153    ID.AddPointer(ReturnVisitor::getTag());
154    ID.AddPointer(StackFrame);
155    ID.AddBoolean(EnableNullFPSuppression);
156  }
157
158  /// Adds a ReturnVisitor if the given statement represents a call that was
159  /// inlined.
160  ///
161  /// This will search back through the ExplodedGraph, starting from the given
162  /// node, looking for when the given statement was processed. If it turns out
163  /// the statement is a call that was inlined, we add the visitor to the
164  /// bug report, so it can print a note later.
165  static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
166                                    BugReport &BR,
167                                    bool InEnableNullFPSuppression) {
168    if (!CallEvent::isCallStmt(S))
169      return;
170
171    // First, find when we processed the statement.
172    do {
173      if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
174        if (CEE->getCalleeContext()->getCallSite() == S)
175          break;
176      if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
177        if (SP->getStmt() == S)
178          break;
179
180      Node = Node->getFirstPred();
181    } while (Node);
182
183    // Next, step over any post-statement checks.
184    while (Node && Node->getLocation().getAs<PostStmt>())
185      Node = Node->getFirstPred();
186    if (!Node)
187      return;
188
189    // Finally, see if we inlined the call.
190    Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
191    if (!CEE)
192      return;
193
194    const StackFrameContext *CalleeContext = CEE->getCalleeContext();
195    if (CalleeContext->getCallSite() != S)
196      return;
197
198    // Check the return value.
199    ProgramStateRef State = Node->getState();
200    SVal RetVal = State->getSVal(S, Node->getLocationContext());
201
202    // Handle cases where a reference is returned and then immediately used.
203    if (cast<Expr>(S)->isGLValue())
204      if (Optional<Loc> LValue = RetVal.getAs<Loc>())
205        RetVal = State->getSVal(*LValue);
206
207    // See if the return value is NULL. If so, suppress the report.
208    SubEngine *Eng = State->getStateManager().getOwningEngine();
209    assert(Eng && "Cannot file a bug report without an owning engine");
210    AnalyzerOptions &Options = Eng->getAnalysisManager().options;
211
212    bool EnableNullFPSuppression = false;
213    if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
214      if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
215        EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
216
217    BR.markInteresting(CalleeContext);
218    BR.addVisitor(new ReturnVisitor(CalleeContext, EnableNullFPSuppression));
219  }
220
221  /// Returns true if any counter-suppression heuristics are enabled for
222  /// ReturnVisitor.
223  static bool hasCounterSuppression(AnalyzerOptions &Options) {
224    return Options.shouldAvoidSuppressingNullArgumentPaths();
225  }
226
227  PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
228                                        const ExplodedNode *PrevN,
229                                        BugReporterContext &BRC,
230                                        BugReport &BR) {
231    // Only print a message at the interesting return statement.
232    if (N->getLocationContext() != StackFrame)
233      return 0;
234
235    Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
236    if (!SP)
237      return 0;
238
239    const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
240    if (!Ret)
241      return 0;
242
243    // Okay, we're at the right return statement, but do we have the return
244    // value available?
245    ProgramStateRef State = N->getState();
246    SVal V = State->getSVal(Ret, StackFrame);
247    if (V.isUnknownOrUndef())
248      return 0;
249
250    // Don't print any more notes after this one.
251    Mode = Satisfied;
252
253    const Expr *RetE = Ret->getRetValue();
254    assert(RetE && "Tracking a return value for a void function");
255
256    // Handle cases where a reference is returned and then immediately used.
257    Optional<Loc> LValue;
258    if (RetE->isGLValue()) {
259      if ((LValue = V.getAs<Loc>())) {
260        SVal RValue = State->getRawSVal(*LValue, RetE->getType());
261        if (RValue.getAs<DefinedSVal>())
262          V = RValue;
263      }
264    }
265
266    // Ignore aggregate rvalues.
267    if (V.getAs<nonloc::LazyCompoundVal>() ||
268        V.getAs<nonloc::CompoundVal>())
269      return 0;
270
271    RetE = RetE->IgnoreParenCasts();
272
273    // If we can't prove the return value is 0, just mark it interesting, and
274    // make sure to track it into any further inner functions.
275    if (!State->isNull(V).isConstrainedTrue()) {
276      BR.markInteresting(V);
277      ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
278                                           EnableNullFPSuppression);
279      return 0;
280    }
281
282    // If we're returning 0, we should track where that 0 came from.
283    bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
284                                       EnableNullFPSuppression);
285
286    // Build an appropriate message based on the return value.
287    SmallString<64> Msg;
288    llvm::raw_svector_ostream Out(Msg);
289
290    if (V.getAs<Loc>()) {
291      // If we have counter-suppression enabled, make sure we keep visiting
292      // future nodes. We want to emit a path note as well, in case
293      // the report is resurrected as valid later on.
294      ExprEngine &Eng = BRC.getBugReporter().getEngine();
295      AnalyzerOptions &Options = Eng.getAnalysisManager().options;
296      if (EnableNullFPSuppression && hasCounterSuppression(Options))
297        Mode = MaybeUnsuppress;
298
299      if (RetE->getType()->isObjCObjectPointerType())
300        Out << "Returning nil";
301      else
302        Out << "Returning null pointer";
303    } else {
304      Out << "Returning zero";
305    }
306
307    if (LValue) {
308      if (const MemRegion *MR = LValue->getAsRegion()) {
309        if (MR->canPrintPretty()) {
310          Out << " (reference to '";
311          MR->printPretty(Out);
312          Out << "')";
313        }
314      }
315    } else {
316      // FIXME: We should have a more generalized location printing mechanism.
317      if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
318        if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
319          Out << " (loaded from '" << *DD << "')";
320    }
321
322    PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
323    return new PathDiagnosticEventPiece(L, Out.str());
324  }
325
326  PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
327                                                const ExplodedNode *PrevN,
328                                                BugReporterContext &BRC,
329                                                BugReport &BR) {
330#ifndef NDEBUG
331    ExprEngine &Eng = BRC.getBugReporter().getEngine();
332    AnalyzerOptions &Options = Eng.getAnalysisManager().options;
333    assert(hasCounterSuppression(Options));
334#endif
335
336    // Are we at the entry node for this call?
337    Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
338    if (!CE)
339      return 0;
340
341    if (CE->getCalleeContext() != StackFrame)
342      return 0;
343
344    Mode = Satisfied;
345
346    // Don't automatically suppress a report if one of the arguments is
347    // known to be a null pointer. Instead, start tracking /that/ null
348    // value back to its origin.
349    ProgramStateManager &StateMgr = BRC.getStateManager();
350    CallEventManager &CallMgr = StateMgr.getCallEventManager();
351
352    ProgramStateRef State = N->getState();
353    CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
354    for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
355      Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
356      if (!ArgV)
357        continue;
358
359      const Expr *ArgE = Call->getArgExpr(I);
360      if (!ArgE)
361        continue;
362
363      // Is it possible for this argument to be non-null?
364      if (!State->isNull(*ArgV).isConstrainedTrue())
365        continue;
366
367      if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
368                                             EnableNullFPSuppression))
369        BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
370
371      // If we /can't/ track the null pointer, we should err on the side of
372      // false negatives, and continue towards marking this report invalid.
373      // (We will still look at the other arguments, though.)
374    }
375
376    return 0;
377  }
378
379  PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
380                                 const ExplodedNode *PrevN,
381                                 BugReporterContext &BRC,
382                                 BugReport &BR) {
383    switch (Mode) {
384    case Initial:
385      return visitNodeInitial(N, PrevN, BRC, BR);
386    case MaybeUnsuppress:
387      return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
388    case Satisfied:
389      return 0;
390    }
391
392    llvm_unreachable("Invalid visit mode!");
393  }
394
395  PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
396                                  const ExplodedNode *N,
397                                  BugReport &BR) {
398    if (EnableNullFPSuppression)
399      BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
400    return 0;
401  }
402};
403} // end anonymous namespace
404
405
406void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
407  static int tag = 0;
408  ID.AddPointer(&tag);
409  ID.AddPointer(R);
410  ID.Add(V);
411  ID.AddBoolean(EnableNullFPSuppression);
412}
413
414PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
415                                                       const ExplodedNode *Pred,
416                                                       BugReporterContext &BRC,
417                                                       BugReport &BR) {
418
419  if (Satisfied)
420    return NULL;
421
422  const ExplodedNode *StoreSite = 0;
423  const Expr *InitE = 0;
424  bool IsParam = false;
425
426  // First see if we reached the declaration of the region.
427  if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
428    if (Optional<PostStmt> P = Pred->getLocationAs<PostStmt>()) {
429      if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
430        if (DS->getSingleDecl() == VR->getDecl()) {
431          StoreSite = Pred;
432          InitE = VR->getDecl()->getInit();
433        }
434      }
435    }
436  }
437
438  // If this is a post initializer expression, initializing the region, we
439  // should track the initializer expression.
440  if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
441    const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
442    if (FieldReg && FieldReg == R) {
443      StoreSite = Pred;
444      InitE = PIP->getInitializer()->getInit();
445    }
446  }
447
448  // Otherwise, see if this is the store site:
449  // (1) Succ has this binding and Pred does not, i.e. this is
450  //     where the binding first occurred.
451  // (2) Succ has this binding and is a PostStore node for this region, i.e.
452  //     the same binding was re-assigned here.
453  if (!StoreSite) {
454    if (Succ->getState()->getSVal(R) != V)
455      return NULL;
456
457    if (Pred->getState()->getSVal(R) == V) {
458      Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
459      if (!PS || PS->getLocationValue() != R)
460        return NULL;
461    }
462
463    StoreSite = Succ;
464
465    // If this is an assignment expression, we can track the value
466    // being assigned.
467    if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
468      if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
469        if (BO->isAssignmentOp())
470          InitE = BO->getRHS();
471
472    // If this is a call entry, the variable should be a parameter.
473    // FIXME: Handle CXXThisRegion as well. (This is not a priority because
474    // 'this' should never be NULL, but this visitor isn't just for NULL and
475    // UndefinedVal.)
476    if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
477      if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
478        const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
479
480        ProgramStateManager &StateMgr = BRC.getStateManager();
481        CallEventManager &CallMgr = StateMgr.getCallEventManager();
482
483        CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
484                                                Succ->getState());
485        InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
486        IsParam = true;
487      }
488    }
489
490    // If this is a CXXTempObjectRegion, the Expr responsible for its creation
491    // is wrapped inside of it.
492    if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
493      InitE = TmpR->getExpr();
494  }
495
496  if (!StoreSite)
497    return NULL;
498  Satisfied = true;
499
500  // If we have an expression that provided the value, try to track where it
501  // came from.
502  if (InitE) {
503    if (V.isUndef() || V.getAs<loc::ConcreteInt>()) {
504      if (!IsParam)
505        InitE = InitE->IgnoreParenCasts();
506      bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
507                                         EnableNullFPSuppression);
508    } else {
509      ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
510                                           BR, EnableNullFPSuppression);
511    }
512  }
513
514  if (!R->canPrintPretty())
515    return 0;
516
517  // Okay, we've found the binding. Emit an appropriate message.
518  SmallString<256> sbuf;
519  llvm::raw_svector_ostream os(sbuf);
520
521  if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
522    const Stmt *S = PS->getStmt();
523    const char *action = 0;
524    const DeclStmt *DS = dyn_cast<DeclStmt>(S);
525    const VarRegion *VR = dyn_cast<VarRegion>(R);
526
527    if (DS) {
528      action = "initialized to ";
529    } else if (isa<BlockExpr>(S)) {
530      action = "captured by block as ";
531      if (VR) {
532        // See if we can get the BlockVarRegion.
533        ProgramStateRef State = StoreSite->getState();
534        SVal V = State->getSVal(S, PS->getLocationContext());
535        if (const BlockDataRegion *BDR =
536              dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
537          if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
538            if (Optional<KnownSVal> KV =
539                State->getSVal(OriginalR).getAs<KnownSVal>())
540              BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR,
541                                                      EnableNullFPSuppression));
542          }
543        }
544      }
545    }
546
547    if (action) {
548      if (!R)
549        return 0;
550
551      os << '\'';
552      R->printPretty(os);
553      os << "' ";
554
555      if (V.getAs<loc::ConcreteInt>()) {
556        bool b = false;
557        if (R->isBoundable()) {
558          if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
559            if (TR->getValueType()->isObjCObjectPointerType()) {
560              os << action << "nil";
561              b = true;
562            }
563          }
564        }
565
566        if (!b)
567          os << action << "a null pointer value";
568      } else if (Optional<nonloc::ConcreteInt> CVal =
569                     V.getAs<nonloc::ConcreteInt>()) {
570        os << action << CVal->getValue();
571      }
572      else if (DS) {
573        if (V.isUndef()) {
574          if (isa<VarRegion>(R)) {
575            const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
576            if (VD->getInit())
577              os << "initialized to a garbage value";
578            else
579              os << "declared without an initial value";
580          }
581        }
582        else {
583          os << "initialized here";
584        }
585      }
586    }
587  } else if (StoreSite->getLocation().getAs<CallEnter>()) {
588    if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
589      const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
590
591      os << "Passing ";
592
593      if (V.getAs<loc::ConcreteInt>()) {
594        if (Param->getType()->isObjCObjectPointerType())
595          os << "nil object reference";
596        else
597          os << "null pointer value";
598      } else if (V.isUndef()) {
599        os << "uninitialized value";
600      } else if (Optional<nonloc::ConcreteInt> CI =
601                     V.getAs<nonloc::ConcreteInt>()) {
602        os << "the value " << CI->getValue();
603      } else {
604        os << "value";
605      }
606
607      // Printed parameter indexes are 1-based, not 0-based.
608      unsigned Idx = Param->getFunctionScopeIndex() + 1;
609      os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
610
611      R->printPretty(os);
612      os << '\'';
613    }
614  }
615
616  if (os.str().empty()) {
617    if (V.getAs<loc::ConcreteInt>()) {
618      bool b = false;
619      if (R->isBoundable()) {
620        if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
621          if (TR->getValueType()->isObjCObjectPointerType()) {
622            os << "nil object reference stored to ";
623            b = true;
624          }
625        }
626      }
627
628      if (!b)
629        os << "Null pointer value stored to ";
630    }
631    else if (V.isUndef()) {
632      os << "Uninitialized value stored to ";
633    } else if (Optional<nonloc::ConcreteInt> CV =
634                   V.getAs<nonloc::ConcreteInt>()) {
635      os << "The value " << CV->getValue() << " is assigned to ";
636    }
637    else
638      os << "Value assigned to ";
639
640    os << '\'';
641    R->printPretty(os);
642    os << '\'';
643  }
644
645  // Construct a new PathDiagnosticPiece.
646  ProgramPoint P = StoreSite->getLocation();
647  PathDiagnosticLocation L;
648  if (P.getAs<CallEnter>() && InitE)
649    L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
650                               P.getLocationContext());
651  else
652    L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
653  if (!L.isValid())
654    return NULL;
655  return new PathDiagnosticEventPiece(L, os.str());
656}
657
658void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
659  static int tag = 0;
660  ID.AddPointer(&tag);
661  ID.AddBoolean(Assumption);
662  ID.Add(Constraint);
663}
664
665/// Return the tag associated with this visitor.  This tag will be used
666/// to make all PathDiagnosticPieces created by this visitor.
667const char *TrackConstraintBRVisitor::getTag() {
668  return "TrackConstraintBRVisitor";
669}
670
671bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
672  if (IsZeroCheck)
673    return N->getState()->isNull(Constraint).isUnderconstrained();
674  return N->getState()->assume(Constraint, !Assumption);
675}
676
677PathDiagnosticPiece *
678TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
679                                    const ExplodedNode *PrevN,
680                                    BugReporterContext &BRC,
681                                    BugReport &BR) {
682  if (IsSatisfied)
683    return NULL;
684
685  // Check if in the previous state it was feasible for this constraint
686  // to *not* be true.
687  if (isUnderconstrained(PrevN)) {
688
689    IsSatisfied = true;
690
691    // As a sanity check, make sure that the negation of the constraint
692    // was infeasible in the current state.  If it is feasible, we somehow
693    // missed the transition point.
694    if (isUnderconstrained(N))
695      return NULL;
696
697    // We found the transition point for the constraint.  We now need to
698    // pretty-print the constraint. (work-in-progress)
699    SmallString<64> sbuf;
700    llvm::raw_svector_ostream os(sbuf);
701
702    if (Constraint.getAs<Loc>()) {
703      os << "Assuming pointer value is ";
704      os << (Assumption ? "non-null" : "null");
705    }
706
707    if (os.str().empty())
708      return NULL;
709
710    // Construct a new PathDiagnosticPiece.
711    ProgramPoint P = N->getLocation();
712    PathDiagnosticLocation L =
713      PathDiagnosticLocation::create(P, BRC.getSourceManager());
714    if (!L.isValid())
715      return NULL;
716
717    PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
718    X->setTag(getTag());
719    return X;
720  }
721
722  return NULL;
723}
724
725SuppressInlineDefensiveChecksVisitor::
726SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
727  : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
728
729    // Check if the visitor is disabled.
730    SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
731    assert(Eng && "Cannot file a bug report without an owning engine");
732    AnalyzerOptions &Options = Eng->getAnalysisManager().options;
733    if (!Options.shouldSuppressInlinedDefensiveChecks())
734      IsSatisfied = true;
735
736    assert(N->getState()->isNull(V).isConstrainedTrue() &&
737           "The visitor only tracks the cases where V is constrained to 0");
738}
739
740void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
741  static int id = 0;
742  ID.AddPointer(&id);
743  ID.Add(V);
744}
745
746const char *SuppressInlineDefensiveChecksVisitor::getTag() {
747  return "IDCVisitor";
748}
749
750PathDiagnosticPiece *
751SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
752                                                const ExplodedNode *Pred,
753                                                BugReporterContext &BRC,
754                                                BugReport &BR) {
755  if (IsSatisfied)
756    return 0;
757
758  // Start tracking after we see the first state in which the value is null.
759  if (!IsTrackingTurnedOn)
760    if (Succ->getState()->isNull(V).isConstrainedTrue())
761      IsTrackingTurnedOn = true;
762  if (!IsTrackingTurnedOn)
763    return 0;
764
765  // Check if in the previous state it was feasible for this value
766  // to *not* be null.
767  if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
768    IsSatisfied = true;
769
770    assert(Succ->getState()->isNull(V).isConstrainedTrue());
771
772    // Check if this is inlined defensive checks.
773    const LocationContext *CurLC =Succ->getLocationContext();
774    const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
775    if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
776      BR.markInvalid("Suppress IDC", CurLC);
777  }
778  return 0;
779}
780
781static const MemRegion *getLocationRegionIfReference(const Expr *E,
782                                                     const ExplodedNode *N) {
783  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
784    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
785      if (!VD->getType()->isReferenceType())
786        return 0;
787      ProgramStateManager &StateMgr = N->getState()->getStateManager();
788      MemRegionManager &MRMgr = StateMgr.getRegionManager();
789      return MRMgr.getVarRegion(VD, N->getLocationContext());
790    }
791  }
792
793  // FIXME: This does not handle other kinds of null references,
794  // for example, references from FieldRegions:
795  //   struct Wrapper { int &ref; };
796  //   Wrapper w = { *(int *)0 };
797  //   w.ref = 1;
798
799  return 0;
800}
801
802static const Expr *peelOffOuterExpr(const Expr *Ex,
803                                    const ExplodedNode *N) {
804  Ex = Ex->IgnoreParenCasts();
805  if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
806    return peelOffOuterExpr(EWC->getSubExpr(), N);
807  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
808    return peelOffOuterExpr(OVE->getSourceExpr(), N);
809
810  // Peel off the ternary operator.
811  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
812    // Find a node where the branching occured and find out which branch
813    // we took (true/false) by looking at the ExplodedGraph.
814    const ExplodedNode *NI = N;
815    do {
816      ProgramPoint ProgPoint = NI->getLocation();
817      if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
818        const CFGBlock *srcBlk = BE->getSrc();
819        if (const Stmt *term = srcBlk->getTerminator()) {
820          if (term == CO) {
821            bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
822            if (TookTrueBranch)
823              return peelOffOuterExpr(CO->getTrueExpr(), N);
824            else
825              return peelOffOuterExpr(CO->getFalseExpr(), N);
826          }
827        }
828      }
829      NI = NI->getFirstPred();
830    } while (NI);
831  }
832  return Ex;
833}
834
835bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
836                                        const Stmt *S,
837                                        BugReport &report, bool IsArg,
838                                        bool EnableNullFPSuppression) {
839  if (!S || !N)
840    return false;
841
842  if (const Expr *Ex = dyn_cast<Expr>(S)) {
843    Ex = Ex->IgnoreParenCasts();
844    const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
845    if (Ex != PeeledEx)
846      S = PeeledEx;
847  }
848
849  const Expr *Inner = 0;
850  if (const Expr *Ex = dyn_cast<Expr>(S)) {
851    Ex = Ex->IgnoreParenCasts();
852    if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
853      Inner = Ex;
854  }
855
856  if (IsArg) {
857    assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
858  } else {
859    // Walk through nodes until we get one that matches the statement exactly.
860    // Alternately, if we hit a known lvalue for the statement, we know we've
861    // gone too far (though we can likely track the lvalue better anyway).
862    do {
863      const ProgramPoint &pp = N->getLocation();
864      if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
865        if (ps->getStmt() == S || ps->getStmt() == Inner)
866          break;
867      } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
868        if (CEE->getCalleeContext()->getCallSite() == S ||
869            CEE->getCalleeContext()->getCallSite() == Inner)
870          break;
871      }
872      N = N->getFirstPred();
873    } while (N);
874
875    if (!N)
876      return false;
877  }
878
879  ProgramStateRef state = N->getState();
880
881  // The message send could be nil due to the receiver being nil.
882  // At this point in the path, the receiver should be live since we are at the
883  // message send expr. If it is nil, start tracking it.
884  if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
885    trackNullOrUndefValue(N, Receiver, report, IsArg, EnableNullFPSuppression);
886
887
888  // See if the expression we're interested refers to a variable.
889  // If so, we can track both its contents and constraints on its value.
890  if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
891    const MemRegion *R = 0;
892
893    // Find the ExplodedNode where the lvalue (the value of 'Ex')
894    // was computed.  We need this for getting the location value.
895    const ExplodedNode *LVNode = N;
896    while (LVNode) {
897      if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
898        if (P->getStmt() == Inner)
899          break;
900      }
901      LVNode = LVNode->getFirstPred();
902    }
903    assert(LVNode && "Unable to find the lvalue node.");
904    ProgramStateRef LVState = LVNode->getState();
905    SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
906
907    if (LVState->isNull(LVal).isConstrainedTrue()) {
908      // In case of C++ references, we want to differentiate between a null
909      // reference and reference to null pointer.
910      // If the LVal is null, check if we are dealing with null reference.
911      // For those, we want to track the location of the reference.
912      if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
913        R = RR;
914    } else {
915      R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
916
917      // If this is a C++ reference to a null pointer, we are tracking the
918      // pointer. In additon, we should find the store at which the reference
919      // got initialized.
920      if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
921        if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
922          report.addVisitor(new FindLastStoreBRVisitor(*KV, RR,
923                                                      EnableNullFPSuppression));
924      }
925    }
926
927    if (R) {
928      // Mark both the variable region and its contents as interesting.
929      SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
930
931      report.markInteresting(R);
932      report.markInteresting(V);
933      report.addVisitor(new UndefOrNullArgVisitor(R));
934
935      // If the contents are symbolic, find out when they became null.
936      if (V.getAsLocSymbol()) {
937        BugReporterVisitor *ConstraintTracker =
938          new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
939        report.addVisitor(ConstraintTracker);
940
941        // Add visitor, which will suppress inline defensive checks.
942        if (LVState->isNull(V).isConstrainedTrue() &&
943            EnableNullFPSuppression) {
944          BugReporterVisitor *IDCSuppressor =
945            new SuppressInlineDefensiveChecksVisitor(V.castAs<DefinedSVal>(),
946                                                     LVNode);
947          report.addVisitor(IDCSuppressor);
948        }
949      }
950
951      if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
952        report.addVisitor(new FindLastStoreBRVisitor(*KV, R,
953                                                     EnableNullFPSuppression));
954      return true;
955    }
956  }
957
958  // If the expression is not an "lvalue expression", we can still
959  // track the constraints on its contents.
960  SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
961
962  // If the value came from an inlined function call, we should at least make
963  // sure that function isn't pruned in our output.
964  if (const Expr *E = dyn_cast<Expr>(S))
965    S = E->IgnoreParenCasts();
966
967  ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
968
969  // Uncomment this to find cases where we aren't properly getting the
970  // base value that was dereferenced.
971  // assert(!V.isUnknownOrUndef());
972  // Is it a symbolic value?
973  if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
974    // At this point we are dealing with the region's LValue.
975    // However, if the rvalue is a symbolic region, we should track it as well.
976    SVal RVal = state->getSVal(L->getRegion());
977    const MemRegion *RegionRVal = RVal.getAsRegion();
978    report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
979
980    if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
981      report.markInteresting(RegionRVal);
982      report.addVisitor(new TrackConstraintBRVisitor(
983        loc::MemRegionVal(RegionRVal), false));
984    }
985  }
986
987  return true;
988}
989
990const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
991                                                 const ExplodedNode *N) {
992  const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
993  if (!ME)
994    return 0;
995  if (const Expr *Receiver = ME->getInstanceReceiver()) {
996    ProgramStateRef state = N->getState();
997    SVal V = state->getSVal(Receiver, N->getLocationContext());
998    if (state->isNull(V).isConstrainedTrue())
999      return Receiver;
1000  }
1001  return 0;
1002}
1003
1004PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1005                                                     const ExplodedNode *PrevN,
1006                                                     BugReporterContext &BRC,
1007                                                     BugReport &BR) {
1008  Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1009  if (!P)
1010    return 0;
1011
1012  const Expr *Receiver = getNilReceiver(P->getStmt(), N);
1013  if (!Receiver)
1014    return 0;
1015
1016  // The receiver was nil, and hence the method was skipped.
1017  // Register a BugReporterVisitor to issue a message telling us how
1018  // the receiver was null.
1019  bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1020                                     /*EnableNullFPSuppression*/ false);
1021  // Issue a message saying that the method was skipped.
1022  PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1023                                     N->getLocationContext());
1024  return new PathDiagnosticEventPiece(L, "No method is called "
1025      "because the receiver is nil");
1026}
1027
1028// Registers every VarDecl inside a Stmt with a last store visitor.
1029void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1030                                                const Stmt *S,
1031                                                bool EnableNullFPSuppression) {
1032  const ExplodedNode *N = BR.getErrorNode();
1033  std::deque<const Stmt *> WorkList;
1034  WorkList.push_back(S);
1035
1036  while (!WorkList.empty()) {
1037    const Stmt *Head = WorkList.front();
1038    WorkList.pop_front();
1039
1040    ProgramStateRef state = N->getState();
1041    ProgramStateManager &StateMgr = state->getStateManager();
1042
1043    if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1044      if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1045        const VarRegion *R =
1046        StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1047
1048        // What did we load?
1049        SVal V = state->getSVal(S, N->getLocationContext());
1050
1051        if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1052          // Register a new visitor with the BugReport.
1053          BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R,
1054                                                   EnableNullFPSuppression));
1055        }
1056      }
1057    }
1058
1059    for (Stmt::const_child_iterator I = Head->child_begin();
1060        I != Head->child_end(); ++I)
1061      WorkList.push_back(*I);
1062  }
1063}
1064
1065//===----------------------------------------------------------------------===//
1066// Visitor that tries to report interesting diagnostics from conditions.
1067//===----------------------------------------------------------------------===//
1068
1069/// Return the tag associated with this visitor.  This tag will be used
1070/// to make all PathDiagnosticPieces created by this visitor.
1071const char *ConditionBRVisitor::getTag() {
1072  return "ConditionBRVisitor";
1073}
1074
1075PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1076                                                   const ExplodedNode *Prev,
1077                                                   BugReporterContext &BRC,
1078                                                   BugReport &BR) {
1079  PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1080  if (piece) {
1081    piece->setTag(getTag());
1082    if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1083      ev->setPrunable(true, /* override */ false);
1084  }
1085  return piece;
1086}
1087
1088PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1089                                                       const ExplodedNode *Prev,
1090                                                       BugReporterContext &BRC,
1091                                                       BugReport &BR) {
1092
1093  ProgramPoint progPoint = N->getLocation();
1094  ProgramStateRef CurrentState = N->getState();
1095  ProgramStateRef PrevState = Prev->getState();
1096
1097  // Compare the GDMs of the state, because that is where constraints
1098  // are managed.  Note that ensure that we only look at nodes that
1099  // were generated by the analyzer engine proper, not checkers.
1100  if (CurrentState->getGDM().getRoot() ==
1101      PrevState->getGDM().getRoot())
1102    return 0;
1103
1104  // If an assumption was made on a branch, it should be caught
1105  // here by looking at the state transition.
1106  if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1107    const CFGBlock *srcBlk = BE->getSrc();
1108    if (const Stmt *term = srcBlk->getTerminator())
1109      return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1110    return 0;
1111  }
1112
1113  if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1114    // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1115    // violation.
1116    const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1117      cast<GRBugReporter>(BRC.getBugReporter()).
1118        getEngine().geteagerlyAssumeBinOpBifurcationTags();
1119
1120    const ProgramPointTag *tag = PS->getTag();
1121    if (tag == tags.first)
1122      return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1123                           BRC, BR, N);
1124    if (tag == tags.second)
1125      return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1126                           BRC, BR, N);
1127
1128    return 0;
1129  }
1130
1131  return 0;
1132}
1133
1134PathDiagnosticPiece *
1135ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1136                                    const ExplodedNode *N,
1137                                    const CFGBlock *srcBlk,
1138                                    const CFGBlock *dstBlk,
1139                                    BugReport &R,
1140                                    BugReporterContext &BRC) {
1141  const Expr *Cond = 0;
1142
1143  switch (Term->getStmtClass()) {
1144  default:
1145    return 0;
1146  case Stmt::IfStmtClass:
1147    Cond = cast<IfStmt>(Term)->getCond();
1148    break;
1149  case Stmt::ConditionalOperatorClass:
1150    Cond = cast<ConditionalOperator>(Term)->getCond();
1151    break;
1152  }
1153
1154  assert(Cond);
1155  assert(srcBlk->succ_size() == 2);
1156  const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1157  return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1158}
1159
1160PathDiagnosticPiece *
1161ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1162                                  bool tookTrue,
1163                                  BugReporterContext &BRC,
1164                                  BugReport &R,
1165                                  const ExplodedNode *N) {
1166
1167  const Expr *Ex = Cond;
1168
1169  while (true) {
1170    Ex = Ex->IgnoreParenCasts();
1171    switch (Ex->getStmtClass()) {
1172      default:
1173        return 0;
1174      case Stmt::BinaryOperatorClass:
1175        return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1176                             R, N);
1177      case Stmt::DeclRefExprClass:
1178        return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1179                             R, N);
1180      case Stmt::UnaryOperatorClass: {
1181        const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1182        if (UO->getOpcode() == UO_LNot) {
1183          tookTrue = !tookTrue;
1184          Ex = UO->getSubExpr();
1185          continue;
1186        }
1187        return 0;
1188      }
1189    }
1190  }
1191}
1192
1193bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1194                                      BugReporterContext &BRC,
1195                                      BugReport &report,
1196                                      const ExplodedNode *N,
1197                                      Optional<bool> &prunable) {
1198  const Expr *OriginalExpr = Ex;
1199  Ex = Ex->IgnoreParenCasts();
1200
1201  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1202    const bool quotes = isa<VarDecl>(DR->getDecl());
1203    if (quotes) {
1204      Out << '\'';
1205      const LocationContext *LCtx = N->getLocationContext();
1206      const ProgramState *state = N->getState().getPtr();
1207      if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1208                                                LCtx).getAsRegion()) {
1209        if (report.isInteresting(R))
1210          prunable = false;
1211        else {
1212          const ProgramState *state = N->getState().getPtr();
1213          SVal V = state->getSVal(R);
1214          if (report.isInteresting(V))
1215            prunable = false;
1216        }
1217      }
1218    }
1219    Out << DR->getDecl()->getDeclName().getAsString();
1220    if (quotes)
1221      Out << '\'';
1222    return quotes;
1223  }
1224
1225  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1226    QualType OriginalTy = OriginalExpr->getType();
1227    if (OriginalTy->isPointerType()) {
1228      if (IL->getValue() == 0) {
1229        Out << "null";
1230        return false;
1231      }
1232    }
1233    else if (OriginalTy->isObjCObjectPointerType()) {
1234      if (IL->getValue() == 0) {
1235        Out << "nil";
1236        return false;
1237      }
1238    }
1239
1240    Out << IL->getValue();
1241    return false;
1242  }
1243
1244  return false;
1245}
1246
1247PathDiagnosticPiece *
1248ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1249                                  const BinaryOperator *BExpr,
1250                                  const bool tookTrue,
1251                                  BugReporterContext &BRC,
1252                                  BugReport &R,
1253                                  const ExplodedNode *N) {
1254
1255  bool shouldInvert = false;
1256  Optional<bool> shouldPrune;
1257
1258  SmallString<128> LhsString, RhsString;
1259  {
1260    llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1261    const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1262                                       shouldPrune);
1263    const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1264                                       shouldPrune);
1265
1266    shouldInvert = !isVarLHS && isVarRHS;
1267  }
1268
1269  BinaryOperator::Opcode Op = BExpr->getOpcode();
1270
1271  if (BinaryOperator::isAssignmentOp(Op)) {
1272    // For assignment operators, all that we care about is that the LHS
1273    // evaluates to "true" or "false".
1274    return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1275                                  BRC, R, N);
1276  }
1277
1278  // For non-assignment operations, we require that we can understand
1279  // both the LHS and RHS.
1280  if (LhsString.empty() || RhsString.empty())
1281    return 0;
1282
1283  // Should we invert the strings if the LHS is not a variable name?
1284  SmallString<256> buf;
1285  llvm::raw_svector_ostream Out(buf);
1286  Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1287
1288  // Do we need to invert the opcode?
1289  if (shouldInvert)
1290    switch (Op) {
1291      default: break;
1292      case BO_LT: Op = BO_GT; break;
1293      case BO_GT: Op = BO_LT; break;
1294      case BO_LE: Op = BO_GE; break;
1295      case BO_GE: Op = BO_LE; break;
1296    }
1297
1298  if (!tookTrue)
1299    switch (Op) {
1300      case BO_EQ: Op = BO_NE; break;
1301      case BO_NE: Op = BO_EQ; break;
1302      case BO_LT: Op = BO_GE; break;
1303      case BO_GT: Op = BO_LE; break;
1304      case BO_LE: Op = BO_GT; break;
1305      case BO_GE: Op = BO_LT; break;
1306      default:
1307        return 0;
1308    }
1309
1310  switch (Op) {
1311    case BO_EQ:
1312      Out << "equal to ";
1313      break;
1314    case BO_NE:
1315      Out << "not equal to ";
1316      break;
1317    default:
1318      Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1319      break;
1320  }
1321
1322  Out << (shouldInvert ? LhsString : RhsString);
1323  const LocationContext *LCtx = N->getLocationContext();
1324  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1325  PathDiagnosticEventPiece *event =
1326    new PathDiagnosticEventPiece(Loc, Out.str());
1327  if (shouldPrune.hasValue())
1328    event->setPrunable(shouldPrune.getValue());
1329  return event;
1330}
1331
1332PathDiagnosticPiece *
1333ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1334                                           const Expr *CondVarExpr,
1335                                           const bool tookTrue,
1336                                           BugReporterContext &BRC,
1337                                           BugReport &report,
1338                                           const ExplodedNode *N) {
1339  // FIXME: If there's already a constraint tracker for this variable,
1340  // we shouldn't emit anything here (c.f. the double note in
1341  // test/Analysis/inlining/path-notes.c)
1342  SmallString<256> buf;
1343  llvm::raw_svector_ostream Out(buf);
1344  Out << "Assuming " << LhsString << " is ";
1345
1346  QualType Ty = CondVarExpr->getType();
1347
1348  if (Ty->isPointerType())
1349    Out << (tookTrue ? "not null" : "null");
1350  else if (Ty->isObjCObjectPointerType())
1351    Out << (tookTrue ? "not nil" : "nil");
1352  else if (Ty->isBooleanType())
1353    Out << (tookTrue ? "true" : "false");
1354  else if (Ty->isIntegerType())
1355    Out << (tookTrue ? "non-zero" : "zero");
1356  else
1357    return 0;
1358
1359  const LocationContext *LCtx = N->getLocationContext();
1360  PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1361  PathDiagnosticEventPiece *event =
1362    new PathDiagnosticEventPiece(Loc, Out.str());
1363
1364  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1365    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1366      const ProgramState *state = N->getState().getPtr();
1367      if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1368        if (report.isInteresting(R))
1369          event->setPrunable(false);
1370      }
1371    }
1372  }
1373
1374  return event;
1375}
1376
1377PathDiagnosticPiece *
1378ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1379                                  const DeclRefExpr *DR,
1380                                  const bool tookTrue,
1381                                  BugReporterContext &BRC,
1382                                  BugReport &report,
1383                                  const ExplodedNode *N) {
1384
1385  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1386  if (!VD)
1387    return 0;
1388
1389  SmallString<256> Buf;
1390  llvm::raw_svector_ostream Out(Buf);
1391
1392  Out << "Assuming '";
1393  VD->getDeclName().printName(Out);
1394  Out << "' is ";
1395
1396  QualType VDTy = VD->getType();
1397
1398  if (VDTy->isPointerType())
1399    Out << (tookTrue ? "non-null" : "null");
1400  else if (VDTy->isObjCObjectPointerType())
1401    Out << (tookTrue ? "non-nil" : "nil");
1402  else if (VDTy->isScalarType())
1403    Out << (tookTrue ? "not equal to 0" : "0");
1404  else
1405    return 0;
1406
1407  const LocationContext *LCtx = N->getLocationContext();
1408  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1409  PathDiagnosticEventPiece *event =
1410    new PathDiagnosticEventPiece(Loc, Out.str());
1411
1412  const ProgramState *state = N->getState().getPtr();
1413  if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1414    if (report.isInteresting(R))
1415      event->setPrunable(false);
1416    else {
1417      SVal V = state->getSVal(R);
1418      if (report.isInteresting(V))
1419        event->setPrunable(false);
1420    }
1421  }
1422  return event;
1423}
1424
1425
1426// FIXME: Copied from ExprEngineCallAndReturn.cpp.
1427static bool isInStdNamespace(const Decl *D) {
1428  const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
1429  const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
1430  if (!ND)
1431    return false;
1432
1433  while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
1434    ND = Parent;
1435
1436  return ND->getName() == "std";
1437}
1438
1439
1440PathDiagnosticPiece *
1441LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1442                                                    const ExplodedNode *N,
1443                                                    BugReport &BR) {
1444  // Here we suppress false positives coming from system headers. This list is
1445  // based on known issues.
1446
1447  // Skip reports within the 'std' namespace. Although these can sometimes be
1448  // the user's fault, we currently don't report them very well, and
1449  // Note that this will not help for any other data structure libraries, like
1450  // TR1, Boost, or llvm/ADT.
1451  ExprEngine &Eng = BRC.getBugReporter().getEngine();
1452  AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1453  if (Options.shouldSuppressFromCXXStandardLibrary()) {
1454    const LocationContext *LCtx = N->getLocationContext();
1455    if (isInStdNamespace(LCtx->getDecl())) {
1456      BR.markInvalid(getTag(), 0);
1457      return 0;
1458    }
1459  }
1460
1461  // Skip reports within the sys/queue.h macros as we do not have the ability to
1462  // reason about data structure shapes.
1463  SourceManager &SM = BRC.getSourceManager();
1464  FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1465  while (Loc.isMacroID()) {
1466    if (SM.isInSystemMacro(Loc) &&
1467       (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
1468      BR.markInvalid(getTag(), 0);
1469      return 0;
1470    }
1471    Loc = Loc.getSpellingLoc();
1472  }
1473
1474  return 0;
1475}
1476
1477PathDiagnosticPiece *
1478UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1479                                  const ExplodedNode *PrevN,
1480                                  BugReporterContext &BRC,
1481                                  BugReport &BR) {
1482
1483  ProgramStateRef State = N->getState();
1484  ProgramPoint ProgLoc = N->getLocation();
1485
1486  // We are only interested in visiting CallEnter nodes.
1487  Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1488  if (!CEnter)
1489    return 0;
1490
1491  // Check if one of the arguments is the region the visitor is tracking.
1492  CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1493  CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1494  unsigned Idx = 0;
1495  for (CallEvent::param_iterator I = Call->param_begin(),
1496                                 E = Call->param_end(); I != E; ++I, ++Idx) {
1497    const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1498
1499    // Are we tracking the argument or its subregion?
1500    if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1501      continue;
1502
1503    // Check the function parameter type.
1504    const ParmVarDecl *ParamDecl = *I;
1505    assert(ParamDecl && "Formal parameter has no decl?");
1506    QualType T = ParamDecl->getType();
1507
1508    if (!(T->isAnyPointerType() || T->isReferenceType())) {
1509      // Function can only change the value passed in by address.
1510      continue;
1511    }
1512
1513    // If it is a const pointer value, the function does not intend to
1514    // change the value.
1515    if (T->getPointeeType().isConstQualified())
1516      continue;
1517
1518    // Mark the call site (LocationContext) as interesting if the value of the
1519    // argument is undefined or '0'/'NULL'.
1520    SVal BoundVal = State->getSVal(R);
1521    if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1522      BR.markInteresting(CEnter->getCalleeContext());
1523      return 0;
1524    }
1525  }
1526  return 0;
1527}
1528