UndefResultChecker.cpp revision a93d0f280693b8418bc88cf7a8c93325f7fcf4c6
1//=== UndefResultChecker.cpp ------------------------------------*- 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 defines UndefResultChecker, a builtin check in ExprEngine that 11// performs checks for undefined results of non-assignment binary operators. 12// 13//===----------------------------------------------------------------------===// 14 15#include "ClangSACheckers.h" 16#include "clang/StaticAnalyzer/Core/Checker.h" 17#include "clang/StaticAnalyzer/Core/CheckerManager.h" 18#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 19#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 21#include "llvm/ADT/SmallString.h" 22#include "llvm/Support/raw_ostream.h" 23 24using namespace clang; 25using namespace ento; 26 27namespace { 28class UndefResultChecker 29 : public Checker< check::PostStmt<BinaryOperator> > { 30 31 mutable OwningPtr<BugType> BT; 32 33public: 34 void checkPostStmt(const BinaryOperator *B, CheckerContext &C) const; 35}; 36} // end anonymous namespace 37 38void UndefResultChecker::checkPostStmt(const BinaryOperator *B, 39 CheckerContext &C) const { 40 ProgramStateRef state = C.getState(); 41 const LocationContext *LCtx = C.getLocationContext(); 42 if (state->getSVal(B, LCtx).isUndef()) { 43 // Generate an error node. 44 ExplodedNode *N = C.generateSink(); 45 if (!N) 46 return; 47 48 if (!BT) 49 BT.reset(new BuiltinBug("Result of operation is garbage or undefined")); 50 51 SmallString<256> sbuf; 52 llvm::raw_svector_ostream OS(sbuf); 53 const Expr *Ex = NULL; 54 bool isLeft = true; 55 56 if (state->getSVal(B->getLHS(), LCtx).isUndef()) { 57 Ex = B->getLHS()->IgnoreParenCasts(); 58 isLeft = true; 59 } 60 else if (state->getSVal(B->getRHS(), LCtx).isUndef()) { 61 Ex = B->getRHS()->IgnoreParenCasts(); 62 isLeft = false; 63 } 64 65 if (Ex) { 66 OS << "The " << (isLeft ? "left" : "right") 67 << " operand of '" 68 << BinaryOperator::getOpcodeStr(B->getOpcode()) 69 << "' is a garbage value"; 70 } 71 else { 72 // Neither operand was undefined, but the result is undefined. 73 OS << "The result of the '" 74 << BinaryOperator::getOpcodeStr(B->getOpcode()) 75 << "' expression is undefined"; 76 } 77 BugReport *report = new BugReport(*BT, OS.str(), N); 78 if (Ex) { 79 report->addRange(Ex->getSourceRange()); 80 bugreporter::trackNullOrUndefValue(N, Ex, *report); 81 } 82 else 83 bugreporter::trackNullOrUndefValue(N, B, *report); 84 85 C.emitReport(report); 86 } 87} 88 89void ento::registerUndefResultChecker(CheckerManager &mgr) { 90 mgr.registerChecker<UndefResultChecker>(); 91} 92