Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
Line
Count
Source (jump to first uncovered line)
1
//== ArrayBoundCheckerV2.cpp ------------------------------------*- C++ -*--==//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file defines ArrayBoundCheckerV2, which is a path-sensitive check
10
// which looks for an out-of-bound array element access.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "Taint.h"
15
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16
#include "clang/AST/CharUnits.h"
17
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18
#include "clang/StaticAnalyzer/Core/Checker.h"
19
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
23
#include "llvm/ADT/SmallString.h"
24
#include "llvm/Support/raw_ostream.h"
25
26
using namespace clang;
27
using namespace ento;
28
using namespace taint;
29
30
namespace {
31
class ArrayBoundCheckerV2 :
32
    public Checker<check::Location> {
33
  mutable std::unique_ptr<BuiltinBug> BT;
34
35
  enum OOB_Kind { OOB_Precedes, OOB_Excedes, OOB_Tainted };
36
37
  void reportOOB(CheckerContext &C, ProgramStateRef errorState, OOB_Kind kind,
38
                 std::unique_ptr<BugReporterVisitor> Visitor = nullptr) const;
39
40
public:
41
  void checkLocation(SVal l, bool isLoad, const Stmt*S,
42
                     CheckerContext &C) const;
43
};
44
45
// FIXME: Eventually replace RegionRawOffset with this class.
46
class RegionRawOffsetV2 {
47
private:
48
  const SubRegion *baseRegion;
49
  SVal byteOffset;
50
51
  RegionRawOffsetV2()
52
1
    : baseRegion(nullptr), byteOffset(UnknownVal()) {}
53
54
public:
55
  RegionRawOffsetV2(const SubRegion* base, SVal offset)
56
987
    : baseRegion(base), byteOffset(offset) {}
57
58
2.86k
  NonLoc getByteOffset() const { return byteOffset.castAs<NonLoc>(); }
59
2.95k
  const SubRegion *getRegion() const { return baseRegion; }
60
61
  static RegionRawOffsetV2 computeOffset(ProgramStateRef state,
62
                                         SValBuilder &svalBuilder,
63
                                         SVal location);
64
65
  void dump() const;
66
  void dumpToStream(raw_ostream &os) const;
67
};
68
}
69
70
static SVal computeExtentBegin(SValBuilder &svalBuilder,
71
987
                               const MemRegion *region) {
72
987
  const MemSpaceRegion *SR = region->getMemorySpace();
73
987
  if (SR->getKind() == MemRegion::UnknownSpaceRegionKind)
74
43
    return UnknownVal();
75
944
  else
76
944
    return svalBuilder.makeZeroArrayIndex();
77
987
}
78
79
// TODO: once the constraint manager is smart enough to handle non simplified
80
// symbolic expressions remove this function. Note that this can not be used in
81
// the constraint manager as is, since this does not handle overflows. It is
82
// safe to assume, however, that memory offsets will not overflow.
83
static std::pair<NonLoc, nonloc::ConcreteInt>
84
getSimplifiedOffsets(NonLoc offset, nonloc::ConcreteInt extent,
85
1.88k
                     SValBuilder &svalBuilder) {
86
1.88k
  Optional<nonloc::SymbolVal> SymVal = offset.getAs<nonloc::SymbolVal>();
87
1.88k
  if (SymVal && 
SymVal->isExpression()56
) {
88
35
    if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SymVal->getSymbol())) {
89
31
      llvm::APSInt constant =
90
31
          APSIntType(extent.getValue()).convert(SIE->getRHS());
91
31
      switch (SIE->getOpcode()) {
92
31
      case BO_Mul:
93
27
        // The constant should never be 0 here, since it the result of scaling
94
27
        // based on the size of a type which is never 0.
95
27
        if ((extent.getValue() % constant) != 0)
96
0
          return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
97
27
        else
98
27
          return getSimplifiedOffsets(
99
27
              nonloc::SymbolVal(SIE->getLHS()),
100
27
              svalBuilder.makeIntVal(extent.getValue() / constant),
101
27
              svalBuilder);
102
0
      case BO_Add:
103
0
        return getSimplifiedOffsets(
104
0
            nonloc::SymbolVal(SIE->getLHS()),
105
0
            svalBuilder.makeIntVal(extent.getValue() - constant), svalBuilder);
106
4
      default:
107
4
        break;
108
1.85k
      }
109
1.85k
    }
