1 // MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
14 //===----------------------------------------------------------------------===//
16 #include "ClangSACheckers.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
20 #include "clang/StaticAnalyzer/Core/Checker.h"
21 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
31 typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
32 typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
34 class CastedAllocFinder
35 : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
36 IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
40 ExprParent CastedExprParent;
41 const Expr *CastedExpr;
42 const TypeSourceInfo *ExplicitCastType;
43 const CallExpr *AllocCall;
45 CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr,
46 const TypeSourceInfo *ExplicitCastType,
47 const CallExpr *AllocCall)
48 : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr),
49 ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {}
52 typedef std::vector<CallRecord> CallVec;
55 CastedAllocFinder(ASTContext *Ctx) :
56 II_malloc(&Ctx->Idents.get("malloc")),
57 II_calloc(&Ctx->Idents.get("calloc")),
58 II_realloc(&Ctx->Idents.get("realloc")) {}
60 void VisitChild(ExprParent Parent, const Stmt *S) {
61 TypeCallPair AllocCall = Visit(S);
62 if (AllocCall.second && AllocCall.second != S)
63 Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
67 void VisitChildren(const Stmt *S) {
68 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
70 if (const Stmt *child = *I)
74 TypeCallPair VisitCastExpr(const CastExpr *E) {
75 return Visit(E->getSubExpr());
78 TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
79 return TypeCallPair(E->getTypeInfoAsWritten(),
80 Visit(E->getSubExpr()).second);
83 TypeCallPair VisitParenExpr(const ParenExpr *E) {
84 return Visit(E->getSubExpr());
87 TypeCallPair VisitStmt(const Stmt *S) {
89 return TypeCallPair();
92 TypeCallPair VisitCallExpr(const CallExpr *E) {
94 const FunctionDecl *FD = E->getDirectCallee();
96 IdentifierInfo *II = FD->getIdentifier();
97 if (II == II_malloc || II == II_calloc || II == II_realloc)
98 return TypeCallPair((const TypeSourceInfo *)0, E);
100 return TypeCallPair();
103 TypeCallPair VisitDeclStmt(const DeclStmt *S) {
104 for (DeclStmt::const_decl_iterator I = S->decl_begin(), E = S->decl_end();
106 if (const VarDecl *VD = dyn_cast<VarDecl>(*I))
107 if (const Expr *Init = VD->getInit())
108 VisitChild(VD, Init);
109 return TypeCallPair();
113 class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
115 std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
117 void VisitBinMul(const BinaryOperator *E) {
122 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
123 return Visit(E->getSubExpr());
126 void VisitParenExpr(const ParenExpr *E) {
127 return Visit(E->getSubExpr());
130 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
131 if (E->getKind() != UETT_SizeOf)
134 Sizeofs.push_back(E);
138 // Determine if the pointee and sizeof types are compatible. Here
139 // we ignore constness of pointer types.
140 static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
142 A = A.getCanonicalType();
143 B = B.getCanonicalType();
145 if (A.getTypePtr() == B.getTypePtr())
148 if (const PointerType *ptrA = A->getAs<PointerType>())
149 if (const PointerType *ptrB = B->getAs<PointerType>()) {
150 A = ptrA->getPointeeType();
151 B = ptrB->getPointeeType();
161 static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
162 // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
163 while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
164 QualType ElemType = AT->getElementType();
165 if (typesCompatible(C, PT, AT->getElementType()))
173 class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
175 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
176 BugReporter &BR) const {
177 AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
178 CastedAllocFinder Finder(&BR.getContext());
179 Finder.Visit(D->getBody());
180 for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
181 e = Finder.Calls.end(); i != e; ++i) {
182 QualType CastedType = i->CastedExpr->getType();
183 if (!CastedType->isPointerType())
185 QualType PointeeType = CastedType->getAs<PointerType>()->getPointeeType();
186 if (PointeeType->isVoidType())
189 for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
190 ae = i->AllocCall->arg_end(); ai != ae; ++ai) {
191 if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType())
194 SizeofFinder SFinder;
196 if (SFinder.Sizeofs.size() != 1)
199 QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
201 if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
204 // If the argument to sizeof is an array, the result could be a
205 // pointer to any array element.
206 if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
209 const TypeSourceInfo *TSI = 0;
210 if (i->CastedExprParent.is<const VarDecl *>()) {
212 i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
214 TSI = i->ExplicitCastType;
218 llvm::raw_svector_ostream OS(buf);
221 const FunctionDecl *Callee = i->AllocCall->getDirectCallee();
222 if (Callee && Callee->getIdentifier())
223 OS << '\'' << Callee->getIdentifier()->getName() << '\'';
226 OS << " is converted to a pointer of type '"
227 << PointeeType.getAsString() << "', which is incompatible with "
228 << "sizeof operand type '" << SizeofType.getAsString() << "'";
229 SmallVector<SourceRange, 4> Ranges;
230 Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
231 Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
233 Ranges.push_back(TSI->getTypeLoc().getSourceRange());
235 PathDiagnosticLocation L =
236 PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
237 BR.getSourceManager(), ADC);
239 BR.EmitBasicReport(D, "Allocator sizeof operand mismatch",
242 L, Ranges.data(), Ranges.size());
250 void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
251 mgr.registerChecker<MallocSizeofChecker>();