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