blob: 158a7cdfe47e9a00b00cb36f1ddb246bb55abda5 [file] [log] [blame]
Ted Kremenekc478a142010-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 Kyrtzidis05357012011-02-28 01:26:57 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
Ted Kremenekc478a142010-12-23 02:42:43 +000021#include "clang/AST/CharUnits.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000022#include "llvm/ADT/STLExtras.h"
Ted Kremenekc478a142010-12-23 02:42:43 +000023
24using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000025using namespace ento;
Ted Kremenekc478a142010-12-23 02:42:43 +000026
27namespace {
28class ArrayBoundCheckerV2 :
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000029 public Checker<check::Location> {
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +000030 mutable llvm::OwningPtr<BuiltinBug> BT;
Ted Kremenekc478a142010-12-23 02:42:43 +000031
Anna Zaks3bfd6d72012-01-21 05:07:33 +000032 enum OOB_Kind { OOB_Precedes, OOB_Excedes, OOB_Tainted };
Ted Kremenekc478a142010-12-23 02:42:43 +000033
Ted Kremenek8bef8232012-01-26 21:29:00 +000034 void reportOOB(CheckerContext &C, ProgramStateRef errorState,
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +000035 OOB_Kind kind) const;
Ted Kremenekc478a142010-12-23 02:42:43 +000036
37public:
Anna Zaks390909c2011-10-06 00:43:15 +000038 void checkLocation(SVal l, bool isLoad, const Stmt*S,
39 CheckerContext &C) const;
Ted Kremenekc478a142010-12-23 02:42:43 +000040};
41
42// FIXME: Eventually replace RegionRawOffset with this class.
43class RegionRawOffsetV2 {
44private:
45 const SubRegion *baseRegion;
46 SVal byteOffset;
47
48 RegionRawOffsetV2()
49 : baseRegion(0), byteOffset(UnknownVal()) {}
50
51public:
52 RegionRawOffsetV2(const SubRegion* base, SVal offset)
53 : baseRegion(base), byteOffset(offset) {}
54
55 NonLoc getByteOffset() const { return cast<NonLoc>(byteOffset); }
56 const SubRegion *getRegion() const { return baseRegion; }
57
Ted Kremenek8bef8232012-01-26 21:29:00 +000058 static RegionRawOffsetV2 computeOffset(ProgramStateRef state,
Ted Kremenekc478a142010-12-23 02:42:43 +000059 SValBuilder &svalBuilder,
60 SVal location);
61
62 void dump() const;
Ted Kremenek9c378f72011-08-12 23:37:29 +000063 void dumpToStream(raw_ostream &os) const;
Ted Kremenekc478a142010-12-23 02:42:43 +000064};
65}
66
Ted Kremenek82cfc682011-04-12 17:21:33 +000067static SVal computeExtentBegin(SValBuilder &svalBuilder,
68 const MemRegion *region) {
69 while (true)
70 switch (region->getKind()) {
71 default:
72 return svalBuilder.makeZeroArrayIndex();
73 case MemRegion::SymbolicRegionKind:
74 // FIXME: improve this later by tracking symbolic lower bounds
75 // for symbolic regions.
76 return UnknownVal();
77 case MemRegion::ElementRegionKind:
78 region = cast<SubRegion>(region)->getSuperRegion();
79 continue;
80 }
81}
82
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +000083void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad,
Anna Zaks390909c2011-10-06 00:43:15 +000084 const Stmt* LoadS,
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +000085 CheckerContext &checkerContext) const {
Ted Kremenekc478a142010-12-23 02:42:43 +000086
Ted Kremenek18c66fd2011-08-15 22:09:50 +000087 // NOTE: Instead of using ProgramState::assumeInBound(), we are prototyping
Ted Kremenekc478a142010-12-23 02:42:43 +000088 // some new logic here that reasons directly about memory region extents.
89 // Once that logic is more mature, we can bring it back to assumeInBound()
90 // for all clients to use.
91 //
92 // The algorithm we are using here for bounds checking is to see if the
93 // memory access is within the extent of the base region. Since we
94 // have some flexibility in defining the base region, we can achieve
95 // various levels of conservatism in our buffer overflow checking.
Ted Kremenek8bef8232012-01-26 21:29:00 +000096 ProgramStateRef state = checkerContext.getState();
97 ProgramStateRef originalState = state;
Ted Kremenekc478a142010-12-23 02:42:43 +000098
99 SValBuilder &svalBuilder = checkerContext.getSValBuilder();
100 const RegionRawOffsetV2 &rawOffset =
101 RegionRawOffsetV2::computeOffset(state, svalBuilder, location);
102
103 if (!rawOffset.getRegion())
104 return;
105
Ted Kremenek82cfc682011-04-12 17:21:33 +0000106 // CHECK LOWER BOUND: Is byteOffset < extent begin?
107 // If so, we are doing a load/store
Ted Kremenekc478a142010-12-23 02:42:43 +0000108 // before the first valid offset in the memory region.
109
Ted Kremenek82cfc682011-04-12 17:21:33 +0000110 SVal extentBegin = computeExtentBegin(svalBuilder, rawOffset.getRegion());
111
112 if (isa<NonLoc>(extentBegin)) {
113 SVal lowerBound
114 = svalBuilder.evalBinOpNN(state, BO_LT, rawOffset.getByteOffset(),
115 cast<NonLoc>(extentBegin),
116 svalBuilder.getConditionType());
Ted Kremenekc478a142010-12-23 02:42:43 +0000117
Ted Kremenek82cfc682011-04-12 17:21:33 +0000118 NonLoc *lowerBoundToCheck = dyn_cast<NonLoc>(&lowerBound);
119 if (!lowerBoundToCheck)
120 return;
Ted Kremenekc478a142010-12-23 02:42:43 +0000121
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 ProgramStateRef state_precedesLowerBound, state_withinLowerBound;
Ted Kremenek82cfc682011-04-12 17:21:33 +0000123 llvm::tie(state_precedesLowerBound, state_withinLowerBound) =
Ted Kremenekc478a142010-12-23 02:42:43 +0000124 state->assume(*lowerBoundToCheck);
125
Ted Kremenek82cfc682011-04-12 17:21:33 +0000126 // Are we constrained enough to definitely precede the lower bound?
127 if (state_precedesLowerBound && !state_withinLowerBound) {
128 reportOOB(checkerContext, state_precedesLowerBound, OOB_Precedes);
129 return;
130 }
Ted Kremenekc478a142010-12-23 02:42:43 +0000131
Ted Kremenek82cfc682011-04-12 17:21:33 +0000132 // Otherwise, assume the constraint of the lower bound.
133 assert(state_withinLowerBound);
134 state = state_withinLowerBound;
135 }
Ted Kremenekc478a142010-12-23 02:42:43 +0000136
137 do {
138 // CHECK UPPER BOUND: Is byteOffset >= extent(baseRegion)? If so,
139 // we are doing a load/store after the last valid offset.
140 DefinedOrUnknownSVal extentVal =
141 rawOffset.getRegion()->getExtent(svalBuilder);
142 if (!isa<NonLoc>(extentVal))
143 break;
144
145 SVal upperbound
146 = svalBuilder.evalBinOpNN(state, BO_GE, rawOffset.getByteOffset(),
147 cast<NonLoc>(extentVal),
148 svalBuilder.getConditionType());
149
150 NonLoc *upperboundToCheck = dyn_cast<NonLoc>(&upperbound);
151 if (!upperboundToCheck)
152 break;
153
Ted Kremenek8bef8232012-01-26 21:29:00 +0000154 ProgramStateRef state_exceedsUpperBound, state_withinUpperBound;
Ted Kremenekc478a142010-12-23 02:42:43 +0000155 llvm::tie(state_exceedsUpperBound, state_withinUpperBound) =
156 state->assume(*upperboundToCheck);
Anna Zaks9b0970f2011-11-16 19:58:17 +0000157
158 // If we are under constrained and the index variables are tainted, report.
159 if (state_exceedsUpperBound && state_withinUpperBound) {
160 if (state->isTainted(rawOffset.getByteOffset()))
Anna Zaks3bfd6d72012-01-21 05:07:33 +0000161 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted);
Anna Zaks9b0970f2011-11-16 19:58:17 +0000162 return;
163 }
Ted Kremenekc478a142010-12-23 02:42:43 +0000164
Anna Zaks9b0970f2011-11-16 19:58:17 +0000165 // If we are constrained enough to definitely exceed the upper bound, report.
166 if (state_exceedsUpperBound) {
167 assert(!state_withinUpperBound);
Ted Kremenekc478a142010-12-23 02:42:43 +0000168 reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
169 return;
170 }
171
172 assert(state_withinUpperBound);
173 state = state_withinUpperBound;
174 }
175 while (false);
176
177 if (state != originalState)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000178 checkerContext.addTransition(state);
Ted Kremenekc478a142010-12-23 02:42:43 +0000179}
180
181void ArrayBoundCheckerV2::reportOOB(CheckerContext &checkerContext,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000182 ProgramStateRef errorState,
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +0000183 OOB_Kind kind) const {
Ted Kremenekc478a142010-12-23 02:42:43 +0000184
185 ExplodedNode *errorNode = checkerContext.generateSink(errorState);
186 if (!errorNode)
187 return;
188
189 if (!BT)
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +0000190 BT.reset(new BuiltinBug("Out-of-bound access"));
Ted Kremenekc478a142010-12-23 02:42:43 +0000191
192 // FIXME: This diagnostics are preliminary. We should get far better
193 // diagnostics for explaining buffer overruns.
194
195 llvm::SmallString<256> buf;
196 llvm::raw_svector_ostream os(buf);
Anna Zaks3bfd6d72012-01-21 05:07:33 +0000197 os << "Out of bound memory access ";
198 switch (kind) {
199 case OOB_Precedes:
200 os << "(accessed memory precedes memory block)";
201 break;
202 case OOB_Excedes:
203 os << "(access exceeds upper limit of memory block)";
204 break;
205 case OOB_Tainted:
206 os << "(index is tainted)";
207 break;
208 }
Ted Kremenekc478a142010-12-23 02:42:43 +0000209
Anna Zakse172e8b2011-08-17 23:00:25 +0000210 checkerContext.EmitReport(new BugReport(*BT, os.str(), errorNode));
Ted Kremenekc478a142010-12-23 02:42:43 +0000211}
212
213void RegionRawOffsetV2::dump() const {
214 dumpToStream(llvm::errs());
215}
216
Ted Kremenek9c378f72011-08-12 23:37:29 +0000217void RegionRawOffsetV2::dumpToStream(raw_ostream &os) const {
Ted Kremenekc478a142010-12-23 02:42:43 +0000218 os << "raw_offset_v2{" << getRegion() << ',' << getByteOffset() << '}';
219}
220
221// FIXME: Merge with the implementation of the same method in Store.cpp
222static bool IsCompleteType(ASTContext &Ctx, QualType Ty) {
223 if (const RecordType *RT = Ty->getAs<RecordType>()) {
224 const RecordDecl *D = RT->getDecl();
225 if (!D->getDefinition())
226 return false;
227 }
228
229 return true;
230}
231
232
233// Lazily computes a value to be used by 'computeOffset'. If 'val'
234// is unknown or undefined, we lazily substitute '0'. Otherwise,
235// return 'val'.
236static inline SVal getValue(SVal val, SValBuilder &svalBuilder) {
237 return isa<UndefinedVal>(val) ? svalBuilder.makeArrayIndex(0) : val;
238}
239
240// Scale a base value by a scaling factor, and return the scaled
241// value as an SVal. Used by 'computeOffset'.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000242static inline SVal scaleValue(ProgramStateRef state,
Ted Kremenekc478a142010-12-23 02:42:43 +0000243 NonLoc baseVal, CharUnits scaling,
244 SValBuilder &sb) {
245 return sb.evalBinOpNN(state, BO_Mul, baseVal,
246 sb.makeArrayIndex(scaling.getQuantity()),
247 sb.getArrayIndexType());
248}
249
250// Add an SVal to another, treating unknown and undefined values as
251// summing to UnknownVal. Used by 'computeOffset'.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000252static SVal addValue(ProgramStateRef state, SVal x, SVal y,
Ted Kremenekc478a142010-12-23 02:42:43 +0000253 SValBuilder &svalBuilder) {
254 // We treat UnknownVals and UndefinedVals the same here because we
255 // only care about computing offsets.
256 if (x.isUnknownOrUndef() || y.isUnknownOrUndef())
257 return UnknownVal();
258
259 return svalBuilder.evalBinOpNN(state, BO_Add,
260 cast<NonLoc>(x), cast<NonLoc>(y),
261 svalBuilder.getArrayIndexType());
262}
263
264/// Compute a raw byte offset from a base region. Used for array bounds
265/// checking.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000266RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state,
Ted Kremenekc478a142010-12-23 02:42:43 +0000267 SValBuilder &svalBuilder,
268 SVal location)
269{
270 const MemRegion *region = location.getAsRegion();
271 SVal offset = UndefinedVal();
272
273 while (region) {
274 switch (region->getKind()) {
275 default: {
Ted Kremenek82cfc682011-04-12 17:21:33 +0000276 if (const SubRegion *subReg = dyn_cast<SubRegion>(region)) {
277 offset = getValue(offset, svalBuilder);
Ted Kremenekc478a142010-12-23 02:42:43 +0000278 if (!offset.isUnknownOrUndef())
279 return RegionRawOffsetV2(subReg, offset);
Ted Kremenek82cfc682011-04-12 17:21:33 +0000280 }
Ted Kremenekc478a142010-12-23 02:42:43 +0000281 return RegionRawOffsetV2();
282 }
283 case MemRegion::ElementRegionKind: {
284 const ElementRegion *elemReg = cast<ElementRegion>(region);
285 SVal index = elemReg->getIndex();
286 if (!isa<NonLoc>(index))
287 return RegionRawOffsetV2();
288 QualType elemType = elemReg->getElementType();
289 // If the element is an incomplete type, go no further.
290 ASTContext &astContext = svalBuilder.getContext();
291 if (!IsCompleteType(astContext, elemType))
292 return RegionRawOffsetV2();
293
294 // Update the offset.
295 offset = addValue(state,
296 getValue(offset, svalBuilder),
297 scaleValue(state,
Anna Zaks9b0970f2011-11-16 19:58:17 +0000298 cast<NonLoc>(index),
299 astContext.getTypeSizeInChars(elemType),
300 svalBuilder),
Ted Kremenekc478a142010-12-23 02:42:43 +0000301 svalBuilder);
302
303 if (offset.isUnknownOrUndef())
304 return RegionRawOffsetV2();
305
306 region = elemReg->getSuperRegion();
307 continue;
308 }
309 }
310 }
311 return RegionRawOffsetV2();
312}
313
314
Argyrios Kyrtzidis05357012011-02-28 01:26:57 +0000315void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
316 mgr.registerChecker<ArrayBoundCheckerV2>();
317}