110
35
  }
111
1.85k
112
1.85k
  return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
113
1.85k
}
114
115
void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad,
116
                                        const Stmt* LoadS,
117
988
                                        CheckerContext &checkerContext) const {
118
988
119
988
  // NOTE: Instead of using ProgramState::assumeInBound(), we are prototyping
120
988
  // some new logic here that reasons directly about memory region extents.
121
988
  // Once that logic is more mature, we can bring it back to assumeInBound()
122
988
  // for all clients to use.
123
988
  //
124
988
  // The algorithm we are using here for bounds checking is to see if the
125
988
  // memory access is within the extent of the base region.  Since we
126
988
  // have some flexibility in defining the base region, we can achieve
127
988
  // various levels of conservatism in our buffer overflow checking.
128
988
  ProgramStateRef state = checkerContext.getState();
129
988
130
988
  SValBuilder &svalBuilder = checkerContext.getSValBuilder();
131
988
  const RegionRawOffsetV2 &rawOffset =
132
988
    RegionRawOffsetV2::computeOffset(state, svalBuilder, location);
133
988
134
988
  if (!rawOffset.getRegion())
135
1
    return;
136
987
137
987
  NonLoc rawOffsetVal = rawOffset.getByteOffset();
138
987
139
987
  // CHECK LOWER BOUND: Is byteOffset < extent begin?
140
987
  //  If so, we are doing a load/store
141
987
  //  before the first valid offset in the memory region.
142
987
143
987
  SVal extentBegin = computeExtentBegin(svalBuilder, rawOffset.getRegion());
144
987
145
987
  if (Optional<NonLoc> NV = extentBegin.getAs<NonLoc>()) {
146
944
    if (NV->getAs<nonloc::ConcreteInt>()) {
147
944
      std::pair<NonLoc, nonloc::ConcreteInt> simplifiedOffsets =
148
944
          getSimplifiedOffsets(rawOffset.getByteOffset(),
149
944
                               NV->castAs<nonloc::ConcreteInt>(),
150
944
                               svalBuilder);
151
944
      rawOffsetVal = simplifiedOffsets.first;
152
944
      *NV = simplifiedOffsets.second;
153
944
    }
154
944
155
944
    SVal lowerBound = svalBuilder.evalBinOpNN(state, BO_LT, rawOffsetVal, *NV,
156
944
                                              svalBuilder.getConditionType());
157
944
158
944
    Optional<NonLoc> lowerBoundToCheck = lowerBound.getAs<NonLoc>();
159
944
    if (!lowerBoundToCheck)
160
0
      return;
161
944
162
944
    ProgramStateRef state_precedesLowerBound, state_withinLowerBound;
163
944
    std::tie(state_precedesLowerBound, state_withinLowerBound) =
164
944
      state->assume(*lowerBoundToCheck);
165
944
166
944
    // Are we constrained enough to definitely precede the lower bound?
167
944
    if (state_precedesLowerBound && 
!state_withinLowerBound23
) {
168
12
      reportOOB(checkerContext, state_precedesLowerBound, OOB_Precedes);
169
12
      return;
170
12
    }
171
932
172
932
    // Otherwise, assume the constraint of the lower bound.
173
932
    assert(state_withinLowerBound);
174
932
    state = state_withinLowerBound;
175
932
  }
176
987
177
987
  
do 975
{
178
975
    // CHECK UPPER BOUND: Is byteOffset >= extent(baseRegion)?  If so,
179
975
    // we are doing a load/store after the last valid offset.
180
975
    DefinedOrUnknownSVal extentVal =
181
975
      rawOffset.getRegion()->getExtent(svalBuilder);
182
975
    if (!extentVal.getAs<NonLoc>())
183
2
      break;
184
973
185
973
    if (extentVal.getAs<nonloc::ConcreteInt>()) {
186
914
      std::pair<NonLoc, nonloc::ConcreteInt> simplifiedOffsets =
187
914
          getSimplifiedOffsets(rawOffset.getByteOffset(),
188
914
                               extentVal.castAs<nonloc::ConcreteInt>(),
189
914
                               svalBuilder);
190
914
      rawOffsetVal = simplifiedOffsets.first;
191
914
      extentVal = simplifiedOffsets.second;
192
914
    }
193
973
194
973
    SVal upperbound = svalBuilder.evalBinOpNN(state, BO_GE, rawOffsetVal,
195
973
                                              extentVal.castAs<NonLoc>(),
196
973
                                              svalBuilder.getConditionType());
197
973
198
973
    Optional<NonLoc> upperboundToCheck = upperbound.getAs<NonLoc>();
199
973
    if (!upperboundToCheck)
200
0
      break;
201
973
202
973
    ProgramStateRef state_exceedsUpperBound, state_withinUpperBound;
203
973
    std::tie(state_exceedsUpperBound, state_withinUpperBound) =
204
973
      state->assume(*upperboundToCheck);
205
973
206
973
    // If we are under constrained and the index variables are tainted, report.
207
973
    if (state_exceedsUpperBound && 
state_withinUpperBound36
) {
208
22
      SVal ByteOffset = rawOffset.getByteOffset();
209
22
      if (isTainted(state, ByteOffset)) {
210
11
        reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted,
211
11
                  llvm::make_unique<TaintBugVisitor>(ByteOffset));
212
11
        return;
213
11
      }
214
951
    } else if (state_exceedsUpperBound) {
215
14
      // If we are constrained enough to definitely exceed the upper bound,
216
14
      // report.
217
14
      assert(!state_withinUpperBound);
218
14
      reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
219
14
      return;
220
14
    }
221
948
222
948
    assert(state_withinUpperBound);
223
948
    state = state_withinUpperBound;
224
948
  }
