ArrayBoundCheckerV2.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. //== 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. #include "ClangSACheckers.h"
  15. #include "clang/StaticAnalyzer/Core/Checker.h"
  16. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  20. #include "clang/AST/CharUnits.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. using namespace clang;
  23. using namespace ento;
  24. namespace {
  25. class ArrayBoundCheckerV2 :
  26. public Checker<check::Location> {
  27. mutable llvm::OwningPtr<BuiltinBug> BT;
  28. enum OOB_Kind { OOB_Precedes, OOB_Excedes, OOB_Tainted };
  29. void reportOOB(CheckerContext &C, ProgramStateRef errorState,
  30. OOB_Kind kind) const;
  31. public:
  32. void checkLocation(SVal l, bool isLoad, const Stmt*S,
  33. CheckerContext &C) const;
  34. };
  35. // FIXME: Eventually replace RegionRawOffset with this class.
  36. class RegionRawOffsetV2 {
  37. private:
  38. const SubRegion *baseRegion;
  39. SVal byteOffset;
  40. RegionRawOffsetV2()
  41. : baseRegion(0), byteOffset(UnknownVal()) {}
  42. public:
  43. RegionRawOffsetV2(const SubRegion* base, SVal offset)
  44. : baseRegion(base), byteOffset(offset) {}
  45. NonLoc getByteOffset() const { return cast<NonLoc>(byteOffset); }
  46. const SubRegion *getRegion() const { return baseRegion; }
  47. static RegionRawOffsetV2 computeOffset(ProgramStateRef state,
  48. SValBuilder &svalBuilder,
  49. SVal location);
  50. void dump() const;
  51. void dumpToStream(raw_ostream &os) const;
  52. };
  53. }
  54. static SVal computeExtentBegin(SValBuilder &svalBuilder,
  55. const MemRegion *region) {
  56. while (true)
  57. switch (region->getKind()) {
  58. default:
  59. return svalBuilder.makeZeroArrayIndex();
  60. case MemRegion::SymbolicRegionKind:
  61. // FIXME: improve this later by tracking symbolic lower bounds
  62. // for symbolic regions.
  63. return UnknownVal();
  64. case MemRegion::ElementRegionKind:
  65. region = cast<SubRegion>(region)->getSuperRegion();
  66. continue;
  67. }
  68. }
  69. void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad,
  70. const Stmt* LoadS,
  71. CheckerContext &checkerContext) const {
  72. // NOTE: Instead of using ProgramState::assumeInBound(), we are prototyping
  73. // some new logic here that reasons directly about memory region extents.
  74. // Once that logic is more mature, we can bring it back to assumeInBound()
  75. // for all clients to use.
  76. //
  77. // The algorithm we are using here for bounds checking is to see if the
  78. // memory access is within the extent of the base region. Since we
  79. // have some flexibility in defining the base region, we can achieve
  80. // various levels of conservatism in our buffer overflow checking.
  81. ProgramStateRef state = checkerContext.getState();
  82. ProgramStateRef originalState = state;
  83. SValBuilder &svalBuilder = checkerContext.getSValBuilder();
  84. const RegionRawOffsetV2 &rawOffset =
  85. RegionRawOffsetV2::computeOffset(state, svalBuilder, location);
  86. if (!rawOffset.getRegion())
  87. return;
  88. // CHECK LOWER BOUND: Is byteOffset < extent begin?
  89. // If so, we are doing a load/store
  90. // before the first valid offset in the memory region.
  91. SVal extentBegin = computeExtentBegin(svalBuilder, rawOffset.getRegion());
  92. if (isa<NonLoc>(extentBegin)) {
  93. SVal lowerBound
  94. = svalBuilder.evalBinOpNN(state, BO_LT, rawOffset.getByteOffset(),
  95. cast<NonLoc>(extentBegin),
  96. svalBuilder.getConditionType());
  97. NonLoc *lowerBoundToCheck = dyn_cast<NonLoc>(&lowerBound);
  98. if (!lowerBoundToCheck)
  99. return;
  100. ProgramStateRef state_precedesLowerBound, state_withinLowerBound;
  101. llvm::tie(state_precedesLowerBound, state_withinLowerBound) =
  102. state->assume(*lowerBoundToCheck);
  103. // Are we constrained enough to definitely precede the lower bound?
  104. if (state_precedesLowerBound && !state_withinLowerBound) {
  105. reportOOB(checkerContext, state_precedesLowerBound, OOB_Precedes);
  106. return;
  107. }
  108. // Otherwise, assume the constraint of the lower bound.
  109. assert(state_withinLowerBound);
  110. state = state_withinLowerBound;
  111. }
  112. do {
  113. // CHECK UPPER BOUND: Is byteOffset >= extent(baseRegion)? If so,
  114. // we are doing a load/store after the last valid offset.
  115. DefinedOrUnknownSVal extentVal =
  116. rawOffset.getRegion()->getExtent(svalBuilder);
  117. if (!isa<NonLoc>(extentVal))
  118. break;
  119. SVal upperbound
  120. = svalBuilder.evalBinOpNN(state, BO_GE, rawOffset.getByteOffset(),
  121. cast<NonLoc>(extentVal),
  122. svalBuilder.getConditionType());
  123. NonLoc *upperboundToCheck = dyn_cast<NonLoc>(&upperbound);
  124. if (!upperboundToCheck)
  125. break;
  126. ProgramStateRef state_exceedsUpperBound, state_withinUpperBound;
  127. llvm::tie(state_exceedsUpperBound, state_withinUpperBound) =
  128. state->assume(*upperboundToCheck);
  129. // If we are under constrained and the index variables are tainted, report.
  130. if (state_exceedsUpperBound && state_withinUpperBound) {
  131. if (state->isTainted(rawOffset.getByteOffset()))
  132. reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted);
  133. return;
  134. }
  135. // If we are constrained enough to definitely exceed the upper bound, report.
  136. if (state_exceedsUpperBound) {
  137. assert(!state_withinUpperBound);
  138. reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
  139. return;
  140. }
  141. assert(state_withinUpperBound);
  142. state = state_withinUpperBound;
  143. }
  144. while (false);
  145. if (state != originalState)
  146. checkerContext.addTransition(state);
  147. }
  148. void ArrayBoundCheckerV2::reportOOB(CheckerContext &checkerContext,
  149. ProgramStateRef errorState,
  150. OOB_Kind kind) const {
  151. ExplodedNode *errorNode = checkerContext.generateSink(errorState);
  152. if (!errorNode)
  153. return;
  154. if (!BT)
  155. BT.reset(new BuiltinBug("Out-of-bound access"));
  156. // FIXME: This diagnostics are preliminary. We should get far better
  157. // diagnostics for explaining buffer overruns.
  158. llvm::SmallString<256> buf;
  159. llvm::raw_svector_ostream os(buf);
  160. os << "Out of bound memory access ";
  161. switch (kind) {
  162. case OOB_Precedes:
  163. os << "(accessed memory precedes memory block)";
  164. break;
  165. case OOB_Excedes:
  166. os << "(access exceeds upper limit of memory block)";
  167. break;
  168. case OOB_Tainted:
  169. os << "(index is tainted)";
  170. break;
  171. }
  172. checkerContext.EmitReport(new BugReport(*BT, os.str(), errorNode));
  173. }
  174. void RegionRawOffsetV2::dump() const {
  175. dumpToStream(llvm::errs());
  176. }
  177. void RegionRawOffsetV2::dumpToStream(raw_ostream &os) const {
  178. os << "raw_offset_v2{" << getRegion() << ',' << getByteOffset() << '}';
  179. }
  180. // FIXME: Merge with the implementation of the same method in Store.cpp
  181. static bool IsCompleteType(ASTContext &Ctx, QualType Ty) {
  182. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  183. const RecordDecl *D = RT->getDecl();
  184. if (!D->getDefinition())
  185. return false;
  186. }
  187. return true;
  188. }
  189. // Lazily computes a value to be used by 'computeOffset'. If 'val'
  190. // is unknown or undefined, we lazily substitute '0'. Otherwise,
  191. // return 'val'.
  192. static inline SVal getValue(SVal val, SValBuilder &svalBuilder) {
  193. return isa<UndefinedVal>(val) ? svalBuilder.makeArrayIndex(0) : val;
  194. }
  195. // Scale a base value by a scaling factor, and return the scaled
  196. // value as an SVal. Used by 'computeOffset'.
  197. static inline SVal scaleValue(ProgramStateRef state,
  198. NonLoc baseVal, CharUnits scaling,
  199. SValBuilder &sb) {
  200. return sb.evalBinOpNN(state, BO_Mul, baseVal,
  201. sb.makeArrayIndex(scaling.getQuantity()),
  202. sb.getArrayIndexType());
  203. }
  204. // Add an SVal to another, treating unknown and undefined values as
  205. // summing to UnknownVal. Used by 'computeOffset'.
  206. static SVal addValue(ProgramStateRef state, SVal x, SVal y,
  207. SValBuilder &svalBuilder) {
  208. // We treat UnknownVals and UndefinedVals the same here because we
  209. // only care about computing offsets.
  210. if (x.isUnknownOrUndef() || y.isUnknownOrUndef())
  211. return UnknownVal();
  212. return svalBuilder.evalBinOpNN(state, BO_Add,
  213. cast<NonLoc>(x), cast<NonLoc>(y),
  214. svalBuilder.getArrayIndexType());
  215. }
  216. /// Compute a raw byte offset from a base region. Used for array bounds
  217. /// checking.
  218. RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state,
  219. SValBuilder &svalBuilder,
  220. SVal location)
  221. {
  222. const MemRegion *region = location.getAsRegion();
  223. SVal offset = UndefinedVal();
  224. while (region) {
  225. switch (region->getKind()) {
  226. default: {
  227. if (const SubRegion *subReg = dyn_cast<SubRegion>(region)) {
  228. offset = getValue(offset, svalBuilder);
  229. if (!offset.isUnknownOrUndef())
  230. return RegionRawOffsetV2(subReg, offset);
  231. }
  232. return RegionRawOffsetV2();
  233. }
  234. case MemRegion::ElementRegionKind: {
  235. const ElementRegion *elemReg = cast<ElementRegion>(region);
  236. SVal index = elemReg->getIndex();
  237. if (!isa<NonLoc>(index))
  238. return RegionRawOffsetV2();
  239. QualType elemType = elemReg->getElementType();
  240. // If the element is an incomplete type, go no further.
  241. ASTContext &astContext = svalBuilder.getContext();
  242. if (!IsCompleteType(astContext, elemType))
  243. return RegionRawOffsetV2();
  244. // Update the offset.
  245. offset = addValue(state,
  246. getValue(offset, svalBuilder),
  247. scaleValue(state,
  248. cast<NonLoc>(index),
  249. astContext.getTypeSizeInChars(elemType),
  250. svalBuilder),
  251. svalBuilder);
  252. if (offset.isUnknownOrUndef())
  253. return RegionRawOffsetV2();
  254. region = elemReg->getSuperRegion();
  255. continue;
  256. }
  257. }
  258. }
  259. return RegionRawOffsetV2();
  260. }
  261. void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
  262. mgr.registerChecker<ArrayBoundCheckerV2>();
  263. }