clang  6.0.0svn
VLASizeChecker.cpp
Go to the documentation of this file.
1 //=== VLASizeChecker.cpp - Undefined dereference checker --------*- 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 VLASizeChecker, a builtin check in ExprEngine that
11 // performs checks for declaration of VLA of undefined or zero size.
12 // In addition, VLASizeChecker is responsible for defining the extent
13 // of the MemRegion that represents a VLA.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "ClangSACheckers.h"
18 #include "clang/AST/CharUnits.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Support/raw_ostream.h"
26 
27 using namespace clang;
28 using namespace ento;
29 
30 namespace {
31 class VLASizeChecker : public Checker< check::PreStmt<DeclStmt> > {
32  mutable std::unique_ptr<BugType> BT;
33  enum VLASize_Kind { VLA_Garbage, VLA_Zero, VLA_Tainted, VLA_Negative };
34 
35  void reportBug(VLASize_Kind Kind,
36  const Expr *SizeE,
38  CheckerContext &C) const;
39 public:
40  void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
41 };
42 } // end anonymous namespace
43 
44 void VLASizeChecker::reportBug(VLASize_Kind Kind,
45  const Expr *SizeE,
47  CheckerContext &C) const {
48  // Generate an error node.
49  ExplodedNode *N = C.generateErrorNode(State);
50  if (!N)
51  return;
52 
53  if (!BT)
54  BT.reset(new BuiltinBug(
55  this, "Dangerous variable-length array (VLA) declaration"));
56 
57  SmallString<256> buf;
58  llvm::raw_svector_ostream os(buf);
59  os << "Declared variable-length array (VLA) ";
60  switch (Kind) {
61  case VLA_Garbage:
62  os << "uses a garbage value as its size";
63  break;
64  case VLA_Zero:
65  os << "has zero size";
66  break;
67  case VLA_Tainted:
68  os << "has tainted size";
69  break;
70  case VLA_Negative:
71  os << "has negative size";
72  break;
73  }
74 
75  auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
76  report->addRange(SizeE->getSourceRange());
77  bugreporter::trackNullOrUndefValue(N, SizeE, *report);
78  C.emitReport(std::move(report));
79 }
80 
81 void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
82  if (!DS->isSingleDecl())
83  return;
84 
85  const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
86  if (!VD)
87  return;
88 
89  ASTContext &Ctx = C.getASTContext();
90  const VariableArrayType *VLA = Ctx.getAsVariableArrayType(VD->getType());
91  if (!VLA)
92  return;
93 
94  // FIXME: Handle multi-dimensional VLAs.
95  const Expr *SE = VLA->getSizeExpr();
97  SVal sizeV = state->getSVal(SE, C.getLocationContext());
98 
99  if (sizeV.isUndef()) {
100  reportBug(VLA_Garbage, SE, state, C);
101  return;
102  }
103 
104  // See if the size value is known. It can't be undefined because we would have
105  // warned about that already.
106  if (sizeV.isUnknown())
107  return;
108 
109  // Check if the size is tainted.
110  if (state->isTainted(sizeV)) {
111  reportBug(VLA_Tainted, SE, nullptr, C);
112  return;
113  }
114 
115  // Check if the size is zero.
116  DefinedSVal sizeD = sizeV.castAs<DefinedSVal>();
117 
118  ProgramStateRef stateNotZero, stateZero;
119  std::tie(stateNotZero, stateZero) = state->assume(sizeD);
120 
121  if (stateZero && !stateNotZero) {
122  reportBug(VLA_Zero, SE, stateZero, C);
123  return;
124  }
125 
126  // From this point on, assume that the size is not zero.
127  state = stateNotZero;
128 
129  // VLASizeChecker is responsible for defining the extent of the array being
130  // declared. We do this by multiplying the array length by the element size,
131  // then matching that with the array region's extent symbol.
132 
133  // Check if the size is negative.
134  SValBuilder &svalBuilder = C.getSValBuilder();
135 
136  QualType Ty = SE->getType();
137  DefinedOrUnknownSVal Zero = svalBuilder.makeZeroVal(Ty);
138 
139  SVal LessThanZeroVal = svalBuilder.evalBinOp(state, BO_LT, sizeD, Zero, Ty);
140  if (Optional<DefinedSVal> LessThanZeroDVal =
141  LessThanZeroVal.getAs<DefinedSVal>()) {
143  ProgramStateRef StatePos, StateNeg;
144 
145  std::tie(StateNeg, StatePos) = CM.assumeDual(state, *LessThanZeroDVal);
146  if (StateNeg && !StatePos) {
147  reportBug(VLA_Negative, SE, state, C);
148  return;
149  }
150  state = StatePos;
151  }
152 
153  // Convert the array length to size_t.
154  QualType SizeTy = Ctx.getSizeType();
155  NonLoc ArrayLength =
156  svalBuilder.evalCast(sizeD, SizeTy, SE->getType()).castAs<NonLoc>();
157 
158  // Get the element size.
159  CharUnits EleSize = Ctx.getTypeSizeInChars(VLA->getElementType());
160  SVal EleSizeVal = svalBuilder.makeIntVal(EleSize.getQuantity(), SizeTy);
161 
162  // Multiply the array length by the element size.
163  SVal ArraySizeVal = svalBuilder.evalBinOpNN(
164  state, BO_Mul, ArrayLength, EleSizeVal.castAs<NonLoc>(), SizeTy);
165 
166  // Finally, assume that the array's extent matches the given size.
167  const LocationContext *LC = C.getLocationContext();
168  DefinedOrUnknownSVal Extent =
169  state->getRegion(VD, LC)->getExtent(svalBuilder);
170  DefinedOrUnknownSVal ArraySize = ArraySizeVal.castAs<DefinedOrUnknownSVal>();
171  DefinedOrUnknownSVal sizeIsKnown =
172  svalBuilder.evalEQ(state, Extent, ArraySize);
173  state = state->assume(sizeIsKnown, true);
174 
175  // Assume should not fail at this point.
176  assert(state);
177 
178  // Remember our assumptions!
179  C.addTransition(state);
180 }
181 
182 void ento::registerVLASizeChecker(CheckerManager &mgr) {
183  mgr.registerChecker<VLASizeChecker>();
184 }
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:254
A (possibly-)qualified type.
Definition: Type.h:653
ExplodedNode * generateErrorNode(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a transition to a node that will be used to report an error.
ExplodedNode * addTransition(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generates a new transition in the program state graph (ExplodedGraph).
SVal evalCast(SVal val, QualType castTy, QualType originalType)
QualType getElementType() const
Definition: Type.h:2595
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:807
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
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
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isUnknown() const
Definition: SVals.h:125
Expr * getSizeExpr() const
Definition: Type.h:2739
ProgramStatePair assumeDual(ProgramStateRef State, DefinedSVal Cond)
Returns a pair of states (StTrue, StFalse) where the given condition is assumed to be true or false...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing &#39;0&#39; for the specified type.
Definition: SValBuilder.cpp:32
Expr - This represents one expression.
Definition: Expr.h:106
QualType getType() const
Definition: Expr.h:128
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
Definition: SVals.h:100
ConstraintManager & getConstraintManager()
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
Kind
CHECKER * registerChecker()
Used to register checkers.
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:487
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:63
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two non- location operands.
Dataflow Directional Tag Classes.
const Decl * getSingleDecl() const
Definition: Stmt.h:504
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl. ...
Definition: Stmt.h:500
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
DefinedOrUnknownSVal evalEQ(ProgramStateRef state, DefinedOrUnknownSVal lhs, DefinedOrUnknownSVal rhs)
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.
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()
bool isUndef() const
Definition: SVals.h:129
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2324
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getType() const
Definition: Decl.h:639
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2719
const LocationContext * getLocationContext() const
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.