ArrayBoundCheckerV2.cpp 11 KB

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