clang  7.0.0svn
UndefResultChecker.cpp
Go to the documentation of this file.
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"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 namespace {
28 class UndefResultChecker
29  : public Checker< check::PostStmt<BinaryOperator> > {
30 
31  mutable std::unique_ptr<BugType> BT;
32 
33 public:
34  void checkPostStmt(const BinaryOperator *B, CheckerContext &C) const;
35 };
36 } // end anonymous namespace
37 
38 static bool isArrayIndexOutOfBounds(CheckerContext &C, const Expr *Ex) {
40 
41  if (!isa<ArraySubscriptExpr>(Ex))
42  return false;
43 
44  SVal Loc = C.getSVal(Ex);
45  if (!Loc.isValid())
46  return false;
47 
48  const MemRegion *MR = Loc.castAs<loc::MemRegionVal>().getRegion();
49  const ElementRegion *ER = dyn_cast<ElementRegion>(MR);
50  if (!ER)
51  return false;
52 
55  state, ER->getSuperRegion(), ER->getValueType());
56  ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true);
57  ProgramStateRef StOutBound = state->assumeInBound(Idx, NumElements, false);
58  return StOutBound && !StInBound;
59 }
60 
61 static bool isShiftOverflow(const BinaryOperator *B, CheckerContext &C) {
62  return C.isGreaterOrEqual(
63  B->getRHS(), C.getASTContext().getIntWidth(B->getLHS()->getType()));
64 }
65 
67  CheckerContext &C) {
68  SValBuilder &SB = C.getSValBuilder();
70  const llvm::APSInt *LHS = SB.getKnownValue(State, C.getSVal(B->getLHS()));
71  const llvm::APSInt *RHS = SB.getKnownValue(State, C.getSVal(B->getRHS()));
72  return (unsigned)RHS->getZExtValue() > LHS->countLeadingZeros();
73 }
74 
75 void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
76  CheckerContext &C) const {
77  if (C.getSVal(B).isUndef()) {
78 
79  // Do not report assignments of uninitialized values inside swap functions.
80  // This should allow to swap partially uninitialized structs
81  // (radar://14129997)
82  if (const FunctionDecl *EnclosingFunctionDecl =
83  dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
84  if (C.getCalleeName(EnclosingFunctionDecl) == "swap")
85  return;
86 
87  // Generate an error node.
89  if (!N)
90  return;
91 
92  if (!BT)
93  BT.reset(
94  new BuiltinBug(this, "Result of operation is garbage or undefined"));
95 
96  SmallString<256> sbuf;
97  llvm::raw_svector_ostream OS(sbuf);
98  const Expr *Ex = nullptr;
99  bool isLeft = true;
100 
101  if (C.getSVal(B->getLHS()).isUndef()) {
102  Ex = B->getLHS()->IgnoreParenCasts();
103  isLeft = true;
104  }
105  else if (C.getSVal(B->getRHS()).isUndef()) {
106  Ex = B->getRHS()->IgnoreParenCasts();
107  isLeft = false;
108  }
109 
110  if (Ex) {
111  OS << "The " << (isLeft ? "left" : "right") << " operand of '"
113  << "' is a garbage value";
114  if (isArrayIndexOutOfBounds(C, Ex))
115  OS << " due to array index out of bounds";
116  } else {
117  // Neither operand was undefined, but the result is undefined.
118  if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
119  B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
120  C.isNegative(B->getRHS())) {
121  OS << "The result of the "
122  << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
123  : "right")
124  << " shift is undefined because the right operand is negative";
125  } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
126  B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
127  isShiftOverflow(B, C)) {
128 
129  OS << "The result of the "
130  << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
131  : "right")
132  << " shift is undefined due to shifting by ";
133 
134  SValBuilder &SB = C.getSValBuilder();
135  const llvm::APSInt *I =
136  SB.getKnownValue(C.getState(), C.getSVal(B->getRHS()));
137  if (!I)
138  OS << "a value that is";
139  else if (I->isUnsigned())
140  OS << '\'' << I->getZExtValue() << "\', which is";
141  else
142  OS << '\'' << I->getSExtValue() << "\', which is";
143 
144  OS << " greater or equal to the width of type '"
145  << B->getLHS()->getType().getAsString() << "'.";
146  } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
147  C.isNegative(B->getLHS())) {
148  OS << "The result of the left shift is undefined because the left "
149  "operand is negative";
150  } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
153  SValBuilder &SB = C.getSValBuilder();
154  const llvm::APSInt *LHS =
155  SB.getKnownValue(State, C.getSVal(B->getLHS()));
156  const llvm::APSInt *RHS =
157  SB.getKnownValue(State, C.getSVal(B->getRHS()));
158  OS << "The result of the left shift is undefined due to shifting \'"
159  << LHS->getSExtValue() << "\' by \'" << RHS->getZExtValue()
160  << "\', which is unrepresentable in the unsigned version of "
161  << "the return type \'" << B->getLHS()->getType().getAsString()
162  << "\'";
163  } else {
164  OS << "The result of the '"
166  << "' expression is undefined";
167  }
168  }
169  auto report = llvm::make_unique<BugReport>(*BT, OS.str(), N);
170  if (Ex) {
171  report->addRange(Ex->getSourceRange());
172  bugreporter::trackNullOrUndefValue(N, Ex, *report);
173  }
174  else
175  bugreporter::trackNullOrUndefValue(N, B, *report);
176 
177  C.emitReport(std::move(report));
178  }
179 }
180 
181 void ento::registerUndefResultChecker(CheckerManager &mgr) {
182  mgr.registerChecker<UndefResultChecker>();
183 }
virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state, const MemRegion *region, QualType EleTy)
Definition: Store.h:152
Represents a function declaration or definition.
Definition: Decl.h:1714
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:94
ExplodedNode * generateErrorNode(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a transition to a node that will be used to report an error.
NonLoc getIndex() const
Definition: MemRegion.h:1096
Opcode getOpcode() const
Definition: Expr.h:3110
SVal getSVal(const Stmt *S) const
Get the value of arbitrary expressions at this point in the path.
const MemRegion * getSuperRegion() const
Definition: MemRegion.h:443
StringRef getCalleeName(const FunctionDecl *FunDecl) const
Get the name of the called function (path-sensitive).
bool isGreaterOrEqual(const Expr *E, unsigned long long Val)
Returns true if the value of E is greater than or equal to Val under unsigned comparison.
LineState State
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
static bool isShiftOverflow(const BinaryOperator *B, CheckerContext &C)
StringRef getOpcodeStr() const
Definition: Expr.h:3129
static bool isArrayIndexOutOfBounds(CheckerContext &C, const Expr *Ex)
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3069
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2517
static bool isLeftShiftResultUnrepresentable(const BinaryOperator *B, CheckerContext &C)
Expr - This represents one expression.
Definition: Expr.h:106
bool isValid() const
Definition: SVals.h:149
QualType getType() const
Definition: Expr.h:128
CHECKER * registerChecker(AT... Args)
Used to register checkers.
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
StoreManager & getStoreManager()
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:76
Expr * getLHS() const
Definition: Expr.h:3113
Dataflow Directional Tag Classes.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:988
const Decl * getDecl() const
unsigned getIntWidth(QualType T) const
const StackFrameContext * getStackFrame() const
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:104
const ProgramStateRef & getState() const
bool isNegative(const Expr *E)
Returns true if the value of E is negative.
QualType getValueType() const override
Definition: MemRegion.h:1098
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:266
SValBuilder & getSValBuilder()
bool isUndef() const
Definition: SVals.h:141
ElementRegin is used to represent both array elements and casts.
Definition: MemRegion.h:1076
virtual const llvm::APSInt * getKnownValue(ProgramStateRef state, SVal val)=0
Evaluates a given SVal.
Expr * getRHS() const
Definition: Expr.h:3115