CastSizeChecker.cpp 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. //=== CastSizeChecker.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. // CastSizeChecker checks when casting a malloc'ed symbolic region to type T,
  11. // whether the size of the symbolic region is a multiple of the size of T.
  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. 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. if (Left % FlexSize == 0)
  77. return true;
  78. return false;
  79. }
  80. void CastSizeChecker::checkPreStmt(const CastExpr *CE,CheckerContext &C) const {
  81. const Expr *E = CE->getSubExpr();
  82. ASTContext &Ctx = C.getASTContext();
  83. QualType ToTy = Ctx.getCanonicalType(CE->getType());
  84. const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
  85. if (!ToPTy)
  86. return;
  87. QualType ToPointeeTy = ToPTy->getPointeeType();
  88. // Only perform the check if 'ToPointeeTy' is a complete type.
  89. if (ToPointeeTy->isIncompleteType())
  90. return;
  91. ProgramStateRef state = C.getState();
  92. const MemRegion *R = state->getSVal(E, C.getLocationContext()).getAsRegion();
  93. if (!R)
  94. return;
  95. const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
  96. if (!SR)
  97. return;
  98. SValBuilder &svalBuilder = C.getSValBuilder();
  99. SVal extent = SR->getExtent(svalBuilder);
  100. const llvm::APSInt *extentInt = svalBuilder.getKnownValue(state, extent);
  101. if (!extentInt)
  102. return;
  103. CharUnits regionSize = CharUnits::fromQuantity(extentInt->getSExtValue());
  104. CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
  105. // Ignore void, and a few other un-sizeable types.
  106. if (typeSize.isZero())
  107. return;
  108. if (regionSize % typeSize == 0)
  109. return;
  110. if (evenFlexibleArraySize(Ctx, regionSize, typeSize, ToPointeeTy))
  111. return;
  112. if (ExplodedNode *errorNode = C.generateSink()) {
  113. if (!BT)
  114. BT.reset(new BuiltinBug(this, "Cast region with wrong size.",
  115. "Cast a region whose size is not a multiple"
  116. " of the destination type size."));
  117. auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), errorNode);
  118. R->addRange(CE->getSourceRange());
  119. C.emitReport(std::move(R));
  120. }
  121. }
  122. void ento::registerCastSizeChecker(CheckerManager &mgr) {
  123. mgr.registerChecker<CastSizeChecker>();
  124. }