blob: b944f90539d42c9ac0095b0c38223a4d76f248fa [file] [log] [blame]
Ted Kremeneke73571b2010-12-23 02:42:43 +00001//== ArrayBoundCheckerV2.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 file defines ArrayBoundCheckerV2, which is a path-sensitive check
11// which looks for an out-of-bound array element access.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +000015#include "ClangSACheckers.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/CharUnits.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000018#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +000019#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Gabor Horvath855ad822016-08-22 10:07:32 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000024#include "llvm/Support/raw_ostream.h"
Ted Kremeneke73571b2010-12-23 02:42:43 +000025
26using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000027using namespace ento;
Ted Kremeneke73571b2010-12-23 02:42:43 +000028
29namespace {
Ted Kremenek3a0678e2015-09-08 03:50:52 +000030class ArrayBoundCheckerV2 :
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000031 public Checker<check::Location> {
Ahmed Charlesb8984322014-03-07 20:03:18 +000032 mutable std::unique_ptr<BuiltinBug> BT;
33
Anna Zaksb7eac9f2012-01-21 05:07:33 +000034 enum OOB_Kind { OOB_Precedes, OOB_Excedes, OOB_Tainted };
Ted Kremenek3a0678e2015-09-08 03:50:52 +000035
Ted Kremenek49b1e382012-01-26 21:29:00 +000036 void reportOOB(CheckerContext &C, ProgramStateRef errorState,
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +000037 OOB_Kind kind) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +000038
Ted Kremeneke73571b2010-12-23 02:42:43 +000039public:
Anna Zaks3e0f4152011-10-06 00:43:15 +000040 void checkLocation(SVal l, bool isLoad, const Stmt*S,
41 CheckerContext &C) const;
Ted Kremeneke73571b2010-12-23 02:42:43 +000042};
43
44// FIXME: Eventually replace RegionRawOffset with this class.
45class RegionRawOffsetV2 {
46private:
47 const SubRegion *baseRegion;
48 SVal byteOffset;
Craig Topper0dbb7832014-05-27 02:45:47 +000049
Ted Kremeneke73571b2010-12-23 02:42:43 +000050 RegionRawOffsetV2()
Craig Topper0dbb7832014-05-27 02:45:47 +000051 : baseRegion(nullptr), byteOffset(UnknownVal()) {}
Ted Kremeneke73571b2010-12-23 02:42:43 +000052
53public:
54 RegionRawOffsetV2(const SubRegion* base, SVal offset)
55 : baseRegion(base), byteOffset(offset) {}
56
David Blaikie2fdacbc2013-02-20 05:52:05 +000057 NonLoc getByteOffset() const { return byteOffset.castAs<NonLoc>(); }
Ted Kremeneke73571b2010-12-23 02:42:43 +000058 const SubRegion *getRegion() const { return baseRegion; }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000059
Ted Kremenek49b1e382012-01-26 21:29:00 +000060 static RegionRawOffsetV2 computeOffset(ProgramStateRef state,
Ted Kremeneke73571b2010-12-23 02:42:43 +000061 SValBuilder &svalBuilder,
62 SVal location);
63
64 void dump() const;
Ted Kremenek5ef32db2011-08-12 23:37:29 +000065 void dumpToStream(raw_ostream &os) const;
Ted Kremeneke73571b2010-12-23 02:42:43 +000066};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000067}
Ted Kremeneke73571b2010-12-23 02:42:43 +000068
Ted Kremenek3a0678e2015-09-08 03:50:52 +000069static SVal computeExtentBegin(SValBuilder &svalBuilder,
Ted Kremenek8a4c7602011-04-12 17:21:33 +000070 const MemRegion *region) {
Gabor Horvath73040272016-09-19 20:39:52 +000071 const MemSpaceRegion *SR = region->getMemorySpace();
72 if (SR->getKind() == MemRegion::UnknownSpaceRegionKind)
73 return UnknownVal();
74 else
75 return svalBuilder.makeZeroArrayIndex();
Ted Kremenek8a4c7602011-04-12 17:21:33 +000076}
77
Gabor Horvath855ad822016-08-22 10:07:32 +000078// TODO: once the constraint manager is smart enough to handle non simplified
79// symbolic expressions remove this function. Note that this can not be used in
80// the constraint manager as is, since this does not handle overflows. It is
81// safe to assume, however, that memory offsets will not overflow.
82static std::pair<NonLoc, nonloc::ConcreteInt>
83getSimplifiedOffsets(NonLoc offset, nonloc::ConcreteInt extent,
84 SValBuilder &svalBuilder) {
85 Optional<nonloc::SymbolVal> SymVal = offset.getAs<nonloc::SymbolVal>();
86 if (SymVal && SymVal->isExpression()) {
87 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SymVal->getSymbol())) {
88 llvm::APSInt constant =
89 APSIntType(extent.getValue()).convert(SIE->getRHS());
90 switch (SIE->getOpcode()) {
91 case BO_Mul:
92 // The constant should never be 0 here, since it the result of scaling
93 // based on the size of a type which is never 0.
94 if ((extent.getValue() % constant) != 0)
95 return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
96 else
97 return getSimplifiedOffsets(
98 nonloc::SymbolVal(SIE->getLHS()),
99 svalBuilder.makeIntVal(extent.getValue() / constant),
100 svalBuilder);
101 case BO_Add:
102 return getSimplifiedOffsets(
103 nonloc::SymbolVal(SIE->getLHS()),
104 svalBuilder.makeIntVal(extent.getValue() - constant), svalBuilder);
105 default:
106 break;
107 }
108 }
109 }
110
111 return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
112}
113
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +0000114void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad,
Anna Zaks3e0f4152011-10-06 00:43:15 +0000115 const Stmt* LoadS,
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +0000116 CheckerContext &checkerContext) const {
Ted Kremeneke73571b2010-12-23 02:42:43 +0000117
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000118 // NOTE: Instead of using ProgramState::assumeInBound(), we are prototyping
Ted Kremeneke73571b2010-12-23 02:42:43 +0000119 // some new logic here that reasons directly about memory region extents.
120 // Once that logic is more mature, we can bring it back to assumeInBound()
121 // for all clients to use.
122 //
123 // The algorithm we are using here for bounds checking is to see if the
124 // memory access is within the extent of the base region. Since we
125 // have some flexibility in defining the base region, we can achieve
126 // various levels of conservatism in our buffer overflow checking.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000127 ProgramStateRef state = checkerContext.getState();
Ted Kremenek49b1e382012-01-26 21:29:00 +0000128 ProgramStateRef originalState = state;
Ted Kremeneke73571b2010-12-23 02:42:43 +0000129
130 SValBuilder &svalBuilder = checkerContext.getSValBuilder();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000131 const RegionRawOffsetV2 &rawOffset =
Ted Kremeneke73571b2010-12-23 02:42:43 +0000132 RegionRawOffsetV2::computeOffset(state, svalBuilder, location);
133
134 if (!rawOffset.getRegion())
135 return;
136
Gabor Horvath855ad822016-08-22 10:07:32 +0000137 NonLoc rawOffsetVal = rawOffset.getByteOffset();
138
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000139 // CHECK LOWER BOUND: Is byteOffset < extent begin?
Ted Kremenek8a4c7602011-04-12 17:21:33 +0000140 // If so, we are doing a load/store
Ted Kremeneke73571b2010-12-23 02:42:43 +0000141 // before the first valid offset in the memory region.
142
Ted Kremenek8a4c7602011-04-12 17:21:33 +0000143 SVal extentBegin = computeExtentBegin(svalBuilder, rawOffset.getRegion());
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000144
David Blaikie05785d12013-02-20 22:23:23 +0000145 if (Optional<NonLoc> NV = extentBegin.getAs<NonLoc>()) {
Gabor Horvath855ad822016-08-22 10:07:32 +0000146 if (NV->getAs<nonloc::ConcreteInt>()) {
147 std::pair<NonLoc, nonloc::ConcreteInt> simplifiedOffsets =
148 getSimplifiedOffsets(rawOffset.getByteOffset(),
149 NV->castAs<nonloc::ConcreteInt>(),
150 svalBuilder);
151 rawOffsetVal = simplifiedOffsets.first;
152 *NV = simplifiedOffsets.second;
153 }
154
155 SVal lowerBound = svalBuilder.evalBinOpNN(state, BO_LT, rawOffsetVal, *NV,
156 svalBuilder.getConditionType());
Ted Kremeneke73571b2010-12-23 02:42:43 +0000157
David Blaikie05785d12013-02-20 22:23:23 +0000158 Optional<NonLoc> lowerBoundToCheck = lowerBound.getAs<NonLoc>();
Ted Kremenek8a4c7602011-04-12 17:21:33 +0000159 if (!lowerBoundToCheck)
160 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000161
Ted Kremenek49b1e382012-01-26 21:29:00 +0000162 ProgramStateRef state_precedesLowerBound, state_withinLowerBound;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000163 std::tie(state_precedesLowerBound, state_withinLowerBound) =
Ted Kremeneke73571b2010-12-23 02:42:43 +0000164 state->assume(*lowerBoundToCheck);
165
Ted Kremenek8a4c7602011-04-12 17:21:33 +0000166 // Are we constrained enough to definitely precede the lower bound?
167 if (state_precedesLowerBound && !state_withinLowerBound) {
168 reportOOB(checkerContext, state_precedesLowerBound, OOB_Precedes);
169 return;
170 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000171
Ted Kremenek8a4c7602011-04-12 17:21:33 +0000172 // Otherwise, assume the constraint of the lower bound.
173 assert(state_withinLowerBound);
174 state = state_withinLowerBound;
175 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000176
Ted Kremeneke73571b2010-12-23 02:42:43 +0000177 do {
178 // CHECK UPPER BOUND: Is byteOffset >= extent(baseRegion)? If so,
179 // we are doing a load/store after the last valid offset.
180 DefinedOrUnknownSVal extentVal =
181 rawOffset.getRegion()->getExtent(svalBuilder);
David Blaikie2fdacbc2013-02-20 05:52:05 +0000182 if (!extentVal.getAs<NonLoc>())
Ted Kremeneke73571b2010-12-23 02:42:43 +0000183 break;
184
Gabor Horvath855ad822016-08-22 10:07:32 +0000185 if (extentVal.getAs<nonloc::ConcreteInt>()) {
186 std::pair<NonLoc, nonloc::ConcreteInt> simplifiedOffsets =
187 getSimplifiedOffsets(rawOffset.getByteOffset(),
188 extentVal.castAs<nonloc::ConcreteInt>(),
189 svalBuilder);
190 rawOffsetVal = simplifiedOffsets.first;
191 extentVal = simplifiedOffsets.second;
192 }
193
194 SVal upperbound = svalBuilder.evalBinOpNN(state, BO_GE, rawOffsetVal,
195 extentVal.castAs<NonLoc>(),
196 svalBuilder.getConditionType());
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000197
David Blaikie05785d12013-02-20 22:23:23 +0000198 Optional<NonLoc> upperboundToCheck = upperbound.getAs<NonLoc>();
Ted Kremeneke73571b2010-12-23 02:42:43 +0000199 if (!upperboundToCheck)
200 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000201
Ted Kremenek49b1e382012-01-26 21:29:00 +0000202 ProgramStateRef state_exceedsUpperBound, state_withinUpperBound;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000203 std::tie(state_exceedsUpperBound, state_withinUpperBound) =
Ted Kremeneke73571b2010-12-23 02:42:43 +0000204 state->assume(*upperboundToCheck);
Anna Zaks20829c92011-11-16 19:58:17 +0000205
206 // If we are under constrained and the index variables are tainted, report.
207 if (state_exceedsUpperBound && state_withinUpperBound) {
Gabor Horvath855ad822016-08-22 10:07:32 +0000208 if (state->isTainted(rawOffset.getByteOffset())) {
Anna Zaksb7eac9f2012-01-21 05:07:33 +0000209 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted);
Anna Zaks20829c92011-11-16 19:58:17 +0000210 return;
Gabor Horvath855ad822016-08-22 10:07:32 +0000211 }
212 } else if (state_exceedsUpperBound) {
213 // If we are constrained enough to definitely exceed the upper bound,
214 // report.
Anna Zaks20829c92011-11-16 19:58:17 +0000215 assert(!state_withinUpperBound);
Ted Kremeneke73571b2010-12-23 02:42:43 +0000216 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
217 return;
218 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000219
Ted Kremeneke73571b2010-12-23 02:42:43 +0000220 assert(state_withinUpperBound);
221 state = state_withinUpperBound;
222 }
223 while (false);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000224
Ted Kremeneke73571b2010-12-23 02:42:43 +0000225 if (state != originalState)
Anna Zaksda4c8d62011-10-26 21:06:34 +0000226 checkerContext.addTransition(state);
Ted Kremeneke73571b2010-12-23 02:42:43 +0000227}
228
229void ArrayBoundCheckerV2::reportOOB(CheckerContext &checkerContext,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000230 ProgramStateRef errorState,
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +0000231 OOB_Kind kind) const {
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000232
Devin Coughline39bd402015-09-16 22:03:05 +0000233 ExplodedNode *errorNode = checkerContext.generateErrorNode(errorState);
Ted Kremeneke73571b2010-12-23 02:42:43 +0000234 if (!errorNode)
235 return;
236
237 if (!BT)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000238 BT.reset(new BuiltinBug(this, "Out-of-bound access"));
Ted Kremeneke73571b2010-12-23 02:42:43 +0000239
240 // FIXME: This diagnostics are preliminary. We should get far better
241 // diagnostics for explaining buffer overruns.
242
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000243 SmallString<256> buf;
Ted Kremeneke73571b2010-12-23 02:42:43 +0000244 llvm::raw_svector_ostream os(buf);
Anna Zaksb7eac9f2012-01-21 05:07:33 +0000245 os << "Out of bound memory access ";
246 switch (kind) {
247 case OOB_Precedes:
248 os << "(accessed memory precedes memory block)";
249 break;
250 case OOB_Excedes:
251 os << "(access exceeds upper limit of memory block)";
252 break;
253 case OOB_Tainted:
254 os << "(index is tainted)";
255 break;
256 }
Ted Kremeneke73571b2010-12-23 02:42:43 +0000257
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000258 checkerContext.emitReport(
259 llvm::make_unique<BugReport>(*BT, os.str(), errorNode));
Ted Kremeneke73571b2010-12-23 02:42:43 +0000260}
261
Eric Christopherf18016c2017-11-16 03:18:09 +0000262#ifndef NDEBUG
Yaron Kerencdae9412016-01-29 19:38:18 +0000263LLVM_DUMP_METHOD void RegionRawOffsetV2::dump() const {
Ted Kremeneke73571b2010-12-23 02:42:43 +0000264 dumpToStream(llvm::errs());
265}
266
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000267void RegionRawOffsetV2::dumpToStream(raw_ostream &os) const {
Ted Kremeneke73571b2010-12-23 02:42:43 +0000268 os << "raw_offset_v2{" << getRegion() << ',' << getByteOffset() << '}';
269}
Eric Christopherf18016c2017-11-16 03:18:09 +0000270#endif
Ted Kremeneke73571b2010-12-23 02:42:43 +0000271
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 val, SValBuilder &svalBuilder) {
David Blaikie2fdacbc2013-02-20 05:52:05 +0000276 return val.getAs<UndefinedVal>() ? svalBuilder.makeArrayIndex(0) : val;
Ted Kremeneke73571b2010-12-23 02:42:43 +0000277}
278
279// Scale a base value by a scaling factor, and return the scaled
280// value as an SVal. Used by 'computeOffset'.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000281static inline SVal scaleValue(ProgramStateRef state,
Ted Kremeneke73571b2010-12-23 02:42:43 +0000282 NonLoc baseVal, CharUnits 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'.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000291static SVal addValue(ProgramStateRef state, SVal x, SVal y,
Ted Kremeneke73571b2010-12-23 02:42:43 +0000292 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();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000297
298 return svalBuilder.evalBinOpNN(state, BO_Add, x.castAs<NonLoc>(),
299 y.castAs<NonLoc>(),
Ted Kremeneke73571b2010-12-23 02:42:43 +0000300 svalBuilder.getArrayIndexType());
301}
302
303/// Compute a raw byte offset from a base region. Used for array bounds
304/// checking.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000305RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state,
Ted Kremeneke73571b2010-12-23 02:42:43 +0000306 SValBuilder &svalBuilder,
307 SVal location)
308{
309 const MemRegion *region = location.getAsRegion();
310 SVal offset = UndefinedVal();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000311
Ted Kremeneke73571b2010-12-23 02:42:43 +0000312 while (region) {
313 switch (region->getKind()) {
314 default: {
Ted Kremenek8a4c7602011-04-12 17:21:33 +0000315 if (const SubRegion *subReg = dyn_cast<SubRegion>(region)) {
316 offset = getValue(offset, svalBuilder);
Ted Kremeneke73571b2010-12-23 02:42:43 +0000317 if (!offset.isUnknownOrUndef())
318 return RegionRawOffsetV2(subReg, offset);
Ted Kremenek8a4c7602011-04-12 17:21:33 +0000319 }
Ted Kremeneke73571b2010-12-23 02:42:43 +0000320 return RegionRawOffsetV2();
321 }
322 case MemRegion::ElementRegionKind: {
323 const ElementRegion *elemReg = cast<ElementRegion>(region);
324 SVal index = elemReg->getIndex();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000325 if (!index.getAs<NonLoc>())
Ted Kremeneke73571b2010-12-23 02:42:43 +0000326 return RegionRawOffsetV2();
327 QualType elemType = elemReg->getElementType();
328 // If the element is an incomplete type, go no further.
329 ASTContext &astContext = svalBuilder.getContext();
Anna Zaks0820e132014-10-03 21:49:03 +0000330 if (elemType->isIncompleteType())
Ted Kremeneke73571b2010-12-23 02:42:43 +0000331 return RegionRawOffsetV2();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000332
Ted Kremeneke73571b2010-12-23 02:42:43 +0000333 // Update the offset.
334 offset = addValue(state,
335 getValue(offset, svalBuilder),
336 scaleValue(state,
David Blaikie2fdacbc2013-02-20 05:52:05 +0000337 index.castAs<NonLoc>(),
Anna Zaks20829c92011-11-16 19:58:17 +0000338 astContext.getTypeSizeInChars(elemType),
339 svalBuilder),
Ted Kremeneke73571b2010-12-23 02:42:43 +0000340 svalBuilder);
341
342 if (offset.isUnknownOrUndef())
343 return RegionRawOffsetV2();
344
345 region = elemReg->getSuperRegion();
346 continue;
347 }
348 }
349 }
350 return RegionRawOffsetV2();
351}
352
Argyrios Kyrtzidis0a9ce3e2011-02-28 01:26:57 +0000353void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
354 mgr.registerChecker<ArrayBoundCheckerV2>();
355}