MallocSizeofChecker.cpp 7.9 KB

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