VLASizeChecker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //=== VLASizeChecker.cpp - Undefined dereference checker --------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This defines VLASizeChecker, a builtin check in ExprEngine that
  10. // performs checks for declaration of VLA of undefined or zero size.
  11. // In addition, VLASizeChecker is responsible for defining the extent
  12. // of the MemRegion that represents a VLA.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "Taint.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  19. #include "clang/StaticAnalyzer/Core/Checker.h"
  20. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace clang;
  27. using namespace ento;
  28. using namespace taint;
  29. namespace {
  30. class VLASizeChecker
  31. : public Checker<check::PreStmt<DeclStmt>,
  32. check::PreStmt<UnaryExprOrTypeTraitExpr>> {
  33. mutable std::unique_ptr<BugType> BT;
  34. enum VLASize_Kind {
  35. VLA_Garbage,
  36. VLA_Zero,
  37. VLA_Tainted,
  38. VLA_Negative,
  39. VLA_Overflow
  40. };
  41. /// Check a VLA for validity.
  42. /// Every dimension of the array and the total size is checked for validity.
  43. /// Returns null or a new state where the size is validated.
  44. /// 'ArraySize' will contain SVal that refers to the total size (in char)
  45. /// of the array.
  46. ProgramStateRef checkVLA(CheckerContext &C, ProgramStateRef State,
  47. const VariableArrayType *VLA, SVal &ArraySize) const;
  48. /// Check a single VLA index size expression for validity.
  49. ProgramStateRef checkVLAIndexSize(CheckerContext &C, ProgramStateRef State,
  50. const Expr *SizeE) const;
  51. void reportBug(VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
  52. CheckerContext &C,
  53. std::unique_ptr<BugReporterVisitor> Visitor = nullptr) const;
  54. public:
  55. void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
  56. void checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
  57. CheckerContext &C) const;
  58. };
  59. } // end anonymous namespace
  60. ProgramStateRef VLASizeChecker::checkVLA(CheckerContext &C,
  61. ProgramStateRef State,
  62. const VariableArrayType *VLA,
  63. SVal &ArraySize) const {
  64. assert(VLA && "Function should be called with non-null VLA argument.");
  65. const VariableArrayType *VLALast = nullptr;
  66. llvm::SmallVector<const Expr *, 2> VLASizes;
  67. // Walk over the VLAs for every dimension until a non-VLA is found.
  68. // There is a VariableArrayType for every dimension (fixed or variable) until
  69. // the most inner array that is variably modified.
  70. // Dimension sizes are collected into 'VLASizes'. 'VLALast' is set to the
  71. // innermost VLA that was encountered.
  72. // In "int vla[x][2][y][3]" this will be the array for index "y" (with type
  73. // int[3]). 'VLASizes' contains 'x', '2', and 'y'.
  74. while (VLA) {
  75. const Expr *SizeE = VLA->getSizeExpr();
  76. State = checkVLAIndexSize(C, State, SizeE);
  77. if (!State)
  78. return nullptr;
  79. VLASizes.push_back(SizeE);
  80. VLALast = VLA;
  81. VLA = C.getASTContext().getAsVariableArrayType(VLA->getElementType());
  82. };
  83. assert(VLALast &&
  84. "Array should have at least one variably-modified dimension.");
  85. ASTContext &Ctx = C.getASTContext();
  86. SValBuilder &SVB = C.getSValBuilder();
  87. CanQualType SizeTy = Ctx.getSizeType();
  88. uint64_t SizeMax =
  89. SVB.getBasicValueFactory().getMaxValue(SizeTy).getZExtValue();
  90. // Get the element size.
  91. CharUnits EleSize = Ctx.getTypeSizeInChars(VLALast->getElementType());
  92. NonLoc ArrSize =
  93. SVB.makeIntVal(EleSize.getQuantity(), SizeTy).castAs<NonLoc>();
  94. // Try to calculate the known real size of the array in KnownSize.
  95. uint64_t KnownSize = 0;
  96. if (const llvm::APSInt *KV = SVB.getKnownValue(State, ArrSize))
  97. KnownSize = KV->getZExtValue();
  98. for (const Expr *SizeE : VLASizes) {
  99. auto SizeD = C.getSVal(SizeE).castAs<DefinedSVal>();
  100. // Convert the array length to size_t.
  101. NonLoc IndexLength =
  102. SVB.evalCast(SizeD, SizeTy, SizeE->getType()).castAs<NonLoc>();
  103. // Multiply the array length by the element size.
  104. SVal Mul = SVB.evalBinOpNN(State, BO_Mul, ArrSize, IndexLength, SizeTy);
  105. if (auto MulNonLoc = Mul.getAs<NonLoc>())
  106. ArrSize = *MulNonLoc;
  107. else
  108. // Extent could not be determined.
  109. return State;
  110. if (const llvm::APSInt *IndexLVal = SVB.getKnownValue(State, IndexLength)) {
  111. // Check if the array size will overflow.
  112. // Size overflow check does not work with symbolic expressions because a
  113. // overflow situation can not be detected easily.
  114. uint64_t IndexL = IndexLVal->getZExtValue();
  115. // FIXME: See https://reviews.llvm.org/D80903 for discussion of
  116. // some difference in assume and getKnownValue that leads to
  117. // unexpected behavior. Just bail on IndexL == 0 at this point.
  118. if (IndexL == 0)
  119. return nullptr;
  120. if (KnownSize <= SizeMax / IndexL) {
  121. KnownSize *= IndexL;
  122. } else {
  123. // Array size does not fit into size_t.
  124. reportBug(VLA_Overflow, SizeE, State, C);
  125. return nullptr;
  126. }
  127. } else {
  128. KnownSize = 0;
  129. }
  130. }
  131. ArraySize = ArrSize;
  132. return State;
  133. }
  134. ProgramStateRef VLASizeChecker::checkVLAIndexSize(CheckerContext &C,
  135. ProgramStateRef State,
  136. const Expr *SizeE) const {
  137. SVal SizeV = C.getSVal(SizeE);
  138. if (SizeV.isUndef()) {
  139. reportBug(VLA_Garbage, SizeE, State, C);
  140. return nullptr;
  141. }
  142. // See if the size value is known. It can't be undefined because we would have
  143. // warned about that already.
  144. if (SizeV.isUnknown())
  145. return nullptr;
  146. // Check if the size is tainted.
  147. if (isTainted(State, SizeV)) {
  148. reportBug(VLA_Tainted, SizeE, nullptr, C,
  149. std::make_unique<TaintBugVisitor>(SizeV));
  150. return nullptr;
  151. }
  152. // Check if the size is zero.
  153. DefinedSVal SizeD = SizeV.castAs<DefinedSVal>();
  154. ProgramStateRef StateNotZero, StateZero;
  155. std::tie(StateNotZero, StateZero) = State->assume(SizeD);
  156. if (StateZero && !StateNotZero) {
  157. reportBug(VLA_Zero, SizeE, StateZero, C);
  158. return nullptr;
  159. }
  160. // From this point on, assume that the size is not zero.
  161. State = StateNotZero;
  162. // Check if the size is negative.
  163. SValBuilder &SVB = C.getSValBuilder();
  164. QualType SizeTy = SizeE->getType();
  165. DefinedOrUnknownSVal Zero = SVB.makeZeroVal(SizeTy);
  166. SVal LessThanZeroVal = SVB.evalBinOp(State, BO_LT, SizeD, Zero, SizeTy);
  167. if (Optional<DefinedSVal> LessThanZeroDVal =
  168. LessThanZeroVal.getAs<DefinedSVal>()) {
  169. ConstraintManager &CM = C.getConstraintManager();
  170. ProgramStateRef StatePos, StateNeg;
  171. std::tie(StateNeg, StatePos) = CM.assumeDual(State, *LessThanZeroDVal);
  172. if (StateNeg && !StatePos) {
  173. reportBug(VLA_Negative, SizeE, State, C);
  174. return nullptr;
  175. }
  176. State = StatePos;
  177. }
  178. return State;
  179. }
  180. void VLASizeChecker::reportBug(
  181. VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
  182. CheckerContext &C, std::unique_ptr<BugReporterVisitor> Visitor) const {
  183. // Generate an error node.
  184. ExplodedNode *N = C.generateErrorNode(State);
  185. if (!N)
  186. return;
  187. if (!BT)
  188. BT.reset(new BuiltinBug(
  189. this, "Dangerous variable-length array (VLA) declaration"));
  190. SmallString<256> buf;
  191. llvm::raw_svector_ostream os(buf);
  192. os << "Declared variable-length array (VLA) ";
  193. switch (Kind) {
  194. case VLA_Garbage:
  195. os << "uses a garbage value as its size";
  196. break;
  197. case VLA_Zero:
  198. os << "has zero size";
  199. break;
  200. case VLA_Tainted:
  201. os << "has tainted size";
  202. break;
  203. case VLA_Negative:
  204. os << "has negative size";
  205. break;
  206. case VLA_Overflow:
  207. os << "has too large size";
  208. break;
  209. }
  210. auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  211. report->addVisitor(std::move(Visitor));
  212. report->addRange(SizeE->getSourceRange());
  213. bugreporter::trackExpressionValue(N, SizeE, *report);
  214. C.emitReport(std::move(report));
  215. }
  216. void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
  217. if (!DS->isSingleDecl())
  218. return;
  219. ASTContext &Ctx = C.getASTContext();
  220. SValBuilder &SVB = C.getSValBuilder();
  221. ProgramStateRef State = C.getState();
  222. QualType TypeToCheck;
  223. const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  224. if (VD)
  225. TypeToCheck = VD->getType().getCanonicalType();
  226. else if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl()))
  227. TypeToCheck = TND->getUnderlyingType().getCanonicalType();
  228. else
  229. return;
  230. const VariableArrayType *VLA = Ctx.getAsVariableArrayType(TypeToCheck);
  231. if (!VLA)
  232. return;
  233. // Check the VLA sizes for validity.
  234. SVal ArraySize;
  235. State = checkVLA(C, State, VLA, ArraySize);
  236. if (!State)
  237. return;
  238. auto ArraySizeNL = ArraySize.getAs<NonLoc>();
  239. if (!ArraySizeNL) {
  240. // Array size could not be determined but state may contain new assumptions.
  241. C.addTransition(State);
  242. return;
  243. }
  244. // VLASizeChecker is responsible for defining the extent of the array.
  245. if (VD) {
  246. State =
  247. setDynamicExtent(State, State->getRegion(VD, C.getLocationContext()),
  248. ArraySize.castAs<DefinedOrUnknownSVal>(), SVB);
  249. }
  250. // Remember our assumptions!
  251. C.addTransition(State);
  252. }
  253. void VLASizeChecker::checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
  254. CheckerContext &C) const {
  255. // Want to check for sizeof.
  256. if (UETTE->getKind() != UETT_SizeOf)
  257. return;
  258. // Ensure a type argument.
  259. if (!UETTE->isArgumentType())
  260. return;
  261. const VariableArrayType *VLA = C.getASTContext().getAsVariableArrayType(
  262. UETTE->getTypeOfArgument().getCanonicalType());
  263. // Ensure that the type is a VLA.
  264. if (!VLA)
  265. return;
  266. ProgramStateRef State = C.getState();
  267. SVal ArraySize;
  268. State = checkVLA(C, State, VLA, ArraySize);
  269. if (!State)
  270. return;
  271. C.addTransition(State);
  272. }
  273. void ento::registerVLASizeChecker(CheckerManager &mgr) {
  274. mgr.registerChecker<VLASizeChecker>();
  275. }
  276. bool ento::shouldRegisterVLASizeChecker(const CheckerManager &mgr) {
  277. return true;
  278. }