225
975
  while (
false948
);
226
975
227
975
  checkerContext.addTransition(state);
228
950
}
229
230
void ArrayBoundCheckerV2::reportOOB(
231
    CheckerContext &checkerContext, ProgramStateRef errorState, OOB_Kind kind,
232
37
    std::unique_ptr<BugReporterVisitor> Visitor) const {
233
37
234
37
  ExplodedNode *errorNode = checkerContext.generateErrorNode(errorState);
235
37
  if (!errorNode)
236
0
    return;
237
37
238
37
  if (!BT)
239
5
    BT.reset(new BuiltinBug(this, "Out-of-bound access"));
240
37
241
37
  // FIXME: This diagnostics are preliminary.  We should get far better
242
37
  // diagnostics for explaining buffer overruns.
243
37
244
37
  SmallString<256> buf;
245
37
  llvm::raw_svector_ostream os(buf);
246
37
  os << "Out of bound memory access ";
247
37
  switch (kind) {
248
37
  case OOB_Precedes:
249
12
    os << "(accessed memory precedes memory block)";
250
12
    break;
251
37
  case OOB_Excedes:
252
14
    os << "(access exceeds upper limit of memory block)";
253
14
    break;
254
37
  case OOB_Tainted:
255
11
    os << "(index is tainted)";
256
11
    break;
257
37
  }
258
37
259
37
  auto BR = llvm::make_unique<BugReport>(*BT, os.str(), errorNode);
260
37
  BR->addVisitor(std::move(Visitor));
261
37
  checkerContext.emitReport(std::move(BR));
262
37
}
263
264
#ifndef NDEBUG
265
LLVM_DUMP_METHOD void RegionRawOffsetV2::dump() const {
266
  dumpToStream(llvm::errs());
267
}
268
269
void RegionRawOffsetV2::dumpToStream(raw_ostream &os) const {
270
  os << "raw_offset_v2{" << getRegion() << ',' << getByteOffset() << '}';
271
}
272
#endif
273
274
// Lazily computes a value to be used by 'computeOffset'.  If 'val'
275
// is unknown or undefined, we lazily substitute '0'.  Otherwise,
276
// return 'val'.
277
1.09k
static inline SVal getValue(SVal val, SValBuilder &svalBuilder) {
278
1.09k
  return val.getAs<UndefinedVal>() ? 
svalBuilder.makeArrayIndex(0)987
:
val104
;
279
1.09k
}
280
281
// Scale a base value by a scaling factor, and return the scaled
282
// value as an SVal.  Used by 'computeOffset'.
283
static inline SVal scaleValue(ProgramStateRef state,
284
                              NonLoc baseVal, CharUnits scaling,
285
104
                              SValBuilder &sb) {
286
104
  return sb.evalBinOpNN(state, BO_Mul, baseVal,
287
104
                        sb.makeArrayIndex(scaling.getQuantity()),
288
104
                        sb.getArrayIndexType());
289
104
}
290
291
// Add an SVal to another, treating unknown and undefined values as
292
// summing to UnknownVal.  Used by 'computeOffset'.
293
static SVal addValue(ProgramStateRef state, SVal x, SVal y,
294
104
                     SValBuilder &svalBuilder) {
295
104
  // We treat UnknownVals and UndefinedVals the same here because we
296
104
  // only care about computing offsets.
297
104
  if (x.isUnknownOrUndef() || y.isUnknownOrUndef())
298
0
    return UnknownVal();
299
104
300
104
  return svalBuilder.evalBinOpNN(state, BO_Add, x.castAs<NonLoc>(),
301
104
                                 y.castAs<NonLoc>(),
302
104
                                 svalBuilder.getArrayIndexType());
303
104
}
304
305
/// Compute a raw byte offset from a base region.  Used for array bounds
306
/// checking.
307
RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state,
308
                                                   SValBuilder &svalBuilder,
