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