clang API Documentation

MallocSizeofChecker.cpp
Go to the documentation of this file.
00001 // MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- C++ -*-=//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Reports inconsistencies between the casted type of the return value of a
00011 // malloc/calloc/realloc call and the operand of any sizeof expressions
00012 // contained within its argument(s).
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "ClangSACheckers.h"
00017 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
00018 #include "clang/StaticAnalyzer/Core/Checker.h"
00019 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
00020 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
00021 #include "clang/AST/StmtVisitor.h"
00022 #include "clang/AST/TypeLoc.h"
00023 #include "llvm/ADT/SmallString.h"
00024 
00025 using namespace clang;
00026 using namespace ento;
00027 
00028 namespace {
00029 
00030 typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
00031 typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
00032 
00033 class CastedAllocFinder
00034   : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
00035   IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
00036 
00037 public:
00038   struct CallRecord {
00039     ExprParent CastedExprParent;
00040     const Expr *CastedExpr;
00041     const TypeSourceInfo *ExplicitCastType;
00042     const CallExpr *AllocCall;
00043 
00044     CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr,
00045                const TypeSourceInfo *ExplicitCastType,
00046                const CallExpr *AllocCall)
00047       : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr),
00048         ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {}
00049   };
00050 
00051   typedef std::vector<CallRecord> CallVec;
00052   CallVec Calls;
00053 
00054   CastedAllocFinder(ASTContext *Ctx) :
00055     II_malloc(&Ctx->Idents.get("malloc")),
00056     II_calloc(&Ctx->Idents.get("calloc")),
00057     II_realloc(&Ctx->Idents.get("realloc")) {}
00058 
00059   void VisitChild(ExprParent Parent, const Stmt *S) {
00060     TypeCallPair AllocCall = Visit(S);
00061     if (AllocCall.second && AllocCall.second != S)
00062       Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
00063                                  AllocCall.second));
00064   }
00065 
00066   void VisitChildren(const Stmt *S) {
00067     for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
00068          I!=E; ++I)
00069       if (const Stmt *child = *I)
00070         VisitChild(S, child);
00071   }
00072 
00073   TypeCallPair VisitCastExpr(const CastExpr *E) {
00074     return Visit(E->getSubExpr());
00075   }
00076 
00077   TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
00078     return TypeCallPair(E->getTypeInfoAsWritten(),
00079                         Visit(E->getSubExpr()).second);
00080   }
00081 
00082   TypeCallPair VisitParenExpr(const ParenExpr *E) {
00083     return Visit(E->getSubExpr());
00084   }
00085 
00086   TypeCallPair VisitStmt(const Stmt *S) {
00087     VisitChildren(S);
00088     return TypeCallPair();
00089   }
00090 
00091   TypeCallPair VisitCallExpr(const CallExpr *E) {
00092     VisitChildren(E);
00093     const FunctionDecl *FD = E->getDirectCallee();
00094     if (FD) {
00095       IdentifierInfo *II = FD->getIdentifier();
00096       if (II == II_malloc || II == II_calloc || II == II_realloc)
00097         return TypeCallPair((const TypeSourceInfo *)0, E);
00098     }
00099     return TypeCallPair();
00100   }
00101 
00102   TypeCallPair VisitDeclStmt(const DeclStmt *S) {
00103     for (DeclStmt::const_decl_iterator I = S->decl_begin(), E = S->decl_end();
00104          I!=E; ++I)
00105       if (const VarDecl *VD = dyn_cast<VarDecl>(*I))
00106         if (const Expr *Init = VD->getInit())
00107           VisitChild(VD, Init);
00108     return TypeCallPair();
00109   }
00110 };
00111 
00112 class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
00113 public:
00114   std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
00115 
00116   void VisitBinMul(const BinaryOperator *E) {
00117     Visit(E->getLHS());
00118     Visit(E->getRHS());
00119   }
00120 
00121   void VisitBinAdd(const BinaryOperator *E) {
00122     Visit(E->getLHS());
00123     Visit(E->getRHS());
00124   }
00125 
00126   void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
00127     return Visit(E->getSubExpr());
00128   }
00129 
00130   void VisitParenExpr(const ParenExpr *E) {
00131     return Visit(E->getSubExpr());
00132   }
00133 
00134   void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
00135     if (E->getKind() != UETT_SizeOf)
00136       return;
00137 
00138     Sizeofs.push_back(E);
00139   }
00140 };
00141 
00142 // Determine if the pointee and sizeof types are compatible.  Here
00143 // we ignore constness of pointer types.
00144 static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
00145   while (true) {
00146     A = A.getCanonicalType();
00147     B = B.getCanonicalType();
00148   
00149     if (A.getTypePtr() == B.getTypePtr())
00150       return true;
00151     
00152     if (const PointerType *ptrA = A->getAs<PointerType>())
00153       if (const PointerType *ptrB = B->getAs<PointerType>()) {
00154   A = ptrA->getPointeeType();
00155   B = ptrB->getPointeeType();
00156   continue;
00157       }
00158       
00159     break;
00160   }
00161   
00162   return false;
00163 }
00164 
00165 class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
00166 public:
00167   void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
00168                         BugReporter &BR) const {
00169     AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
00170     CastedAllocFinder Finder(&BR.getContext());
00171     Finder.Visit(D->getBody());
00172     for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
00173          e = Finder.Calls.end(); i != e; ++i) {
00174       QualType CastedType = i->CastedExpr->getType();
00175       if (!CastedType->isPointerType())
00176         continue;
00177       QualType PointeeType = CastedType->getAs<PointerType>()->getPointeeType();
00178       if (PointeeType->isVoidType())
00179         continue;
00180 
00181       for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
00182            ae = i->AllocCall->arg_end(); ai != ae; ++ai) {
00183         if (!(*ai)->getType()->isIntegerType())
00184           continue;
00185 
00186         SizeofFinder SFinder;
00187         SFinder.Visit(*ai);
00188         if (SFinder.Sizeofs.size() != 1)
00189           continue;
00190 
00191         QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
00192         if (!typesCompatible(BR.getContext(), PointeeType, SizeofType)) {
00193           const TypeSourceInfo *TSI = 0;
00194           if (i->CastedExprParent.is<const VarDecl *>()) {
00195             TSI =
00196               i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
00197           } else {
00198             TSI = i->ExplicitCastType;
00199           }
00200 
00201           SmallString<64> buf;
00202           llvm::raw_svector_ostream OS(buf);
00203 
00204           OS << "Result of '"
00205              << i->AllocCall->getDirectCallee()->getIdentifier()->getName()
00206              << "' is converted to a pointer of type '"
00207              << PointeeType.getAsString() << "', which is incompatible with "
00208              << "sizeof operand type '" << SizeofType.getAsString() << "'";
00209           llvm::SmallVector<SourceRange, 4> Ranges;
00210           Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
00211           Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
00212           if (TSI)
00213             Ranges.push_back(TSI->getTypeLoc().getSourceRange());
00214 
00215           PathDiagnosticLocation L =
00216             PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
00217                                                 BR.getSourceManager(), ADC);
00218 
00219           BR.EmitBasicReport(D, "Allocator sizeof operand mismatch",
00220                              categories::UnixAPI,
00221                              OS.str(),
00222                              L, Ranges.data(), Ranges.size());
00223         }
00224       }
00225     }
00226   }
00227 };
00228 
00229 }
00230 
00231 void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
00232   mgr.registerChecker<MallocSizeofChecker>();
00233 }