clang  6.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  const LocationContext *LCtx = C.getLocationContext();
41 
42  if (!isa<ArraySubscriptExpr>(Ex))
43  return false;
44 
45  SVal Loc = state->getSVal(Ex, LCtx);
46  if (!Loc.isValid())
47  return false;
48 
49  const MemRegion *MR = Loc.castAs<loc::MemRegionVal>().getRegion();
50  const ElementRegion *ER = dyn_cast<ElementRegion>(MR);
51  if (!ER)
52  return false;
53 
56  state, ER->getSuperRegion(), ER->getValueType());
57  ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true);
58  ProgramStateRef StOutBound = state->assumeInBound(Idx, NumElements, false);
59  return StOutBound && !StInBound;
60 }
61 
62 static bool isShiftOverflow(const BinaryOperator *B, CheckerContext &C) {
63  return C.isGreaterOrEqual(
64  B->getRHS(), C.getASTContext().getIntWidth(B->getLHS()->getType()));
65 }
66 
67 void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
68  CheckerContext &C) const {
70  const LocationContext *LCtx = C.getLocationContext();
71  if (state->getSVal(B, LCtx).isUndef()) {
72 
73  // Do not report assignments of uninitialized values inside swap functions.
74  // This should allow to swap partially uninitialized structs
75  // (radar://14129997)
76  if (const FunctionDecl *EnclosingFunctionDecl =
77  dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
78  if (C.getCalleeName(EnclosingFunctionDecl) == "swap")
79  return;
80 
81  // Generate an error node.
83  if (!N)
84  return;
85 
86  if (!BT)
87  BT.reset(
88  new BuiltinBug(this, "Result of operation is garbage or undefined"));
89 
90  SmallString<256> sbuf;
91  llvm::raw_svector_ostream OS(sbuf);
92  const Expr *Ex = nullptr;
93  bool isLeft = true;
94 
95  if (state->getSVal(B->getLHS(), LCtx).isUndef()) {
96  Ex = B->getLHS()->IgnoreParenCasts();
97  isLeft = true;
98  }
99  else if (state->getSVal(B->getRHS(), LCtx).isUndef()) {
100  Ex = B->getRHS()->IgnoreParenCasts();
101  isLeft = false;
102  }
103 
104  if (Ex) {
105  OS << "The " << (isLeft ? "left" : "right") << " operand of '"
107  << "' is a garbage value";
108  if (isArrayIndexOutOfBounds(C, Ex))
109  OS << " due to array index out of bounds";
110  } else {
111  // Neither operand was undefined, but the result is undefined.
112  if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
113  B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
114  C.isNegative(B->getRHS())) {
115  OS << "The result of the "
116  << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
117  : "right")
118  << " shift is undefined because the right operand is negative";
119  } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
120  B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
121  isShiftOverflow(B, C)) {
122 
123  OS << "The result of the "
124  << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
125  : "right")
126  << " shift is undefined due to shifting by ";
127 
128  SValBuilder &SB = C.getSValBuilder();
129  const llvm::APSInt *I =
130  SB.getKnownValue(C.getState(), C.getSVal(B->getRHS()));
131  if (!I)
132  OS << "a value that is";
133  else if (I->isUnsigned())
134  OS << '\'' << I->getZExtValue() << "\', which is";
135  else
136  OS << '\'' << I->getSExtValue() << "\', which is";
137 
138  OS << " greater or equal to the width of type '"
139  << B->getLHS()->getType().getAsString() << "'.";
140  } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
141  C.isNegative(B->getLHS())) {
142  OS << "The result of the left shift is undefined because the left "
143  "operand is negative";
144  } else {
145  OS << "The result of the '"
147  << "' expression is undefined";
148  }
149  }
150  auto report = llvm::make_unique<BugReport>(*BT, OS.str(), N);
151  if (Ex) {
152  report->addRange(Ex->getSourceRange());
153  bugreporter::trackNullOrUndefValue(N, Ex, *report);
154  }
155  else
156  bugreporter::trackNullOrUndefValue(N, B, *report);
157 
158  C.emitReport(std::move(report));
159  }
160 }
161 
162 void ento::registerUndefResultChecker(CheckerManager &mgr) {
163  mgr.registerChecker<UndefResultChecker>();
164 }
virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state, const MemRegion *region, QualType EleTy)
Definition: Store.h:129
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1698
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:79
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:1085
Opcode getOpcode() const
Definition: Expr.h:3026
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:430
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.
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:3045
static bool isArrayIndexOutOfBounds(CheckerContext &C, const Expr *Ex)
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
std::string getAsString() const
Definition: Type.h:979
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2463
Expr - This represents one expression.
Definition: Expr.h:106
bool isValid() const
Definition: SVals.h:137
QualType getType() const
Definition: Expr.h:128
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
CHECKER * registerChecker()
Used to register checkers.
StoreManager & getStoreManager()
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:63
Expr * getLHS() const
Definition: Expr.h:3029
Dataflow Directional Tag Classes.
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:92
const ProgramStateRef & getState() const
bool isNegative(const Expr *E)
Returns true if the value of E is negative.
bool trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S, BugReport &R, bool IsArg=false, bool EnableNullFPSuppression=true)
Attempts to add visitors to trace a null or undefined value back to its point of origin, whether it is a symbol constrained to null or an explicit assignment.
QualType getValueType() const override
Definition: MemRegion.h:1087
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:265
SValBuilder & getSValBuilder()
ElementRegin is used to represent both array elements and casts.
Definition: MemRegion.h:1066
virtual const llvm::APSInt * getKnownValue(ProgramStateRef state, SVal val)=0
Evaluates a given SVal.
Expr * getRHS() const
Definition: Expr.h:3031
const LocationContext * getLocationContext() const