309
                                                   SVal location)
310
988
{
311
988
  const MemRegion *region = location.getAsRegion();
312
988
  SVal offset = UndefinedVal();
313
988
314
1.09k
  while (region) {
315
1.09k
    switch (region->getKind()) {
316
1.09k
      default: {
317
987
        if (const SubRegion *subReg = dyn_cast<SubRegion>(region)) {
318
987
          offset = getValue(offset, svalBuilder);
319
987
          if (!offset.isUnknownOrUndef())
320
987
            return RegionRawOffsetV2(subReg, offset);
321
0
        }
322
0
        return RegionRawOffsetV2();
323
0
      }
324
104
      case MemRegion::ElementRegionKind: {
325
104
        const ElementRegion *elemReg = cast<ElementRegion>(region);
326
104
        SVal index = elemReg->getIndex();
327
104
        if (!index.getAs<NonLoc>())
328
0
          return RegionRawOffsetV2();
329
104
        QualType elemType = elemReg->getElementType();
330
104
        // If the element is an incomplete type, go no further.
331
104
        ASTContext &astContext = svalBuilder.getContext();
332
104
        if (elemType->isIncompleteType())
333
0
          return RegionRawOffsetV2();
334
104
335
104
        // Update the offset.
336
104
        offset = addValue(state,
337
104
                          getValue(offset, svalBuilder),
338
104
                          scaleValue(state,
339
104
                          index.castAs<NonLoc>(),
340
104
                          astContext.getTypeSizeInChars(elemType),
341
104
                          svalBuilder),
342
104
                          svalBuilder);
343
104
344
104
        if (offset.isUnknownOrUndef())
345
0
          return RegionRawOffsetV2();
346
104
347
104
        region = elemReg->getSuperRegion();
348
104
        continue;
349
104
      }
350
1.09k
    }
351
1.09k
  }
352
988
  
return RegionRawOffsetV2()1
;
353
988
}
354
355
8
void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
356
8
  mgr.registerChecker<ArrayBoundCheckerV2>();
357
8
}
358
359
8
bool ento::shouldRegisterArrayBoundCheckerV2(const LangOptions &LO) {
360
8
  return true;
361
8
}