CastSizeChecker.cpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //=== CastSizeChecker.cpp ---------------------------------------*- 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. // CastSizeChecker checks when casting a malloc'ed symbolic region to type T,
  10. // whether the size of the symbolic region is a multiple of the size of T.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/CharUnits.h"
  14. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  15. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  16. #include "clang/StaticAnalyzer/Core/Checker.h"
  17. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
  20. using namespace clang;
  21. using namespace ento;
  22. namespace {
  23. class CastSizeChecker : public Checker< check::PreStmt<CastExpr> > {
  24. mutable std::unique_ptr<BuiltinBug> BT;
  25. public:
  26. void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
  27. };
  28. }
  29. /// Check if we are casting to a struct with a flexible array at the end.
  30. /// \code
  31. /// struct foo {
  32. /// size_t len;
  33. /// struct bar data[];
  34. /// };
  35. /// \endcode
  36. /// or
  37. /// \code
  38. /// struct foo {
  39. /// size_t len;
  40. /// struct bar data[0];
  41. /// }
  42. /// \endcode
  43. /// In these cases it is also valid to allocate size of struct foo + a multiple
  44. /// of struct bar.
  45. static bool evenFlexibleArraySize(ASTContext &Ctx, CharUnits RegionSize,
  46. CharUnits TypeSize, QualType ToPointeeTy) {
  47. const RecordType *RT = ToPointeeTy->getAs<RecordType>();
  48. if (!RT)
  49. return false;
  50. const RecordDecl *RD = RT->getDecl();
  51. RecordDecl::field_iterator Iter(RD->field_begin());
  52. RecordDecl::field_iterator End(RD->field_end());
  53. const FieldDecl *Last = nullptr;
  54. for (; Iter != End; ++Iter)
  55. Last = *Iter;
  56. assert(Last && "empty structs should already be handled");
  57. const Type *ElemType = Last->getType()->getArrayElementTypeNoTypeQual();
  58. CharUnits FlexSize;
  59. if (const ConstantArrayType *ArrayTy =
  60. Ctx.getAsConstantArrayType(Last->getType())) {
  61. FlexSize = Ctx.getTypeSizeInChars(ElemType);
  62. if (ArrayTy->getSize() == 1 && TypeSize > FlexSize)
  63. TypeSize -= FlexSize;
  64. else if (ArrayTy->getSize() != 0)
  65. return false;
  66. } else if (RD->hasFlexibleArrayMember()) {
  67. FlexSize = Ctx.getTypeSizeInChars(ElemType);
  68. } else {
  69. return false;
  70. }
  71. if (FlexSize.isZero())
  72. return false;
  73. CharUnits Left = RegionSize - TypeSize;
  74. if (Left.isNegative())
  75. return false;
  76. return Left % FlexSize == 0;
  77. }
  78. void CastSizeChecker::checkPreStmt(const CastExpr *CE,CheckerContext &C) const {
  79. const Expr *E = CE->getSubExpr();
  80. ASTContext &Ctx = C.getASTContext();
  81. QualType ToTy = Ctx.getCanonicalType(CE->getType());
  82. const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
  83. if (!ToPTy)
  84. return;
  85. QualType ToPointeeTy = ToPTy->getPointeeType();
  86. // Only perform the check if 'ToPointeeTy' is a complete type.
  87. if (ToPointeeTy->isIncompleteType())
  88. return;
  89. ProgramStateRef state = C.getState();
  90. const MemRegion *R = C.getSVal(E).getAsRegion();
  91. if (!R)
  92. return;
  93. const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
  94. if (!SR)
  95. return;
  96. SValBuilder &svalBuilder = C.getSValBuilder();
  97. DefinedOrUnknownSVal Size = getDynamicExtent(state, SR, svalBuilder);
  98. const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
  99. if (!SizeInt)
  100. return;
  101. CharUnits regionSize = CharUnits::fromQuantity(SizeInt->getZExtValue());
  102. CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
  103. // Ignore void, and a few other un-sizeable types.
  104. if (typeSize.isZero())
  105. return;
  106. if (regionSize % typeSize == 0)
  107. return;
  108. if (evenFlexibleArraySize(Ctx, regionSize, typeSize, ToPointeeTy))
  109. return;
  110. if (ExplodedNode *errorNode = C.generateErrorNode()) {
  111. if (!BT)
  112. BT.reset(new BuiltinBug(this, "Cast region with wrong size.",
  113. "Cast a region whose size is not a multiple"
  114. " of the destination type size."));
  115. auto R = std::make_unique<PathSensitiveBugReport>(*BT, BT->getDescription(),
  116. errorNode);
  117. R->addRange(CE->getSourceRange());
  118. C.emitReport(std::move(R));
  119. }
  120. }
  121. void ento::registerCastSizeChecker(CheckerManager &mgr) {
  122. mgr.registerChecker<CastSizeChecker>();
  123. }
  124. bool ento::shouldRegisterCastSizeChecker(const CheckerManager &mgr) {
  125. // PR31226: C++ is more complicated than what this checker currently supports.
  126. // There are derived-to-base casts, there are different rules for 0-size
  127. // structures, no flexible arrays, etc.
  128. // FIXME: Disabled on C++ for now.
  129. const LangOptions &LO = mgr.getLangOpts();
  130. return !LO.CPlusPlus;
  131. }