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