Clang Project

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