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