MallocSizeofChecker.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
  58. I!=E; ++I)
  59. if (const Stmt *child = *I)
  60. VisitChild(S, child);
  61. }
  62. TypeCallPair VisitCastExpr(const CastExpr *E) {
  63. return Visit(E->getSubExpr());
  64. }
  65. TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
  66. return TypeCallPair(E->getTypeInfoAsWritten(),
  67. Visit(E->getSubExpr()).second);
  68. }
  69. TypeCallPair VisitParenExpr(const ParenExpr *E) {
  70. return Visit(E->getSubExpr());
  71. }
  72. TypeCallPair VisitStmt(const Stmt *S) {
  73. VisitChildren(S);
  74. return TypeCallPair();
  75. }
  76. TypeCallPair VisitCallExpr(const CallExpr *E) {
  77. VisitChildren(E);
  78. const FunctionDecl *FD = E->getDirectCallee();
  79. if (FD) {
  80. IdentifierInfo *II = FD->getIdentifier();
  81. if (II == II_malloc || II == II_calloc || II == II_realloc)
  82. return TypeCallPair((const TypeSourceInfo *)nullptr, E);
  83. }
  84. return TypeCallPair();
  85. }
  86. TypeCallPair VisitDeclStmt(const DeclStmt *S) {
  87. for (const auto *I : S->decls())
  88. if (const VarDecl *VD = dyn_cast<VarDecl>(I))
  89. if (const Expr *Init = VD->getInit())
  90. VisitChild(VD, Init);
  91. return TypeCallPair();
  92. }
  93. };
  94. class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
  95. public:
  96. std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
  97. void VisitBinMul(const BinaryOperator *E) {
  98. Visit(E->getLHS());
  99. Visit(E->getRHS());
  100. }
  101. void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
  102. return Visit(E->getSubExpr());
  103. }
  104. void VisitParenExpr(const ParenExpr *E) {
  105. return Visit(E->getSubExpr());
  106. }
  107. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
  108. if (E->getKind() != UETT_SizeOf)
  109. return;
  110. Sizeofs.push_back(E);
  111. }
  112. };
  113. // Determine if the pointee and sizeof types are compatible. Here
  114. // we ignore constness of pointer types.
  115. static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
  116. while (true) {
  117. A = A.getCanonicalType();
  118. B = B.getCanonicalType();
  119. if (A.getTypePtr() == B.getTypePtr())
  120. return true;
  121. if (const PointerType *ptrA = A->getAs<PointerType>())
  122. if (const PointerType *ptrB = B->getAs<PointerType>()) {
  123. A = ptrA->getPointeeType();
  124. B = ptrB->getPointeeType();
  125. continue;
  126. }
  127. break;
  128. }
  129. return false;
  130. }
  131. static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
  132. // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
  133. while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
  134. QualType ElemType = AT->getElementType();
  135. if (typesCompatible(C, PT, AT->getElementType()))
  136. return true;
  137. T = ElemType;
  138. }
  139. return false;
  140. }
  141. class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
  142. public:
  143. void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
  144. BugReporter &BR) const {
  145. AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
  146. CastedAllocFinder Finder(&BR.getContext());
  147. Finder.Visit(D->getBody());
  148. for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
  149. e = Finder.Calls.end(); i != e; ++i) {
  150. QualType CastedType = i->CastedExpr->getType();
  151. if (!CastedType->isPointerType())
  152. continue;
  153. QualType PointeeType = CastedType->getAs<PointerType>()->getPointeeType();
  154. if (PointeeType->isVoidType())
  155. continue;
  156. for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
  157. ae = i->AllocCall->arg_end(); ai != ae; ++ai) {
  158. if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType())
  159. continue;
  160. SizeofFinder SFinder;
  161. SFinder.Visit(*ai);
  162. if (SFinder.Sizeofs.size() != 1)
  163. continue;
  164. QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
  165. if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
  166. continue;
  167. // If the argument to sizeof is an array, the result could be a
  168. // pointer to any array element.
  169. if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
  170. continue;
  171. const TypeSourceInfo *TSI = nullptr;
  172. if (i->CastedExprParent.is<const VarDecl *>()) {
  173. TSI =
  174. i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
  175. } else {
  176. TSI = i->ExplicitCastType;
  177. }
  178. SmallString<64> buf;
  179. llvm::raw_svector_ostream OS(buf);
  180. OS << "Result of ";
  181. const FunctionDecl *Callee = i->AllocCall->getDirectCallee();
  182. if (Callee && Callee->getIdentifier())
  183. OS << '\'' << Callee->getIdentifier()->getName() << '\'';
  184. else
  185. OS << "call";
  186. OS << " is converted to a pointer of type '"
  187. << PointeeType.getAsString() << "', which is incompatible with "
  188. << "sizeof operand type '" << SizeofType.getAsString() << "'";
  189. SmallVector<SourceRange, 4> Ranges;
  190. Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
  191. Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
  192. if (TSI)
  193. Ranges.push_back(TSI->getTypeLoc().getSourceRange());
  194. PathDiagnosticLocation L =
  195. PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
  196. BR.getSourceManager(), ADC);
  197. BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
  198. categories::UnixAPI, OS.str(), L, Ranges);
  199. }
  200. }
  201. }
  202. };
  203. }
  204. void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
  205. mgr.registerChecker<MallocSizeofChecker>();
  206. }