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