clang  3.7.0
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.generateSink(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  return;
80 }
81 
82 void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
83  if (!DS->isSingleDecl())
84  return;
85 
86  const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
87  if (!VD)
88  return;
89 
90  ASTContext &Ctx = C.getASTContext();
91  const VariableArrayType *VLA = Ctx.getAsVariableArrayType(VD->getType());
92  if (!VLA)
93  return;
94 
95  // FIXME: Handle multi-dimensional VLAs.
96  const Expr *SE = VLA->getSizeExpr();
97  ProgramStateRef state = C.getState();
98  SVal sizeV = state->getSVal(SE, C.getLocationContext());
99 
100  if (sizeV.isUndef()) {
101  reportBug(VLA_Garbage, SE, state, C);
102  return;
103  }
104 
105  // See if the size value is known. It can't be undefined because we would have
106  // warned about that already.
107  if (sizeV.isUnknown())
108  return;
109 
110  // Check if the size is tainted.
111  if (state->isTainted(sizeV)) {
112  reportBug(VLA_Tainted, SE, nullptr, C);
113  return;
114  }
115 
116  // Check if the size is zero.
117  DefinedSVal sizeD = sizeV.castAs<DefinedSVal>();
118 
119  ProgramStateRef stateNotZero, stateZero;
120  std::tie(stateNotZero, stateZero) = state->assume(sizeD);
121 
122  if (stateZero && !stateNotZero) {
123  reportBug(VLA_Zero, SE, stateZero, C);
124  return;
125  }
126 
127  // From this point on, assume that the size is not zero.
128  state = stateNotZero;
129 
130  // VLASizeChecker is responsible for defining the extent of the array being
131  // declared. We do this by multiplying the array length by the element size,
132  // then matching that with the array region's extent symbol.
133 
134  // Check if the size is negative.
135  SValBuilder &svalBuilder = C.getSValBuilder();
136 
137  QualType Ty = SE->getType();
138  DefinedOrUnknownSVal Zero = svalBuilder.makeZeroVal(Ty);
139 
140  SVal LessThanZeroVal = svalBuilder.evalBinOp(state, BO_LT, sizeD, Zero, Ty);
141  if (Optional<DefinedSVal> LessThanZeroDVal =
142  LessThanZeroVal.getAs<DefinedSVal>()) {
144  ProgramStateRef StatePos, StateNeg;
145 
146  std::tie(StateNeg, StatePos) = CM.assumeDual(state, *LessThanZeroDVal);
147  if (StateNeg && !StatePos) {
148  reportBug(VLA_Negative, SE, state, C);
149  return;
150  }
151  state = StatePos;
152  }
153 
154  // Convert the array length to size_t.
155  QualType SizeTy = Ctx.getSizeType();
156  NonLoc ArrayLength =
157  svalBuilder.evalCast(sizeD, SizeTy, SE->getType()).castAs<NonLoc>();
158 
159  // Get the element size.
160  CharUnits EleSize = Ctx.getTypeSizeInChars(VLA->getElementType());
161  SVal EleSizeVal = svalBuilder.makeIntVal(EleSize.getQuantity(), SizeTy);
162 
163  // Multiply the array length by the element size.
164  SVal ArraySizeVal = svalBuilder.evalBinOpNN(
165  state, BO_Mul, ArrayLength, EleSizeVal.castAs<NonLoc>(), SizeTy);
166 
167  // Finally, assume that the array's extent matches the given size.
168  const LocationContext *LC = C.getLocationContext();
169  DefinedOrUnknownSVal Extent =
170  state->getRegion(VD, LC)->getExtent(svalBuilder);
171  DefinedOrUnknownSVal ArraySize = ArraySizeVal.castAs<DefinedOrUnknownSVal>();
172  DefinedOrUnknownSVal sizeIsKnown =
173  svalBuilder.evalEQ(state, Extent, ArraySize);
174  state = state->assume(sizeIsKnown, true);
175 
176  // Assume should not fail at this point.
177  assert(state);
178 
179  // Remember our assumptions!
180  C.addTransition(state);
181 }
182 
183 void ento::registerVLASizeChecker(CheckerManager &mgr) {
184  mgr.registerChecker<VLASizeChecker>();
185 }
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:232
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:163
ExplodedNode * addTransition(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generates a new transition in the program state graph (ExplodedGraph). Uses the default CheckerContex...
SVal evalCast(SVal val, QualType castTy, QualType originalType)
Expr * getSizeExpr() const
Definition: Type.h:2568
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
LineState State
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getType() const
Definition: Decl.h:538
ProgramStatePair assumeDual(ProgramStateRef State, DefinedSVal Cond)
ExplodedNode * generateSink(ProgramStateRef State=nullptr, ExplodedNode *Pred=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a sink node. Generating a sink stops exploration of the given path.
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
Definition: SValBuilder.cpp:32
const ProgramStateRef & getState() const
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
Definition: SVals.h:86
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
ConstraintManager & getConstraintManager()
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
Kind
CHECKER * registerChecker()
Used to register checkers.
bool isSingleDecl() const
Definition: Stmt.h:463
bool isUndef() const
Definition: SVals.h:121
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
const Decl * getSingleDecl() const
Definition: Stmt.h:467
QualType getType() const
Definition: Expr.h:125
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2006
bool isUnknown() const
Definition: SVals.h:117
DefinedOrUnknownSVal evalEQ(ProgramStateRef state, DefinedOrUnknownSVal lhs, DefinedOrUnknownSVal rhs)
bool trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S, BugReport &R, bool IsArg=false, bool EnableNullFPSuppression=true)
SValBuilder & getSValBuilder()
QualType getElementType() const
Definition: Type.h:2434
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:75
const LocationContext * getLocationContext() const