clang API Documentation

BugReporterVisitors.cpp
Go to the documentation of this file.
00001 // BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- C++ -*--//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines a set of BugReporter "visitors" which can be used to
00011 //  enhance the diagnostics reported for a bug.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
00015 #include "clang/AST/Expr.h"
00016 #include "clang/AST/ExprObjC.h"
00017 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
00018 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
00019 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
00020 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
00021 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
00022 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
00023 #include "llvm/ADT/SmallString.h"
00024 #include "llvm/ADT/StringExtras.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 
00027 using namespace clang;
00028 using namespace ento;
00029 
00030 using llvm::FoldingSetNodeID;
00031 
00032 //===----------------------------------------------------------------------===//
00033 // Utility functions.
00034 //===----------------------------------------------------------------------===//
00035 
00036 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
00037   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
00038     return DRE->getDecl()->getType()->isReferenceType();
00039   }
00040   return false;
00041 }
00042 
00043 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
00044   // Pattern match for a few useful cases:
00045   //   a[0], p->f, *p
00046   const Expr *E = dyn_cast<Expr>(S);
00047   if (!E)
00048     return nullptr;
00049   E = E->IgnoreParenCasts();
00050 
00051   while (true) {
00052     if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
00053       assert(B->isAssignmentOp());
00054       E = B->getLHS()->IgnoreParenCasts();
00055       continue;
00056     }
00057     else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
00058       if (U->getOpcode() == UO_Deref)
00059         return U->getSubExpr()->IgnoreParenCasts();
00060     }
00061     else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
00062       if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
00063         return ME->getBase()->IgnoreParenCasts();
00064       } else {
00065         // If we have a member expr with a dot, the base must have been
00066         // dereferenced.
00067         return getDerefExpr(ME->getBase());
00068       }
00069     }
00070     else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
00071       return IvarRef->getBase()->IgnoreParenCasts();
00072     }
00073     else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
00074       return AE->getBase();
00075     }
00076     else if (isDeclRefExprToReference(E)) {
00077       return E;
00078     }
00079     break;
00080   }
00081 
00082   return nullptr;
00083 }
00084 
00085 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
00086   const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
00087   if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
00088     return BE->getRHS();
00089   return nullptr;
00090 }
00091 
00092 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
00093   const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
00094   if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
00095     return RS->getRetValue();
00096   return nullptr;
00097 }
00098 
00099 //===----------------------------------------------------------------------===//
00100 // Definitions for bug reporter visitors.
00101 //===----------------------------------------------------------------------===//
00102 
00103 std::unique_ptr<PathDiagnosticPiece>
00104 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
00105                                const ExplodedNode *EndPathNode, BugReport &BR) {
00106   return nullptr;
00107 }
00108 
00109 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
00110     BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
00111   PathDiagnosticLocation L =
00112     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
00113 
00114   BugReport::ranges_iterator Beg, End;
00115   std::tie(Beg, End) = BR.getRanges();
00116 
00117   // Only add the statement itself as a range if we didn't specify any
00118   // special ranges for this report.
00119   auto P = llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
00120                                                        Beg == End);
00121   for (; Beg != End; ++Beg)
00122     P->addRange(*Beg);
00123 
00124   return std::move(P);
00125 }
00126 
00127 
00128 namespace {
00129 /// Emits an extra note at the return statement of an interesting stack frame.
00130 ///
00131 /// The returned value is marked as an interesting value, and if it's null,
00132 /// adds a visitor to track where it became null.
00133 ///
00134 /// This visitor is intended to be used when another visitor discovers that an
00135 /// interesting value comes from an inlined function call.
00136 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
00137   const StackFrameContext *StackFrame;
00138   enum {
00139     Initial,
00140     MaybeUnsuppress,
00141     Satisfied
00142   } Mode;
00143 
00144   bool EnableNullFPSuppression;
00145 
00146 public:
00147   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
00148     : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
00149 
00150   static void *getTag() {
00151     static int Tag = 0;
00152     return static_cast<void *>(&Tag);
00153   }
00154 
00155   void Profile(llvm::FoldingSetNodeID &ID) const override {
00156     ID.AddPointer(ReturnVisitor::getTag());
00157     ID.AddPointer(StackFrame);
00158     ID.AddBoolean(EnableNullFPSuppression);
00159   }
00160 
00161   /// Adds a ReturnVisitor if the given statement represents a call that was
00162   /// inlined.
00163   ///
00164   /// This will search back through the ExplodedGraph, starting from the given
00165   /// node, looking for when the given statement was processed. If it turns out
00166   /// the statement is a call that was inlined, we add the visitor to the
00167   /// bug report, so it can print a note later.
00168   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
00169                                     BugReport &BR,
00170                                     bool InEnableNullFPSuppression) {
00171     if (!CallEvent::isCallStmt(S))
00172       return;
00173     
00174     // First, find when we processed the statement.
00175     do {
00176       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
00177         if (CEE->getCalleeContext()->getCallSite() == S)
00178           break;
00179       if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
00180         if (SP->getStmt() == S)
00181           break;
00182 
00183       Node = Node->getFirstPred();
00184     } while (Node);
00185 
00186     // Next, step over any post-statement checks.
00187     while (Node && Node->getLocation().getAs<PostStmt>())
00188       Node = Node->getFirstPred();
00189     if (!Node)
00190       return;
00191 
00192     // Finally, see if we inlined the call.
00193     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
00194     if (!CEE)
00195       return;
00196     
00197     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
00198     if (CalleeContext->getCallSite() != S)
00199       return;
00200     
00201     // Check the return value.
00202     ProgramStateRef State = Node->getState();
00203     SVal RetVal = State->getSVal(S, Node->getLocationContext());
00204 
00205     // Handle cases where a reference is returned and then immediately used.
00206     if (cast<Expr>(S)->isGLValue())
00207       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
00208         RetVal = State->getSVal(*LValue);
00209 
00210     // See if the return value is NULL. If so, suppress the report.
00211     SubEngine *Eng = State->getStateManager().getOwningEngine();
00212     assert(Eng && "Cannot file a bug report without an owning engine");
00213     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
00214 
00215     bool EnableNullFPSuppression = false;
00216     if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
00217       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
00218         EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
00219 
00220     BR.markInteresting(CalleeContext);
00221     BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
00222                                                    EnableNullFPSuppression));
00223   }
00224 
00225   /// Returns true if any counter-suppression heuristics are enabled for
00226   /// ReturnVisitor.
00227   static bool hasCounterSuppression(AnalyzerOptions &Options) {
00228     return Options.shouldAvoidSuppressingNullArgumentPaths();
00229   }
00230 
00231   PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
00232                                         const ExplodedNode *PrevN,
00233                                         BugReporterContext &BRC,
00234                                         BugReport &BR) {
00235     // Only print a message at the interesting return statement.
00236     if (N->getLocationContext() != StackFrame)
00237       return nullptr;
00238 
00239     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
00240     if (!SP)
00241       return nullptr;
00242 
00243     const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
00244     if (!Ret)
00245       return nullptr;
00246 
00247     // Okay, we're at the right return statement, but do we have the return
00248     // value available?
00249     ProgramStateRef State = N->getState();
00250     SVal V = State->getSVal(Ret, StackFrame);
00251     if (V.isUnknownOrUndef())
00252       return nullptr;
00253 
00254     // Don't print any more notes after this one.
00255     Mode = Satisfied;
00256 
00257     const Expr *RetE = Ret->getRetValue();
00258     assert(RetE && "Tracking a return value for a void function");
00259 
00260     // Handle cases where a reference is returned and then immediately used.
00261     Optional<Loc> LValue;
00262     if (RetE->isGLValue()) {
00263       if ((LValue = V.getAs<Loc>())) {
00264         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
00265         if (RValue.getAs<DefinedSVal>())
00266           V = RValue;
00267       }
00268     }
00269 
00270     // Ignore aggregate rvalues.
00271     if (V.getAs<nonloc::LazyCompoundVal>() ||
00272         V.getAs<nonloc::CompoundVal>())
00273       return nullptr;
00274 
00275     RetE = RetE->IgnoreParenCasts();
00276 
00277     // If we can't prove the return value is 0, just mark it interesting, and
00278     // make sure to track it into any further inner functions.
00279     if (!State->isNull(V).isConstrainedTrue()) {
00280       BR.markInteresting(V);
00281       ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
00282                                            EnableNullFPSuppression);
00283       return nullptr;
00284     }
00285       
00286     // If we're returning 0, we should track where that 0 came from.
00287     bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
00288                                        EnableNullFPSuppression);
00289 
00290     // Build an appropriate message based on the return value.
00291     SmallString<64> Msg;
00292     llvm::raw_svector_ostream Out(Msg);
00293 
00294     if (V.getAs<Loc>()) {
00295       // If we have counter-suppression enabled, make sure we keep visiting
00296       // future nodes. We want to emit a path note as well, in case
00297       // the report is resurrected as valid later on.
00298       ExprEngine &Eng = BRC.getBugReporter().getEngine();
00299       AnalyzerOptions &Options = Eng.getAnalysisManager().options;
00300       if (EnableNullFPSuppression && hasCounterSuppression(Options))
00301         Mode = MaybeUnsuppress;
00302 
00303       if (RetE->getType()->isObjCObjectPointerType())
00304         Out << "Returning nil";
00305       else
00306         Out << "Returning null pointer";
00307     } else {
00308       Out << "Returning zero";
00309     }
00310 
00311     if (LValue) {
00312       if (const MemRegion *MR = LValue->getAsRegion()) {
00313         if (MR->canPrintPretty()) {
00314           Out << " (reference to ";
00315           MR->printPretty(Out);
00316           Out << ")";
00317         }
00318       }
00319     } else {
00320       // FIXME: We should have a more generalized location printing mechanism.
00321       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
00322         if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
00323           Out << " (loaded from '" << *DD << "')";
00324     }
00325 
00326     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
00327     return new PathDiagnosticEventPiece(L, Out.str());
00328   }
00329 
00330   PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
00331                                                 const ExplodedNode *PrevN,
00332                                                 BugReporterContext &BRC,
00333                                                 BugReport &BR) {
00334 #ifndef NDEBUG
00335     ExprEngine &Eng = BRC.getBugReporter().getEngine();
00336     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
00337     assert(hasCounterSuppression(Options));
00338 #endif
00339 
00340     // Are we at the entry node for this call?
00341     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
00342     if (!CE)
00343       return nullptr;
00344 
00345     if (CE->getCalleeContext() != StackFrame)
00346       return nullptr;
00347 
00348     Mode = Satisfied;
00349 
00350     // Don't automatically suppress a report if one of the arguments is
00351     // known to be a null pointer. Instead, start tracking /that/ null
00352     // value back to its origin.
00353     ProgramStateManager &StateMgr = BRC.getStateManager();
00354     CallEventManager &CallMgr = StateMgr.getCallEventManager();
00355 
00356     ProgramStateRef State = N->getState();
00357     CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
00358     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
00359       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
00360       if (!ArgV)
00361         continue;
00362 
00363       const Expr *ArgE = Call->getArgExpr(I);
00364       if (!ArgE)
00365         continue;
00366 
00367       // Is it possible for this argument to be non-null?
00368       if (!State->isNull(*ArgV).isConstrainedTrue())
00369         continue;
00370 
00371       if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
00372                                              EnableNullFPSuppression))
00373         BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
00374 
00375       // If we /can't/ track the null pointer, we should err on the side of
00376       // false negatives, and continue towards marking this report invalid.
00377       // (We will still look at the other arguments, though.)
00378     }
00379 
00380     return nullptr;
00381   }
00382 
00383   PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
00384                                  const ExplodedNode *PrevN,
00385                                  BugReporterContext &BRC,
00386                                  BugReport &BR) override {
00387     switch (Mode) {
00388     case Initial:
00389       return visitNodeInitial(N, PrevN, BRC, BR);
00390     case MaybeUnsuppress:
00391       return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
00392     case Satisfied:
00393       return nullptr;
00394     }
00395 
00396     llvm_unreachable("Invalid visit mode!");
00397   }
00398 
00399   std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
00400                                                   const ExplodedNode *N,
00401                                                   BugReport &BR) override {
00402     if (EnableNullFPSuppression)
00403       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
00404     return nullptr;
00405   }
00406 };
00407 } // end anonymous namespace
00408 
00409 
00410 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
00411   static int tag = 0;
00412   ID.AddPointer(&tag);
00413   ID.AddPointer(R);
00414   ID.Add(V);
00415   ID.AddBoolean(EnableNullFPSuppression);
00416 }
00417 
00418 /// Returns true if \p N represents the DeclStmt declaring and initializing
00419 /// \p VR.
00420 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
00421   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
00422   if (!P)
00423     return false;
00424 
00425   const DeclStmt *DS = P->getStmtAs<DeclStmt>();
00426   if (!DS)
00427     return false;
00428 
00429   if (DS->getSingleDecl() != VR->getDecl())
00430     return false;
00431 
00432   const MemSpaceRegion *VarSpace = VR->getMemorySpace();
00433   const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
00434   if (!FrameSpace) {
00435     // If we ever directly evaluate global DeclStmts, this assertion will be
00436     // invalid, but this still seems preferable to silently accepting an
00437     // initialization that may be for a path-sensitive variable.
00438     assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
00439     return true;
00440   }
00441 
00442   assert(VR->getDecl()->hasLocalStorage());
00443   const LocationContext *LCtx = N->getLocationContext();
00444   return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
00445 }
00446 
00447 PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
00448                                                        const ExplodedNode *Pred,
00449                                                        BugReporterContext &BRC,
00450                                                        BugReport &BR) {
00451 
00452   if (Satisfied)
00453     return nullptr;
00454 
00455   const ExplodedNode *StoreSite = nullptr;
00456   const Expr *InitE = nullptr;
00457   bool IsParam = false;
00458 
00459   // First see if we reached the declaration of the region.
00460   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
00461     if (isInitializationOfVar(Pred, VR)) {
00462       StoreSite = Pred;
00463       InitE = VR->getDecl()->getInit();
00464     }
00465   }
00466 
00467   // If this is a post initializer expression, initializing the region, we
00468   // should track the initializer expression.
00469   if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
00470     const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
00471     if (FieldReg && FieldReg == R) {
00472       StoreSite = Pred;
00473       InitE = PIP->getInitializer()->getInit();
00474     }
00475   }
00476   
00477   // Otherwise, see if this is the store site:
00478   // (1) Succ has this binding and Pred does not, i.e. this is
00479   //     where the binding first occurred.
00480   // (2) Succ has this binding and is a PostStore node for this region, i.e.
00481   //     the same binding was re-assigned here.
00482   if (!StoreSite) {
00483     if (Succ->getState()->getSVal(R) != V)
00484       return nullptr;
00485 
00486     if (Pred->getState()->getSVal(R) == V) {
00487       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
00488       if (!PS || PS->getLocationValue() != R)
00489         return nullptr;
00490     }
00491 
00492     StoreSite = Succ;
00493 
00494     // If this is an assignment expression, we can track the value
00495     // being assigned.
00496     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
00497       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
00498         if (BO->isAssignmentOp())
00499           InitE = BO->getRHS();
00500 
00501     // If this is a call entry, the variable should be a parameter.
00502     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
00503     // 'this' should never be NULL, but this visitor isn't just for NULL and
00504     // UndefinedVal.)
00505     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
00506       if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
00507         const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
00508         
00509         ProgramStateManager &StateMgr = BRC.getStateManager();
00510         CallEventManager &CallMgr = StateMgr.getCallEventManager();
00511 
00512         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
00513                                                 Succ->getState());
00514         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
00515         IsParam = true;
00516       }
00517     }
00518 
00519     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
00520     // is wrapped inside of it.
00521     if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
00522       InitE = TmpR->getExpr();
00523   }
00524 
00525   if (!StoreSite)
00526     return nullptr;
00527   Satisfied = true;
00528 
00529   // If we have an expression that provided the value, try to track where it
00530   // came from.
00531   if (InitE) {
00532     if (V.isUndef() ||
00533         V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
00534       if (!IsParam)
00535         InitE = InitE->IgnoreParenCasts();
00536       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
00537                                          EnableNullFPSuppression);
00538     } else {
00539       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
00540                                            BR, EnableNullFPSuppression);
00541     }
00542   }
00543 
00544   // Okay, we've found the binding. Emit an appropriate message.
00545   SmallString<256> sbuf;
00546   llvm::raw_svector_ostream os(sbuf);
00547 
00548   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
00549     const Stmt *S = PS->getStmt();
00550     const char *action = nullptr;
00551     const DeclStmt *DS = dyn_cast<DeclStmt>(S);
00552     const VarRegion *VR = dyn_cast<VarRegion>(R);
00553 
00554     if (DS) {
00555       action = R->canPrintPretty() ? "initialized to " :
00556                                      "Initializing to ";
00557     } else if (isa<BlockExpr>(S)) {
00558       action = R->canPrintPretty() ? "captured by block as " :
00559                                      "Captured by block as ";
00560       if (VR) {
00561         // See if we can get the BlockVarRegion.
00562         ProgramStateRef State = StoreSite->getState();
00563         SVal V = State->getSVal(S, PS->getLocationContext());
00564         if (const BlockDataRegion *BDR =
00565               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
00566           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
00567             if (Optional<KnownSVal> KV =
00568                 State->getSVal(OriginalR).getAs<KnownSVal>())
00569               BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
00570                   *KV, OriginalR, EnableNullFPSuppression));
00571           }
00572         }
00573       }
00574     }
00575 
00576     if (action) {
00577       if (R->canPrintPretty()) {
00578         R->printPretty(os);
00579         os << " ";
00580       }
00581 
00582       if (V.getAs<loc::ConcreteInt>()) {
00583         bool b = false;
00584         if (R->isBoundable()) {
00585           if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
00586             if (TR->getValueType()->isObjCObjectPointerType()) {
00587               os << action << "nil";
00588               b = true;
00589             }
00590           }
00591         }
00592 
00593         if (!b)
00594           os << action << "a null pointer value";
00595       } else if (Optional<nonloc::ConcreteInt> CVal =
00596                      V.getAs<nonloc::ConcreteInt>()) {
00597         os << action << CVal->getValue();
00598       }
00599       else if (DS) {
00600         if (V.isUndef()) {
00601           if (isa<VarRegion>(R)) {
00602             const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
00603             if (VD->getInit()) {
00604               os << (R->canPrintPretty() ? "initialized" : "Initializing")
00605                  << " to a garbage value";
00606             } else {
00607               os << (R->canPrintPretty() ? "declared" : "Declaring")
00608                  << " without an initial value";
00609             }
00610           }
00611         }
00612         else {
00613           os << (R->canPrintPretty() ? "initialized" : "Initialized")
00614              << " here";
00615         }
00616       }
00617     }
00618   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
00619     if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
00620       const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
00621 
00622       os << "Passing ";
00623 
00624       if (V.getAs<loc::ConcreteInt>()) {
00625         if (Param->getType()->isObjCObjectPointerType())
00626           os << "nil object reference";
00627         else
00628           os << "null pointer value";
00629       } else if (V.isUndef()) {
00630         os << "uninitialized value";
00631       } else if (Optional<nonloc::ConcreteInt> CI =
00632                      V.getAs<nonloc::ConcreteInt>()) {
00633         os << "the value " << CI->getValue();
00634       } else {
00635         os << "value";
00636       }
00637 
00638       // Printed parameter indexes are 1-based, not 0-based.
00639       unsigned Idx = Param->getFunctionScopeIndex() + 1;
00640       os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
00641       if (R->canPrintPretty()) {
00642         os << " ";
00643         R->printPretty(os);
00644       }
00645     }
00646   }
00647 
00648   if (os.str().empty()) {
00649     if (V.getAs<loc::ConcreteInt>()) {
00650       bool b = false;
00651       if (R->isBoundable()) {
00652         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
00653           if (TR->getValueType()->isObjCObjectPointerType()) {
00654             os << "nil object reference stored";
00655             b = true;
00656           }
00657         }
00658       }
00659       if (!b) {
00660         if (R->canPrintPretty())
00661           os << "Null pointer value stored";
00662         else
00663           os << "Storing null pointer value";
00664       }
00665 
00666     } else if (V.isUndef()) {
00667       if (R->canPrintPretty())
00668         os << "Uninitialized value stored";
00669       else
00670         os << "Storing uninitialized value";
00671 
00672     } else if (Optional<nonloc::ConcreteInt> CV =
00673                    V.getAs<nonloc::ConcreteInt>()) {
00674       if (R->canPrintPretty())
00675         os << "The value " << CV->getValue() << " is assigned";
00676       else
00677         os << "Assigning " << CV->getValue();
00678 
00679     } else {
00680       if (R->canPrintPretty())
00681         os << "Value assigned";
00682       else
00683         os << "Assigning value";
00684     }
00685     
00686     if (R->canPrintPretty()) {
00687       os << " to ";
00688       R->printPretty(os);
00689     }
00690   }
00691 
00692   // Construct a new PathDiagnosticPiece.
00693   ProgramPoint P = StoreSite->getLocation();
00694   PathDiagnosticLocation L;
00695   if (P.getAs<CallEnter>() && InitE)
00696     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
00697                                P.getLocationContext());
00698 
00699   if (!L.isValid() || !L.asLocation().isValid())
00700     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
00701 
00702   if (!L.isValid() || !L.asLocation().isValid())
00703     return nullptr;
00704 
00705   return new PathDiagnosticEventPiece(L, os.str());
00706 }
00707 
00708 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
00709   static int tag = 0;
00710   ID.AddPointer(&tag);
00711   ID.AddBoolean(Assumption);
00712   ID.Add(Constraint);
00713 }
00714 
00715 /// Return the tag associated with this visitor.  This tag will be used
00716 /// to make all PathDiagnosticPieces created by this visitor.
00717 const char *TrackConstraintBRVisitor::getTag() {
00718   return "TrackConstraintBRVisitor";
00719 }
00720 
00721 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
00722   if (IsZeroCheck)
00723     return N->getState()->isNull(Constraint).isUnderconstrained();
00724   return (bool)N->getState()->assume(Constraint, !Assumption);
00725 }
00726 
00727 PathDiagnosticPiece *
00728 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
00729                                     const ExplodedNode *PrevN,
00730                                     BugReporterContext &BRC,
00731                                     BugReport &BR) {
00732   if (IsSatisfied)
00733     return nullptr;
00734 
00735   // Start tracking after we see the first state in which the value is
00736   // constrained.
00737   if (!IsTrackingTurnedOn)
00738     if (!isUnderconstrained(N))
00739       IsTrackingTurnedOn = true;
00740   if (!IsTrackingTurnedOn)
00741     return nullptr;
00742 
00743   // Check if in the previous state it was feasible for this constraint
00744   // to *not* be true.
00745   if (isUnderconstrained(PrevN)) {
00746 
00747     IsSatisfied = true;
00748 
00749     // As a sanity check, make sure that the negation of the constraint
00750     // was infeasible in the current state.  If it is feasible, we somehow
00751     // missed the transition point.
00752     assert(!isUnderconstrained(N));
00753 
00754     // We found the transition point for the constraint.  We now need to
00755     // pretty-print the constraint. (work-in-progress)
00756     SmallString<64> sbuf;
00757     llvm::raw_svector_ostream os(sbuf);
00758 
00759     if (Constraint.getAs<Loc>()) {
00760       os << "Assuming pointer value is ";
00761       os << (Assumption ? "non-null" : "null");
00762     }
00763 
00764     if (os.str().empty())
00765       return nullptr;
00766 
00767     // Construct a new PathDiagnosticPiece.
00768     ProgramPoint P = N->getLocation();
00769     PathDiagnosticLocation L =
00770       PathDiagnosticLocation::create(P, BRC.getSourceManager());
00771     if (!L.isValid())
00772       return nullptr;
00773 
00774     PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
00775     X->setTag(getTag());
00776     return X;
00777   }
00778 
00779   return nullptr;
00780 }
00781 
00782 SuppressInlineDefensiveChecksVisitor::
00783 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
00784   : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
00785 
00786     // Check if the visitor is disabled.
00787     SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
00788     assert(Eng && "Cannot file a bug report without an owning engine");
00789     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
00790     if (!Options.shouldSuppressInlinedDefensiveChecks())
00791       IsSatisfied = true;
00792 
00793     assert(N->getState()->isNull(V).isConstrainedTrue() &&
00794            "The visitor only tracks the cases where V is constrained to 0");
00795 }
00796 
00797 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
00798   static int id = 0;
00799   ID.AddPointer(&id);
00800   ID.Add(V);
00801 }
00802 
00803 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
00804   return "IDCVisitor";
00805 }
00806 
00807 PathDiagnosticPiece *
00808 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
00809                                                 const ExplodedNode *Pred,
00810                                                 BugReporterContext &BRC,
00811                                                 BugReport &BR) {
00812   if (IsSatisfied)
00813     return nullptr;
00814 
00815   // Start tracking after we see the first state in which the value is null.
00816   if (!IsTrackingTurnedOn)
00817     if (Succ->getState()->isNull(V).isConstrainedTrue())
00818       IsTrackingTurnedOn = true;
00819   if (!IsTrackingTurnedOn)
00820     return nullptr;
00821 
00822   // Check if in the previous state it was feasible for this value
00823   // to *not* be null.
00824   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
00825     IsSatisfied = true;
00826 
00827     assert(Succ->getState()->isNull(V).isConstrainedTrue());
00828 
00829     // Check if this is inlined defensive checks.
00830     const LocationContext *CurLC =Succ->getLocationContext();
00831     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
00832     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
00833       BR.markInvalid("Suppress IDC", CurLC);
00834   }
00835   return nullptr;
00836 }
00837 
00838 static const MemRegion *getLocationRegionIfReference(const Expr *E,
00839                                                      const ExplodedNode *N) {
00840   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
00841     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
00842       if (!VD->getType()->isReferenceType())
00843         return nullptr;
00844       ProgramStateManager &StateMgr = N->getState()->getStateManager();
00845       MemRegionManager &MRMgr = StateMgr.getRegionManager();
00846       return MRMgr.getVarRegion(VD, N->getLocationContext());
00847     }
00848   }
00849 
00850   // FIXME: This does not handle other kinds of null references,
00851   // for example, references from FieldRegions:
00852   //   struct Wrapper { int &ref; };
00853   //   Wrapper w = { *(int *)0 };
00854   //   w.ref = 1;
00855 
00856   return nullptr;
00857 }
00858 
00859 static const Expr *peelOffOuterExpr(const Expr *Ex,
00860                                     const ExplodedNode *N) {
00861   Ex = Ex->IgnoreParenCasts();
00862   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
00863     return peelOffOuterExpr(EWC->getSubExpr(), N);
00864   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
00865     return peelOffOuterExpr(OVE->getSourceExpr(), N);
00866 
00867   // Peel off the ternary operator.
00868   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
00869     // Find a node where the branching occurred and find out which branch
00870     // we took (true/false) by looking at the ExplodedGraph.
00871     const ExplodedNode *NI = N;
00872     do {
00873       ProgramPoint ProgPoint = NI->getLocation();
00874       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
00875         const CFGBlock *srcBlk = BE->getSrc();
00876         if (const Stmt *term = srcBlk->getTerminator()) {
00877           if (term == CO) {
00878             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
00879             if (TookTrueBranch)
00880               return peelOffOuterExpr(CO->getTrueExpr(), N);
00881             else
00882               return peelOffOuterExpr(CO->getFalseExpr(), N);
00883           }
00884         }
00885       }
00886       NI = NI->getFirstPred();
00887     } while (NI);
00888   }
00889   return Ex;
00890 }
00891 
00892 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
00893                                         const Stmt *S,
00894                                         BugReport &report, bool IsArg,
00895                                         bool EnableNullFPSuppression) {
00896   if (!S || !N)
00897     return false;
00898 
00899   if (const Expr *Ex = dyn_cast<Expr>(S)) {
00900     Ex = Ex->IgnoreParenCasts();
00901     const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
00902     if (Ex != PeeledEx)
00903       S = PeeledEx;
00904   }
00905 
00906   const Expr *Inner = nullptr;
00907   if (const Expr *Ex = dyn_cast<Expr>(S)) {
00908     Ex = Ex->IgnoreParenCasts();
00909     if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
00910       Inner = Ex;
00911   }
00912 
00913   if (IsArg && !Inner) {
00914     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
00915   } else {
00916     // Walk through nodes until we get one that matches the statement exactly.
00917     // Alternately, if we hit a known lvalue for the statement, we know we've
00918     // gone too far (though we can likely track the lvalue better anyway).
00919     do {
00920       const ProgramPoint &pp = N->getLocation();
00921       if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
00922         if (ps->getStmt() == S || ps->getStmt() == Inner)
00923           break;
00924       } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
00925         if (CEE->getCalleeContext()->getCallSite() == S ||
00926             CEE->getCalleeContext()->getCallSite() == Inner)
00927           break;
00928       }
00929       N = N->getFirstPred();
00930     } while (N);
00931 
00932     if (!N)
00933       return false;
00934   }
00935   
00936   ProgramStateRef state = N->getState();
00937 
00938   // The message send could be nil due to the receiver being nil.
00939   // At this point in the path, the receiver should be live since we are at the
00940   // message send expr. If it is nil, start tracking it.
00941   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
00942     trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
00943 
00944 
00945   // See if the expression we're interested refers to a variable.
00946   // If so, we can track both its contents and constraints on its value.
00947   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
00948     const MemRegion *R = nullptr;
00949 
00950     // Find the ExplodedNode where the lvalue (the value of 'Ex')
00951     // was computed.  We need this for getting the location value.
00952     const ExplodedNode *LVNode = N;
00953     while (LVNode) {
00954       if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
00955         if (P->getStmt() == Inner)
00956           break;
00957       }
00958       LVNode = LVNode->getFirstPred();
00959     }
00960     assert(LVNode && "Unable to find the lvalue node.");
00961     ProgramStateRef LVState = LVNode->getState();
00962     SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
00963     
00964     if (LVState->isNull(LVal).isConstrainedTrue()) {
00965       // In case of C++ references, we want to differentiate between a null
00966       // reference and reference to null pointer.
00967       // If the LVal is null, check if we are dealing with null reference.
00968       // For those, we want to track the location of the reference.
00969       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
00970         R = RR;
00971     } else {
00972       R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
00973 
00974       // If this is a C++ reference to a null pointer, we are tracking the
00975       // pointer. In additon, we should find the store at which the reference
00976       // got initialized.
00977       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
00978         if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
00979           report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
00980               *KV, RR, EnableNullFPSuppression));
00981       }
00982     }
00983 
00984     if (R) {
00985       // Mark both the variable region and its contents as interesting.
00986       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
00987 
00988       report.markInteresting(R);
00989       report.markInteresting(V);
00990       report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
00991 
00992       // If the contents are symbolic, find out when they became null.
00993       if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
00994         report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
00995             V.castAs<DefinedSVal>(), false));
00996 
00997       // Add visitor, which will suppress inline defensive checks.
00998       if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
00999         if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
01000             EnableNullFPSuppression) {
01001           report.addVisitor(
01002               llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
01003                                                                       LVNode));
01004         }
01005       }
01006 
01007       if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
01008         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
01009             *KV, R, EnableNullFPSuppression));
01010       return true;
01011     }
01012   }
01013 
01014   // If the expression is not an "lvalue expression", we can still
01015   // track the constraints on its contents.
01016   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
01017 
01018   // If the value came from an inlined function call, we should at least make
01019   // sure that function isn't pruned in our output.
01020   if (const Expr *E = dyn_cast<Expr>(S))
01021     S = E->IgnoreParenCasts();
01022 
01023   ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
01024 
01025   // Uncomment this to find cases where we aren't properly getting the
01026   // base value that was dereferenced.
01027   // assert(!V.isUnknownOrUndef());
01028   // Is it a symbolic value?
01029   if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
01030     // At this point we are dealing with the region's LValue.
01031     // However, if the rvalue is a symbolic region, we should track it as well.
01032     // Try to use the correct type when looking up the value.
01033     SVal RVal;
01034     if (const Expr *E = dyn_cast<Expr>(S))
01035       RVal = state->getRawSVal(L.getValue(), E->getType());
01036     else
01037       RVal = state->getSVal(L->getRegion());
01038 
01039     const MemRegion *RegionRVal = RVal.getAsRegion();
01040     report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
01041 
01042     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
01043       report.markInteresting(RegionRVal);
01044       report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
01045           loc::MemRegionVal(RegionRVal), false));
01046     }
01047   }
01048 
01049   return true;
01050 }
01051 
01052 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
01053                                                  const ExplodedNode *N) {
01054   const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
01055   if (!ME)
01056     return nullptr;
01057   if (const Expr *Receiver = ME->getInstanceReceiver()) {
01058     ProgramStateRef state = N->getState();
01059     SVal V = state->getSVal(Receiver, N->getLocationContext());
01060     if (state->isNull(V).isConstrainedTrue())
01061       return Receiver;
01062   }
01063   return nullptr;
01064 }
01065 
01066 PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
01067                                                      const ExplodedNode *PrevN,
01068                                                      BugReporterContext &BRC,
01069                                                      BugReport &BR) {
01070   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
01071   if (!P)
01072     return nullptr;
01073 
01074   const Stmt *S = P->getStmt();
01075   const Expr *Receiver = getNilReceiver(S, N);
01076   if (!Receiver)
01077     return nullptr;
01078 
01079   llvm::SmallString<256> Buf;
01080   llvm::raw_svector_ostream OS(Buf);
01081 
01082   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
01083     OS << "'";
01084     ME->getSelector().print(OS);
01085     OS << "' not called";
01086   }
01087   else {
01088     OS << "No method is called";
01089   }
01090   OS << " because the receiver is nil";
01091 
01092   // The receiver was nil, and hence the method was skipped.
01093   // Register a BugReporterVisitor to issue a message telling us how
01094   // the receiver was null.
01095   bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
01096                                      /*EnableNullFPSuppression*/ false);
01097   // Issue a message saying that the method was skipped.
01098   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
01099                                      N->getLocationContext());
01100   return new PathDiagnosticEventPiece(L, OS.str());
01101 }
01102 
01103 // Registers every VarDecl inside a Stmt with a last store visitor.
01104 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
01105                                                 const Stmt *S,
01106                                                 bool EnableNullFPSuppression) {
01107   const ExplodedNode *N = BR.getErrorNode();
01108   std::deque<const Stmt *> WorkList;
01109   WorkList.push_back(S);
01110 
01111   while (!WorkList.empty()) {
01112     const Stmt *Head = WorkList.front();
01113     WorkList.pop_front();
01114 
01115     ProgramStateRef state = N->getState();
01116     ProgramStateManager &StateMgr = state->getStateManager();
01117 
01118     if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
01119       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
01120         const VarRegion *R =
01121         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
01122 
01123         // What did we load?
01124         SVal V = state->getSVal(S, N->getLocationContext());
01125 
01126         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
01127           // Register a new visitor with the BugReport.
01128           BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
01129               V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
01130         }
01131       }
01132     }
01133 
01134     for (Stmt::const_child_iterator I = Head->child_begin();
01135         I != Head->child_end(); ++I)
01136       WorkList.push_back(*I);
01137   }
01138 }
01139 
01140 //===----------------------------------------------------------------------===//
01141 // Visitor that tries to report interesting diagnostics from conditions.
01142 //===----------------------------------------------------------------------===//
01143 
01144 /// Return the tag associated with this visitor.  This tag will be used
01145 /// to make all PathDiagnosticPieces created by this visitor.
01146 const char *ConditionBRVisitor::getTag() {
01147   return "ConditionBRVisitor";
01148 }
01149 
01150 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
01151                                                    const ExplodedNode *Prev,
01152                                                    BugReporterContext &BRC,
01153                                                    BugReport &BR) {
01154   PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
01155   if (piece) {
01156     piece->setTag(getTag());
01157     if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
01158       ev->setPrunable(true, /* override */ false);
01159   }
01160   return piece;
01161 }
01162 
01163 PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
01164                                                        const ExplodedNode *Prev,
01165                                                        BugReporterContext &BRC,
01166                                                        BugReport &BR) {
01167   
01168   ProgramPoint progPoint = N->getLocation();
01169   ProgramStateRef CurrentState = N->getState();
01170   ProgramStateRef PrevState = Prev->getState();
01171   
01172   // Compare the GDMs of the state, because that is where constraints
01173   // are managed.  Note that ensure that we only look at nodes that
01174   // were generated by the analyzer engine proper, not checkers.
01175   if (CurrentState->getGDM().getRoot() ==
01176       PrevState->getGDM().getRoot())
01177     return nullptr;
01178 
01179   // If an assumption was made on a branch, it should be caught
01180   // here by looking at the state transition.
01181   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
01182     const CFGBlock *srcBlk = BE->getSrc();    
01183     if (const Stmt *term = srcBlk->getTerminator())
01184       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
01185     return nullptr;
01186   }
01187   
01188   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
01189     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
01190     // violation.
01191     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =      
01192       cast<GRBugReporter>(BRC.getBugReporter()).
01193         getEngine().geteagerlyAssumeBinOpBifurcationTags();
01194 
01195     const ProgramPointTag *tag = PS->getTag();
01196     if (tag == tags.first)
01197       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
01198                            BRC, BR, N);
01199     if (tag == tags.second)
01200       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
01201                            BRC, BR, N);
01202 
01203     return nullptr;
01204   }
01205 
01206   return nullptr;
01207 }
01208 
01209 PathDiagnosticPiece *
01210 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
01211                                     const ExplodedNode *N,
01212                                     const CFGBlock *srcBlk,
01213                                     const CFGBlock *dstBlk,
01214                                     BugReport &R,
01215                                     BugReporterContext &BRC) {
01216   const Expr *Cond = nullptr;
01217 
01218   switch (Term->getStmtClass()) {
01219   default:
01220     return nullptr;
01221   case Stmt::IfStmtClass:
01222     Cond = cast<IfStmt>(Term)->getCond();
01223     break;
01224   case Stmt::ConditionalOperatorClass:
01225     Cond = cast<ConditionalOperator>(Term)->getCond();
01226     break;
01227   }      
01228 
01229   assert(Cond);
01230   assert(srcBlk->succ_size() == 2);
01231   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
01232   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
01233 }
01234 
01235 PathDiagnosticPiece *
01236 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
01237                                   bool tookTrue,
01238                                   BugReporterContext &BRC,
01239                                   BugReport &R,
01240                                   const ExplodedNode *N) {
01241   
01242   const Expr *Ex = Cond;
01243   
01244   while (true) {
01245     Ex = Ex->IgnoreParenCasts();
01246     switch (Ex->getStmtClass()) {
01247       default:
01248         return nullptr;
01249       case Stmt::BinaryOperatorClass:
01250         return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
01251                              R, N);
01252       case Stmt::DeclRefExprClass:
01253         return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
01254                              R, N);
01255       case Stmt::UnaryOperatorClass: {
01256         const UnaryOperator *UO = cast<UnaryOperator>(Ex);
01257         if (UO->getOpcode() == UO_LNot) {
01258           tookTrue = !tookTrue;
01259           Ex = UO->getSubExpr();
01260           continue;
01261         }
01262         return nullptr;
01263       }
01264     }
01265   }
01266 }
01267 
01268 bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
01269                                       BugReporterContext &BRC,
01270                                       BugReport &report,
01271                                       const ExplodedNode *N,
01272                                       Optional<bool> &prunable) {
01273   const Expr *OriginalExpr = Ex;
01274   Ex = Ex->IgnoreParenCasts();
01275 
01276   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
01277     const bool quotes = isa<VarDecl>(DR->getDecl());
01278     if (quotes) {
01279       Out << '\'';
01280       const LocationContext *LCtx = N->getLocationContext();
01281       const ProgramState *state = N->getState().get();
01282       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
01283                                                 LCtx).getAsRegion()) {
01284         if (report.isInteresting(R))
01285           prunable = false;
01286         else {
01287           const ProgramState *state = N->getState().get();
01288           SVal V = state->getSVal(R);
01289           if (report.isInteresting(V))
01290             prunable = false;
01291         }
01292       }
01293     }
01294     Out << DR->getDecl()->getDeclName().getAsString();
01295     if (quotes)
01296       Out << '\'';
01297     return quotes;
01298   }
01299   
01300   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
01301     QualType OriginalTy = OriginalExpr->getType();
01302     if (OriginalTy->isPointerType()) {
01303       if (IL->getValue() == 0) {
01304         Out << "null";
01305         return false;
01306       }
01307     }
01308     else if (OriginalTy->isObjCObjectPointerType()) {
01309       if (IL->getValue() == 0) {
01310         Out << "nil";
01311         return false;
01312       }
01313     }
01314     
01315     Out << IL->getValue();
01316     return false;
01317   }
01318   
01319   return false;
01320 }
01321 
01322 PathDiagnosticPiece *
01323 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
01324                                   const BinaryOperator *BExpr,
01325                                   const bool tookTrue,
01326                                   BugReporterContext &BRC,
01327                                   BugReport &R,
01328                                   const ExplodedNode *N) {
01329   
01330   bool shouldInvert = false;
01331   Optional<bool> shouldPrune;
01332   
01333   SmallString<128> LhsString, RhsString;
01334   {
01335     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
01336     const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
01337                                        shouldPrune);
01338     const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
01339                                        shouldPrune);
01340     
01341     shouldInvert = !isVarLHS && isVarRHS;    
01342   }
01343   
01344   BinaryOperator::Opcode Op = BExpr->getOpcode();
01345 
01346   if (BinaryOperator::isAssignmentOp(Op)) {
01347     // For assignment operators, all that we care about is that the LHS
01348     // evaluates to "true" or "false".
01349     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
01350                                   BRC, R, N);
01351   }
01352 
01353   // For non-assignment operations, we require that we can understand
01354   // both the LHS and RHS.
01355   if (LhsString.empty() || RhsString.empty() ||
01356       !BinaryOperator::isComparisonOp(Op))
01357     return nullptr;
01358 
01359   // Should we invert the strings if the LHS is not a variable name?
01360   SmallString<256> buf;
01361   llvm::raw_svector_ostream Out(buf);
01362   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
01363 
01364   // Do we need to invert the opcode?
01365   if (shouldInvert)
01366     switch (Op) {
01367       default: break;
01368       case BO_LT: Op = BO_GT; break;
01369       case BO_GT: Op = BO_LT; break;
01370       case BO_LE: Op = BO_GE; break;
01371       case BO_GE: Op = BO_LE; break;
01372     }
01373 
01374   if (!tookTrue)
01375     switch (Op) {
01376       case BO_EQ: Op = BO_NE; break;
01377       case BO_NE: Op = BO_EQ; break;
01378       case BO_LT: Op = BO_GE; break;
01379       case BO_GT: Op = BO_LE; break;
01380       case BO_LE: Op = BO_GT; break;
01381       case BO_GE: Op = BO_LT; break;
01382       default:
01383         return nullptr;
01384     }
01385   
01386   switch (Op) {
01387     case BO_EQ:
01388       Out << "equal to ";
01389       break;
01390     case BO_NE:
01391       Out << "not equal to ";
01392       break;
01393     default:
01394       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
01395       break;
01396   }
01397   
01398   Out << (shouldInvert ? LhsString : RhsString);
01399   const LocationContext *LCtx = N->getLocationContext();
01400   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
01401   PathDiagnosticEventPiece *event =
01402     new PathDiagnosticEventPiece(Loc, Out.str());
01403   if (shouldPrune.hasValue())
01404     event->setPrunable(shouldPrune.getValue());
01405   return event;
01406 }
01407 
01408 PathDiagnosticPiece *
01409 ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
01410                                            const Expr *CondVarExpr,
01411                                            const bool tookTrue,
01412                                            BugReporterContext &BRC,
01413                                            BugReport &report,
01414                                            const ExplodedNode *N) {
01415   // FIXME: If there's already a constraint tracker for this variable,
01416   // we shouldn't emit anything here (c.f. the double note in
01417   // test/Analysis/inlining/path-notes.c)
01418   SmallString<256> buf;
01419   llvm::raw_svector_ostream Out(buf);
01420   Out << "Assuming " << LhsString << " is ";
01421   
01422   QualType Ty = CondVarExpr->getType();
01423 
01424   if (Ty->isPointerType())
01425     Out << (tookTrue ? "not null" : "null");
01426   else if (Ty->isObjCObjectPointerType())
01427     Out << (tookTrue ? "not nil" : "nil");
01428   else if (Ty->isBooleanType())
01429     Out << (tookTrue ? "true" : "false");
01430   else if (Ty->isIntegralOrEnumerationType())
01431     Out << (tookTrue ? "non-zero" : "zero");
01432   else
01433     return nullptr;
01434 
01435   const LocationContext *LCtx = N->getLocationContext();
01436   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
01437   PathDiagnosticEventPiece *event =
01438     new PathDiagnosticEventPiece(Loc, Out.str());
01439 
01440   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
01441     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
01442       const ProgramState *state = N->getState().get();
01443       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
01444         if (report.isInteresting(R))
01445           event->setPrunable(false);
01446       }
01447     }
01448   }
01449   
01450   return event;
01451 }
01452   
01453 PathDiagnosticPiece *
01454 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
01455                                   const DeclRefExpr *DR,
01456                                   const bool tookTrue,
01457                                   BugReporterContext &BRC,
01458                                   BugReport &report,
01459                                   const ExplodedNode *N) {
01460 
01461   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
01462   if (!VD)
01463     return nullptr;
01464 
01465   SmallString<256> Buf;
01466   llvm::raw_svector_ostream Out(Buf);
01467     
01468   Out << "Assuming '" << VD->getDeclName() << "' is ";
01469     
01470   QualType VDTy = VD->getType();
01471   
01472   if (VDTy->isPointerType())
01473     Out << (tookTrue ? "non-null" : "null");
01474   else if (VDTy->isObjCObjectPointerType())
01475     Out << (tookTrue ? "non-nil" : "nil");
01476   else if (VDTy->isScalarType())
01477     Out << (tookTrue ? "not equal to 0" : "0");
01478   else
01479     return nullptr;
01480 
01481   const LocationContext *LCtx = N->getLocationContext();
01482   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
01483   PathDiagnosticEventPiece *event =
01484     new PathDiagnosticEventPiece(Loc, Out.str());
01485   
01486   const ProgramState *state = N->getState().get();
01487   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
01488     if (report.isInteresting(R))
01489       event->setPrunable(false);
01490     else {
01491       SVal V = state->getSVal(R);
01492       if (report.isInteresting(V))
01493         event->setPrunable(false);
01494     }
01495   }
01496   return event;
01497 }
01498 
01499 
01500 // FIXME: Copied from ExprEngineCallAndReturn.cpp.
01501 static bool isInStdNamespace(const Decl *D) {
01502   const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
01503   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
01504   if (!ND)
01505     return false;
01506 
01507   while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
01508     ND = Parent;
01509 
01510   return ND->isStdNamespace();
01511 }
01512 
01513 std::unique_ptr<PathDiagnosticPiece>
01514 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
01515                                                     const ExplodedNode *N,
01516                                                     BugReport &BR) {
01517   // Here we suppress false positives coming from system headers. This list is
01518   // based on known issues.
01519   ExprEngine &Eng = BRC.getBugReporter().getEngine();
01520   AnalyzerOptions &Options = Eng.getAnalysisManager().options;
01521   const Decl *D = N->getLocationContext()->getDecl();
01522 
01523   if (isInStdNamespace(D)) {
01524     // Skip reports within the 'std' namespace. Although these can sometimes be
01525     // the user's fault, we currently don't report them very well, and
01526     // Note that this will not help for any other data structure libraries, like
01527     // TR1, Boost, or llvm/ADT.
01528     if (Options.shouldSuppressFromCXXStandardLibrary()) {
01529       BR.markInvalid(getTag(), nullptr);
01530       return nullptr;
01531 
01532     } else {
01533       // If the the complete 'std' suppression is not enabled, suppress reports
01534       // from the 'std' namespace that are known to produce false positives.
01535 
01536       // The analyzer issues a false use-after-free when std::list::pop_front
01537       // or std::list::pop_back are called multiple times because we cannot
01538       // reason about the internal invariants of the datastructure.
01539       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
01540         const CXXRecordDecl *CD = MD->getParent();
01541         if (CD->getName() == "list") {
01542           BR.markInvalid(getTag(), nullptr);
01543           return nullptr;
01544         }
01545       }
01546 
01547       // The analyzer issues a false positive on
01548       //   std::basic_string<uint8_t> v; v.push_back(1);
01549       // and
01550       //   std::u16string s; s += u'a';
01551       // because we cannot reason about the internal invariants of the
01552       // datastructure.
01553       for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
01554            LCtx = LCtx->getParent()) {
01555         const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
01556         if (!MD)
01557           continue;
01558 
01559         const CXXRecordDecl *CD = MD->getParent();
01560         if (CD->getName() == "basic_string") {
01561           BR.markInvalid(getTag(), nullptr);
01562           return nullptr;
01563         }
01564       }
01565     }
01566   }
01567 
01568   // Skip reports within the sys/queue.h macros as we do not have the ability to
01569   // reason about data structure shapes.
01570   SourceManager &SM = BRC.getSourceManager();
01571   FullSourceLoc Loc = BR.getLocation(SM).asLocation();
01572   while (Loc.isMacroID()) {
01573     Loc = Loc.getSpellingLoc();
01574     if (SM.getFilename(Loc).endswith("sys/queue.h")) {
01575       BR.markInvalid(getTag(), nullptr);
01576       return nullptr;
01577     }
01578   }
01579 
01580   return nullptr;
01581 }
01582 
01583 PathDiagnosticPiece *
01584 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
01585                                   const ExplodedNode *PrevN,
01586                                   BugReporterContext &BRC,
01587                                   BugReport &BR) {
01588 
01589   ProgramStateRef State = N->getState();
01590   ProgramPoint ProgLoc = N->getLocation();
01591 
01592   // We are only interested in visiting CallEnter nodes.
01593   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
01594   if (!CEnter)
01595     return nullptr;
01596 
01597   // Check if one of the arguments is the region the visitor is tracking.
01598   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
01599   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
01600   unsigned Idx = 0;
01601   ArrayRef<ParmVarDecl*> parms = Call->parameters();
01602 
01603   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
01604                               I != E; ++I, ++Idx) {
01605     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
01606 
01607     // Are we tracking the argument or its subregion?
01608     if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
01609       continue;
01610 
01611     // Check the function parameter type.
01612     const ParmVarDecl *ParamDecl = *I;
01613     assert(ParamDecl && "Formal parameter has no decl?");
01614     QualType T = ParamDecl->getType();
01615 
01616     if (!(T->isAnyPointerType() || T->isReferenceType())) {
01617       // Function can only change the value passed in by address.
01618       continue;
01619     }
01620     
01621     // If it is a const pointer value, the function does not intend to
01622     // change the value.
01623     if (T->getPointeeType().isConstQualified())
01624       continue;
01625 
01626     // Mark the call site (LocationContext) as interesting if the value of the 
01627     // argument is undefined or '0'/'NULL'.
01628     SVal BoundVal = State->getSVal(R);
01629     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
01630       BR.markInteresting(CEnter->getCalleeContext());
01631       return nullptr;
01632     }
01633   }
01634   return nullptr;
01635 }