MallocSizeofChecker.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- 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. // Reports inconsistencies between the casted type of the return value of a
  10. // malloc/calloc/realloc call and the operand of any sizeof expressions
  11. // contained within its argument(s).
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  15. #include "clang/AST/StmtVisitor.h"
  16. #include "clang/AST/TypeLoc.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  18. #include "clang/StaticAnalyzer/Core/Checker.h"
  19. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.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. typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
  27. typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
  28. class CastedAllocFinder
  29. : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
  30. IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
  31. public:
  32. struct CallRecord {
  33. ExprParent CastedExprParent;
  34. const Expr *CastedExpr;
  35. const TypeSourceInfo *ExplicitCastType;
  36. const CallExpr *AllocCall;
  37. CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr,
  38. const TypeSourceInfo *ExplicitCastType,
  39. const CallExpr *AllocCall)
  40. : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr),
  41. ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {}
  42. };
  43. typedef std::vector<CallRecord> CallVec;
  44. CallVec Calls;
  45. CastedAllocFinder(ASTContext *Ctx) :
  46. II_malloc(&Ctx->Idents.get("malloc")),
  47. II_calloc(&Ctx->Idents.get("calloc")),
  48. II_realloc(&Ctx->Idents.get("realloc")) {}
  49. void VisitChild(ExprParent Parent, const Stmt *S) {
  50. TypeCallPair AllocCall = Visit(S);
  51. if (AllocCall.second && AllocCall.second != S)
  52. Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
  53. AllocCall.second));
  54. }
  55. void VisitChildren(const Stmt *S) {
  56. for (const Stmt *Child : S->children())
  57. if (Child)
  58. VisitChild(S, Child);
  59. }
  60. TypeCallPair VisitCastExpr(const CastExpr *E) {
  61. return Visit(E->getSubExpr());
  62. }
  63. TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
  64. return TypeCallPair(E->getTypeInfoAsWritten(),
  65. Visit(E->getSubExpr()).second);
  66. }
  67. TypeCallPair VisitParenExpr(const ParenExpr *E) {
  68. return Visit(E->getSubExpr());
  69. }
  70. TypeCallPair VisitStmt(const Stmt *S) {
  71. VisitChildren(S);
  72. return TypeCallPair();
  73. }
  74. TypeCallPair VisitCallExpr(const CallExpr *E) {
  75. VisitChildren(E);
  76. const FunctionDecl *FD = E->getDirectCallee();
  77. if (FD) {
  78. IdentifierInfo *II = FD->getIdentifier();
  79. if (II == II_malloc || II == II_calloc || II == II_realloc)
  80. return TypeCallPair((const TypeSourceInfo *)nullptr, E);
  81. }
  82. return TypeCallPair();
  83. }
  84. TypeCallPair VisitDeclStmt(const DeclStmt *S) {
  85. for (const auto *I : S->decls())
  86. if (const VarDecl *VD = dyn_cast<VarDecl>(I))
  87. if (const Expr *Init = VD->getInit())
  88. VisitChild(VD, Init);
  89. return TypeCallPair();
  90. }
  91. };
  92. class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
  93. public:
  94. std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
  95. void VisitBinMul(const BinaryOperator *E) {
  96. Visit(E->getLHS());
  97. Visit(E->getRHS());
  98. }
  99. void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
  100. return Visit(E->getSubExpr());
  101. }
  102. void VisitParenExpr(const ParenExpr *E) {
  103. return Visit(E->getSubExpr());
  104. }
  105. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
  106. if (E->getKind() != UETT_SizeOf)
  107. return;
  108. Sizeofs.push_back(E);
  109. }
  110. };
  111. // Determine if the pointee and sizeof types are compatible. Here
  112. // we ignore constness of pointer types.
  113. static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
  114. // sizeof(void*) is compatible with any other pointer.
  115. if (B->isVoidPointerType() && A->getAs<PointerType>())
  116. return true;
  117. // sizeof(pointer type) is compatible with void*
  118. if (A->isVoidPointerType() && B->getAs<PointerType>())
  119. return true;
  120. while (true) {
  121. A = A.getCanonicalType();
  122. B = B.getCanonicalType();
  123. if (A.getTypePtr() == B.getTypePtr())
  124. return true;
  125. if (const PointerType *ptrA = A->getAs<PointerType>())
  126. if (const PointerType *ptrB = B->getAs<PointerType>()) {
  127. A = ptrA->getPointeeType();
  128. B = ptrB->getPointeeType();
  129. continue;
  130. }
  131. break;
  132. }
  133. return false;
  134. }
  135. static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
  136. // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
  137. while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
  138. QualType ElemType = AT->getElementType();
  139. if (typesCompatible(C, PT, AT->getElementType()))
  140. return true;
  141. T = ElemType;
  142. }
  143. return false;
  144. }
  145. class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
  146. public:
  147. void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
  148. BugReporter &BR) const {
  149. AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
  150. CastedAllocFinder Finder(&BR.getContext());
  151. Finder.Visit(D->getBody());
  152. for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
  153. e = Finder.Calls.end(); i != e; ++i) {
  154. QualType CastedType = i->CastedExpr->getType();
  155. if (!CastedType->isPointerType())
  156. continue;
  157. QualType PointeeType = CastedType->getPointeeType();
  158. if (PointeeType->isVoidType())
  159. continue;
  160. for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
  161. ae = i->AllocCall->arg_end(); ai != ae; ++ai) {
  162. if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType())
  163. continue;
  164. SizeofFinder SFinder;
  165. SFinder.Visit(*ai);
  166. if (SFinder.Sizeofs.size() != 1)
  167. continue;
  168. QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
  169. if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
  170. continue;
  171. // If the argument to sizeof is an array, the result could be a
  172. // pointer to any array element.
  173. if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
  174. continue;
  175. const TypeSourceInfo *TSI = nullptr;
  176. if (i->CastedExprParent.is<const VarDecl *>()) {
  177. TSI =
  178. i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
  179. } else {
  180. TSI = i->ExplicitCastType;
  181. }
  182. SmallString<64> buf;
  183. llvm::raw_svector_ostream OS(buf);
  184. OS << "Result of ";
  185. const FunctionDecl *Callee = i->AllocCall->getDirectCallee();
  186. if (Callee && Callee->getIdentifier())
  187. OS << '\'' << Callee->getIdentifier()->getName() << '\'';
  188. else
  189. OS << "call";
  190. OS << " is converted to a pointer of type '"
  191. << PointeeType.getAsString() << "', which is incompatible with "
  192. << "sizeof operand type '" << SizeofType.getAsString() << "'";
  193. SmallVector<SourceRange, 4> Ranges;
  194. Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
  195. Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
  196. if (TSI)
  197. Ranges.push_back(TSI->getTypeLoc().getSourceRange());
  198. PathDiagnosticLocation L =
  199. PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
  200. BR.getSourceManager(), ADC);
  201. BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
  202. categories::UnixAPI, OS.str(), L, Ranges);
  203. }
  204. }
  205. }
  206. };
  207. }
  208. void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
  209. mgr.registerChecker<MallocSizeofChecker>();
  210. }
  211. bool ento::shouldRegisterMallocSizeofChecker(const CheckerManager &mgr) {
  212. return true;
  213. }