1 // BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a set of BugReporter "visitors" which can be used to
11 // enhance the diagnostics reported for a bug.
13 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
24 using namespace clang;
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 const Stmt *bugreporter::GetDerefExpr(const ExplodedNode *N) {
32 // Pattern match for a few useful cases (do something smarter later):
34 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
36 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(S)) {
37 if (U->getOpcode() == UO_Deref)
38 return U->getSubExpr()->IgnoreParenCasts();
40 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
41 return ME->getBase()->IgnoreParenCasts();
43 else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(S)) {
50 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
51 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
52 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
57 const Stmt *bugreporter::GetCalleeExpr(const ExplodedNode *N) {
58 // Callee is checked as a PreVisit to the CallExpr.
59 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
60 if (const CallExpr *CE = dyn_cast<CallExpr>(S))
61 return CE->getCallee();
65 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
66 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
67 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
68 return RS->getRetValue();
72 //===----------------------------------------------------------------------===//
73 // Definitions for bug reporter visitors.
74 //===----------------------------------------------------------------------===//
77 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
78 const ExplodedNode *EndPathNode,
84 BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
85 const ExplodedNode *EndPathNode,
87 const ProgramPoint &PP = EndPathNode->getLocation();
88 PathDiagnosticLocation L;
90 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&PP)) {
91 const CFGBlock *block = BE->getBlock();
92 if (block->getBlockID() == 0) {
93 L = PathDiagnosticLocation::createDeclEnd(PP.getLocationContext(),
94 BRC.getSourceManager());
99 const Stmt *S = BR.getStmt();
104 L = PathDiagnosticLocation(S, BRC.getSourceManager(),
105 PP.getLocationContext());
108 BugReport::ranges_iterator Beg, End;
109 llvm::tie(Beg, End) = BR.getRanges();
111 // Only add the statement itself as a range if we didn't specify any
112 // special ranges for this report.
113 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
116 for (; Beg != End; ++Beg)
123 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
130 PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *N,
131 const ExplodedNode *PrevN,
132 BugReporterContext &BRC,
139 const ExplodedNode *Node = N, *Last = NULL;
141 for ( ; Node ; Last = Node, Node = Node->getFirstPred()) {
143 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
144 if (const PostStmt *P = Node->getLocationAs<PostStmt>())
145 if (const DeclStmt *DS = P->getStmtAs<DeclStmt>())
146 if (DS->getSingleDecl() == VR->getDecl()) {
152 if (Node->getState()->getSVal(R) != V)
156 if (!Node || !Last) {
168 llvm::SmallString<256> sbuf;
169 llvm::raw_svector_ostream os(sbuf);
171 if (const PostStmt *PS = N->getLocationAs<PostStmt>()) {
172 if (const DeclStmt *DS = PS->getStmtAs<DeclStmt>()) {
174 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
175 os << "Variable '" << *VR->getDecl() << "' ";
180 if (isa<loc::ConcreteInt>(V)) {
182 if (R->isBoundable()) {
183 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
184 if (TR->getValueType()->isObjCObjectPointerType()) {
185 os << "initialized to nil";
192 os << "initialized to a null pointer value";
194 else if (isa<nonloc::ConcreteInt>(V)) {
195 os << "initialized to " << cast<nonloc::ConcreteInt>(V).getValue();
197 else if (V.isUndef()) {
198 if (isa<VarRegion>(R)) {
199 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
201 os << "initialized to a garbage value";
203 os << "declared without an initial value";
209 if (os.str().empty()) {
210 if (isa<loc::ConcreteInt>(V)) {
212 if (R->isBoundable()) {
213 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
214 if (TR->getValueType()->isObjCObjectPointerType()) {
215 os << "nil object reference stored to ";
222 os << "Null pointer value stored to ";
224 else if (V.isUndef()) {
225 os << "Uninitialized value stored to ";
227 else if (isa<nonloc::ConcreteInt>(V)) {
228 os << "The value " << cast<nonloc::ConcreteInt>(V).getValue()
229 << " is assigned to ";
234 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
235 os << '\'' << *VR->getDecl() << '\'';
241 // Construct a new PathDiagnosticPiece.
242 ProgramPoint P = N->getLocation();
243 PathDiagnosticLocation L =
244 PathDiagnosticLocation::create(P, BRC.getSourceManager());
247 return new PathDiagnosticEventPiece(L, os.str());
250 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
253 ID.AddBoolean(Assumption);
257 PathDiagnosticPiece *
258 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
259 const ExplodedNode *PrevN,
260 BugReporterContext &BRC,
265 // Check if in the previous state it was feasible for this constraint
267 if (PrevN->getState()->assume(Constraint, !Assumption)) {
271 // As a sanity check, make sure that the negation of the constraint
272 // was infeasible in the current state. If it is feasible, we somehow
273 // missed the transition point.
274 if (N->getState()->assume(Constraint, !Assumption))
277 // We found the transition point for the constraint. We now need to
278 // pretty-print the constraint. (work-in-progress)
280 llvm::raw_string_ostream os(sbuf);
282 if (isa<Loc>(Constraint)) {
283 os << "Assuming pointer value is ";
284 os << (Assumption ? "non-null" : "null");
287 if (os.str().empty())
290 // Construct a new PathDiagnosticPiece.
291 ProgramPoint P = N->getLocation();
292 PathDiagnosticLocation L =
293 PathDiagnosticLocation::create(P, BRC.getSourceManager());
296 return new PathDiagnosticEventPiece(L, os.str());
303 bugreporter::getTrackNullOrUndefValueVisitor(const ExplodedNode *N,
308 ProgramStateManager &StateMgr = N->getState()->getStateManager();
310 // Walk through nodes until we get one that matches the statement
313 const ProgramPoint &pp = N->getLocation();
314 if (const PostStmt *ps = dyn_cast<PostStmt>(&pp)) {
315 if (ps->getStmt() == S)
318 N = N->getFirstPred();
324 const ProgramState *state = N->getState();
326 // Walk through lvalue-to-rvalue conversions.
327 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S)) {
328 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
330 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
333 SVal V = state->getSVal(loc::MemRegionVal(R));
335 if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)
337 return new FindLastStoreBRVisitor(V, R);
342 SVal V = state->getSValAsScalarOrLoc(S);
344 // Uncomment this to find cases where we aren't properly getting the
345 // base value that was dereferenced.
346 // assert(!V.isUnknownOrUndef());
348 // Is it a symbolic value?
349 if (loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&V)) {
350 const SubRegion *R = cast<SubRegion>(L->getRegion());
351 while (R && !isa<SymbolicRegion>(R)) {
352 R = dyn_cast<SubRegion>(R->getSuperRegion());
356 assert(isa<SymbolicRegion>(R));
357 return new TrackConstraintBRVisitor(loc::MemRegionVal(R), false);
365 FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
366 const MemRegion *R) {
367 assert(R && "The memory region is null.");
369 const ProgramState *state = N->getState();
370 SVal V = state->getSVal(R);
374 return new FindLastStoreBRVisitor(V, R);
378 PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
379 const ExplodedNode *PrevN,
380 BugReporterContext &BRC,
382 const PostStmt *P = N->getLocationAs<PostStmt>();
385 const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
388 const Expr *Receiver = ME->getInstanceReceiver();
391 const ProgramState *state = N->getState();
392 const SVal &V = state->getSVal(Receiver);
393 const DefinedOrUnknownSVal *DV = dyn_cast<DefinedOrUnknownSVal>(&V);
396 state = state->assume(*DV, true);
400 // The receiver was nil, and hence the method was skipped.
401 // Register a BugReporterVisitor to issue a message telling us how
402 // the receiver was null.
403 BR.addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, Receiver));
404 // Issue a message saying that the method was skipped.
405 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
406 N->getLocationContext());
407 return new PathDiagnosticEventPiece(L, "No method actually called "
408 "because the receiver is nil");
411 // Registers every VarDecl inside a Stmt with a last store visitor.
412 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
414 const ExplodedNode *N = BR.getErrorNode();
415 std::deque<const Stmt *> WorkList;
416 WorkList.push_back(S);
418 while (!WorkList.empty()) {
419 const Stmt *Head = WorkList.front();
420 WorkList.pop_front();
422 const ProgramState *state = N->getState();
423 ProgramStateManager &StateMgr = state->getStateManager();
425 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
426 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
428 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
431 SVal V = state->getSVal(S);
433 if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)) {
434 // Register a new visitor with the BugReport.
435 BR.addVisitor(new FindLastStoreBRVisitor(V, R));
440 for (Stmt::const_child_iterator I = Head->child_begin();
441 I != Head->child_end(); ++I)
442 WorkList.push_back(*I);
446 //===----------------------------------------------------------------------===//
447 // Visitor that tries to report interesting diagnostics from conditions.
448 //===----------------------------------------------------------------------===//
449 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
450 const ExplodedNode *Prev,
451 BugReporterContext &BRC,
454 const ProgramPoint &progPoint = N->getLocation();
456 const ProgramState *CurrentState = N->getState();
457 const ProgramState *PrevState = Prev->getState();
459 // Compare the GDMs of the state, because that is where constraints
460 // are managed. Note that ensure that we only look at nodes that
461 // were generated by the analyzer engine proper, not checkers.
462 if (CurrentState->getGDM().getRoot() ==
463 PrevState->getGDM().getRoot())
466 // If an assumption was made on a branch, it should be caught
467 // here by looking at the state transition.
468 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&progPoint)) {
469 const CFGBlock *srcBlk = BE->getSrc();
470 if (const Stmt *term = srcBlk->getTerminator())
471 return VisitTerminator(term, N, srcBlk, BE->getDst(), BRC);
475 if (const PostStmt *PS = dyn_cast<PostStmt>(&progPoint)) {
476 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
478 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
479 cast<GRBugReporter>(BRC.getBugReporter()).
480 getEngine().getEagerlyAssumeTags();
482 const ProgramPointTag *tag = PS->getTag();
483 if (tag == tags.first)
484 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
485 BRC, N->getLocationContext());
486 if (tag == tags.second)
487 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
488 BRC, N->getLocationContext());
496 PathDiagnosticPiece *
497 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
498 const ExplodedNode *N,
499 const CFGBlock *srcBlk,
500 const CFGBlock *dstBlk,
501 BugReporterContext &BRC) {
502 const Expr *Cond = 0;
504 switch (Term->getStmtClass()) {
507 case Stmt::IfStmtClass:
508 Cond = cast<IfStmt>(Term)->getCond();
510 case Stmt::ConditionalOperatorClass:
511 Cond = cast<ConditionalOperator>(Term)->getCond();
516 assert(srcBlk->succ_size() == 2);
517 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
518 return VisitTrueTest(Cond->IgnoreParenNoopCasts(BRC.getASTContext()),
519 tookTrue, BRC, N->getLocationContext());
522 PathDiagnosticPiece *
523 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
525 BugReporterContext &BRC,
526 const LocationContext *LC) {
528 const Expr *Ex = Cond;
531 Ex = Ex->IgnoreParens();
532 switch (Ex->getStmtClass()) {
535 case Stmt::BinaryOperatorClass:
536 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC, LC);
537 case Stmt::DeclRefExprClass:
538 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC, LC);
539 case Stmt::UnaryOperatorClass: {
540 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
541 if (UO->getOpcode() == UO_LNot) {
542 tookTrue = !tookTrue;
543 Ex = UO->getSubExpr()->IgnoreParenNoopCasts(BRC.getASTContext());
552 bool ConditionBRVisitor::patternMatch(const Expr *Ex, llvm::raw_ostream &Out,
553 BugReporterContext &BRC) {
554 const Expr *OriginalExpr = Ex;
555 Ex = Ex->IgnoreParenCasts();
557 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
558 const bool quotes = isa<VarDecl>(DR->getDecl());
561 Out << DR->getDecl()->getDeclName().getAsString();
567 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
568 QualType OriginalTy = OriginalExpr->getType();
569 if (OriginalTy->isPointerType()) {
570 if (IL->getValue() == 0) {
575 else if (OriginalTy->isObjCObjectPointerType()) {
576 if (IL->getValue() == 0) {
582 Out << IL->getValue();
589 PathDiagnosticPiece *
590 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
591 const BinaryOperator *BExpr,
593 BugReporterContext &BRC,
594 const LocationContext *LC) {
596 bool shouldInvert = false;
598 llvm::SmallString<128> LhsString, RhsString;
600 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
601 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC);
602 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC);
604 shouldInvert = !isVarLHS && isVarRHS;
607 if (LhsString.empty() || RhsString.empty())
610 // Should we invert the strings if the LHS is not a variable name?
612 llvm::SmallString<256> buf;
613 llvm::raw_svector_ostream Out(buf);
614 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
616 // Do we need to invert the opcode?
617 BinaryOperator::Opcode Op = BExpr->getOpcode();
622 case BO_LT: Op = BO_GT; break;
623 case BO_GT: Op = BO_LT; break;
624 case BO_LE: Op = BO_GE; break;
625 case BO_GE: Op = BO_LE; break;
630 case BO_EQ: Op = BO_NE; break;
631 case BO_NE: Op = BO_EQ; break;
632 case BO_LT: Op = BO_GE; break;
633 case BO_GT: Op = BO_LE; break;
634 case BO_LE: Op = BO_GT; break;
635 case BO_GE: Op = BO_LT; break;
640 switch (BExpr->getOpcode()) {
645 Out << "not equal to ";
648 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
652 Out << (shouldInvert ? LhsString : RhsString);
654 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LC);
655 return new PathDiagnosticEventPiece(Loc, Out.str());
658 PathDiagnosticPiece *
659 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
660 const DeclRefExpr *DR,
662 BugReporterContext &BRC,
663 const LocationContext *LC) {
665 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
669 llvm::SmallString<256> Buf;
670 llvm::raw_svector_ostream Out(Buf);
673 VD->getDeclName().printName(Out);
676 QualType VDTy = VD->getType();
678 if (VDTy->isPointerType())
679 Out << (tookTrue ? "non-null" : "null");
680 else if (VDTy->isObjCObjectPointerType())
681 Out << (tookTrue ? "non-nil" : "nil");
682 else if (VDTy->isScalarType())
683 Out << (tookTrue ? "not equal to 0" : "0");
687 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LC);
688 return new PathDiagnosticEventPiece(Loc, Out.str());