ArrayBoundCheckerV2.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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/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/CheckerContext.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.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 std::unique_ptr<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(nullptr), byteOffset(UnknownVal()) {}
  43. public:
  44. RegionRawOffsetV2(const SubRegion* base, SVal offset)
  45. : baseRegion(base), byteOffset(offset) {}
  46. NonLoc getByteOffset() const { return byteOffset.castAs<NonLoc>(); }
  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 (Optional<NonLoc> NV = extentBegin.getAs<NonLoc>()) {
  94. SVal lowerBound =
  95. svalBuilder.evalBinOpNN(state, BO_LT, rawOffset.getByteOffset(), *NV,
  96. svalBuilder.getConditionType());
  97. Optional<NonLoc> lowerBoundToCheck = lowerBound.getAs<NonLoc>();
  98. if (!lowerBoundToCheck)
  99. return;
  100. ProgramStateRef state_precedesLowerBound, state_withinLowerBound;
  101. std::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 (!extentVal.getAs<NonLoc>())
  118. break;
  119. SVal upperbound
  120. = svalBuilder.evalBinOpNN(state, BO_GE, rawOffset.getByteOffset(),
  121. extentVal.castAs<NonLoc>(),
  122. svalBuilder.getConditionType());
  123. Optional<NonLoc> upperboundToCheck = upperbound.getAs<NonLoc>();
  124. if (!upperboundToCheck)
  125. break;
  126. ProgramStateRef state_exceedsUpperBound, state_withinUpperBound;
  127. std::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(this, "Out-of-bound access"));
  156. // FIXME: This diagnostics are preliminary. We should get far better
  157. // diagnostics for explaining buffer overruns.
  158. 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(
  173. llvm::make_unique<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. // Lazily computes a value to be used by 'computeOffset'. If 'val'
  182. // is unknown or undefined, we lazily substitute '0'. Otherwise,
  183. // return 'val'.
  184. static inline SVal getValue(SVal val, SValBuilder &svalBuilder) {
  185. return val.getAs<UndefinedVal>() ? svalBuilder.makeArrayIndex(0) : val;
  186. }
  187. // Scale a base value by a scaling factor, and return the scaled
  188. // value as an SVal. Used by 'computeOffset'.
  189. static inline SVal scaleValue(ProgramStateRef state,
  190. NonLoc baseVal, CharUnits scaling,
  191. SValBuilder &sb) {
  192. return sb.evalBinOpNN(state, BO_Mul, baseVal,
  193. sb.makeArrayIndex(scaling.getQuantity()),
  194. sb.getArrayIndexType());
  195. }
  196. // Add an SVal to another, treating unknown and undefined values as
  197. // summing to UnknownVal. Used by 'computeOffset'.
  198. static SVal addValue(ProgramStateRef state, SVal x, SVal y,
  199. SValBuilder &svalBuilder) {
  200. // We treat UnknownVals and UndefinedVals the same here because we
  201. // only care about computing offsets.
  202. if (x.isUnknownOrUndef() || y.isUnknownOrUndef())
  203. return UnknownVal();
  204. return svalBuilder.evalBinOpNN(state, BO_Add, x.castAs<NonLoc>(),
  205. y.castAs<NonLoc>(),
  206. svalBuilder.getArrayIndexType());
  207. }
  208. /// Compute a raw byte offset from a base region. Used for array bounds
  209. /// checking.
  210. RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state,
  211. SValBuilder &svalBuilder,
  212. SVal location)
  213. {
  214. const MemRegion *region = location.getAsRegion();
  215. SVal offset = UndefinedVal();
  216. while (region) {
  217. switch (region->getKind()) {
  218. default: {
  219. if (const SubRegion *subReg = dyn_cast<SubRegion>(region)) {
  220. offset = getValue(offset, svalBuilder);
  221. if (!offset.isUnknownOrUndef())
  222. return RegionRawOffsetV2(subReg, offset);
  223. }
  224. return RegionRawOffsetV2();
  225. }
  226. case MemRegion::ElementRegionKind: {
  227. const ElementRegion *elemReg = cast<ElementRegion>(region);
  228. SVal index = elemReg->getIndex();
  229. if (!index.getAs<NonLoc>())
  230. return RegionRawOffsetV2();
  231. QualType elemType = elemReg->getElementType();
  232. // If the element is an incomplete type, go no further.
  233. ASTContext &astContext = svalBuilder.getContext();
  234. if (elemType->isIncompleteType())
  235. return RegionRawOffsetV2();
  236. // Update the offset.
  237. offset = addValue(state,
  238. getValue(offset, svalBuilder),
  239. scaleValue(state,
  240. index.castAs<NonLoc>(),
  241. astContext.getTypeSizeInChars(elemType),
  242. svalBuilder),
  243. svalBuilder);
  244. if (offset.isUnknownOrUndef())
  245. return RegionRawOffsetV2();
  246. region = elemReg->getSuperRegion();
  247. continue;
  248. }
  249. }
  250. }
  251. return RegionRawOffsetV2();
  252. }
  253. void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
  254. mgr.registerChecker<ArrayBoundCheckerV2>();
  255. }