106f32e7eSjoerg // MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- C++ -*-=//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // Reports inconsistencies between the casted type of the return value of a
1006f32e7eSjoerg // malloc/calloc/realloc call and the operand of any sizeof expressions
1106f32e7eSjoerg // contained within its argument(s).
1206f32e7eSjoerg //
1306f32e7eSjoerg //===----------------------------------------------------------------------===//
1406f32e7eSjoerg 
1506f32e7eSjoerg #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
1606f32e7eSjoerg #include "clang/AST/StmtVisitor.h"
1706f32e7eSjoerg #include "clang/AST/TypeLoc.h"
1806f32e7eSjoerg #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
1906f32e7eSjoerg #include "clang/StaticAnalyzer/Core/Checker.h"
2006f32e7eSjoerg #include "clang/StaticAnalyzer/Core/CheckerManager.h"
2106f32e7eSjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
2206f32e7eSjoerg #include "llvm/ADT/SmallString.h"
2306f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
2406f32e7eSjoerg 
2506f32e7eSjoerg using namespace clang;
2606f32e7eSjoerg using namespace ento;
2706f32e7eSjoerg 
2806f32e7eSjoerg namespace {
2906f32e7eSjoerg 
3006f32e7eSjoerg typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
3106f32e7eSjoerg typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
3206f32e7eSjoerg 
3306f32e7eSjoerg class CastedAllocFinder
3406f32e7eSjoerg   : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
3506f32e7eSjoerg   IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
3606f32e7eSjoerg 
3706f32e7eSjoerg public:
3806f32e7eSjoerg   struct CallRecord {
3906f32e7eSjoerg     ExprParent CastedExprParent;
4006f32e7eSjoerg     const Expr *CastedExpr;
4106f32e7eSjoerg     const TypeSourceInfo *ExplicitCastType;
4206f32e7eSjoerg     const CallExpr *AllocCall;
4306f32e7eSjoerg 
CallRecord__anon918b152c0111::CastedAllocFinder::CallRecord4406f32e7eSjoerg     CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr,
4506f32e7eSjoerg                const TypeSourceInfo *ExplicitCastType,
4606f32e7eSjoerg                const CallExpr *AllocCall)
4706f32e7eSjoerg       : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr),
4806f32e7eSjoerg         ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {}
4906f32e7eSjoerg   };
5006f32e7eSjoerg 
5106f32e7eSjoerg   typedef std::vector<CallRecord> CallVec;
5206f32e7eSjoerg   CallVec Calls;
5306f32e7eSjoerg 
CastedAllocFinder(ASTContext * Ctx)5406f32e7eSjoerg   CastedAllocFinder(ASTContext *Ctx) :
5506f32e7eSjoerg     II_malloc(&Ctx->Idents.get("malloc")),
5606f32e7eSjoerg     II_calloc(&Ctx->Idents.get("calloc")),
5706f32e7eSjoerg     II_realloc(&Ctx->Idents.get("realloc")) {}
5806f32e7eSjoerg 
VisitChild(ExprParent Parent,const Stmt * S)5906f32e7eSjoerg   void VisitChild(ExprParent Parent, const Stmt *S) {
6006f32e7eSjoerg     TypeCallPair AllocCall = Visit(S);
6106f32e7eSjoerg     if (AllocCall.second && AllocCall.second != S)
6206f32e7eSjoerg       Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
6306f32e7eSjoerg                                  AllocCall.second));
6406f32e7eSjoerg   }
6506f32e7eSjoerg 
VisitChildren(const Stmt * S)6606f32e7eSjoerg   void VisitChildren(const Stmt *S) {
6706f32e7eSjoerg     for (const Stmt *Child : S->children())
6806f32e7eSjoerg       if (Child)
6906f32e7eSjoerg         VisitChild(S, Child);
7006f32e7eSjoerg   }
7106f32e7eSjoerg 
VisitCastExpr(const CastExpr * E)7206f32e7eSjoerg   TypeCallPair VisitCastExpr(const CastExpr *E) {
7306f32e7eSjoerg     return Visit(E->getSubExpr());
7406f32e7eSjoerg   }
7506f32e7eSjoerg 
VisitExplicitCastExpr(const ExplicitCastExpr * E)7606f32e7eSjoerg   TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
7706f32e7eSjoerg     return TypeCallPair(E->getTypeInfoAsWritten(),
7806f32e7eSjoerg                         Visit(E->getSubExpr()).second);
7906f32e7eSjoerg   }
8006f32e7eSjoerg 
VisitParenExpr(const ParenExpr * E)8106f32e7eSjoerg   TypeCallPair VisitParenExpr(const ParenExpr *E) {
8206f32e7eSjoerg     return Visit(E->getSubExpr());
8306f32e7eSjoerg   }
8406f32e7eSjoerg 
VisitStmt(const Stmt * S)8506f32e7eSjoerg   TypeCallPair VisitStmt(const Stmt *S) {
8606f32e7eSjoerg     VisitChildren(S);
8706f32e7eSjoerg     return TypeCallPair();
8806f32e7eSjoerg   }
8906f32e7eSjoerg 
VisitCallExpr(const CallExpr * E)9006f32e7eSjoerg   TypeCallPair VisitCallExpr(const CallExpr *E) {
9106f32e7eSjoerg     VisitChildren(E);
9206f32e7eSjoerg     const FunctionDecl *FD = E->getDirectCallee();
9306f32e7eSjoerg     if (FD) {
9406f32e7eSjoerg       IdentifierInfo *II = FD->getIdentifier();
9506f32e7eSjoerg       if (II == II_malloc || II == II_calloc || II == II_realloc)
9606f32e7eSjoerg         return TypeCallPair((const TypeSourceInfo *)nullptr, E);
9706f32e7eSjoerg     }
9806f32e7eSjoerg     return TypeCallPair();
9906f32e7eSjoerg   }
10006f32e7eSjoerg 
VisitDeclStmt(const DeclStmt * S)10106f32e7eSjoerg   TypeCallPair VisitDeclStmt(const DeclStmt *S) {
10206f32e7eSjoerg     for (const auto *I : S->decls())
10306f32e7eSjoerg       if (const VarDecl *VD = dyn_cast<VarDecl>(I))
10406f32e7eSjoerg         if (const Expr *Init = VD->getInit())
10506f32e7eSjoerg           VisitChild(VD, Init);
10606f32e7eSjoerg     return TypeCallPair();
10706f32e7eSjoerg   }
10806f32e7eSjoerg };
10906f32e7eSjoerg 
11006f32e7eSjoerg class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
11106f32e7eSjoerg public:
11206f32e7eSjoerg   std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
11306f32e7eSjoerg 
VisitBinMul(const BinaryOperator * E)11406f32e7eSjoerg   void VisitBinMul(const BinaryOperator *E) {
11506f32e7eSjoerg     Visit(E->getLHS());
11606f32e7eSjoerg     Visit(E->getRHS());
11706f32e7eSjoerg   }
11806f32e7eSjoerg 
VisitImplicitCastExpr(const ImplicitCastExpr * E)11906f32e7eSjoerg   void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
12006f32e7eSjoerg     return Visit(E->getSubExpr());
12106f32e7eSjoerg   }
12206f32e7eSjoerg 
VisitParenExpr(const ParenExpr * E)12306f32e7eSjoerg   void VisitParenExpr(const ParenExpr *E) {
12406f32e7eSjoerg     return Visit(E->getSubExpr());
12506f32e7eSjoerg   }
12606f32e7eSjoerg 
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)12706f32e7eSjoerg   void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
12806f32e7eSjoerg     if (E->getKind() != UETT_SizeOf)
12906f32e7eSjoerg       return;
13006f32e7eSjoerg 
13106f32e7eSjoerg     Sizeofs.push_back(E);
13206f32e7eSjoerg   }
13306f32e7eSjoerg };
13406f32e7eSjoerg 
13506f32e7eSjoerg // Determine if the pointee and sizeof types are compatible.  Here
13606f32e7eSjoerg // we ignore constness of pointer types.
typesCompatible(ASTContext & C,QualType A,QualType B)13706f32e7eSjoerg static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
13806f32e7eSjoerg   // sizeof(void*) is compatible with any other pointer.
13906f32e7eSjoerg   if (B->isVoidPointerType() && A->getAs<PointerType>())
14006f32e7eSjoerg     return true;
14106f32e7eSjoerg 
14206f32e7eSjoerg   while (true) {
14306f32e7eSjoerg     A = A.getCanonicalType();
14406f32e7eSjoerg     B = B.getCanonicalType();
14506f32e7eSjoerg 
14606f32e7eSjoerg     if (A.getTypePtr() == B.getTypePtr())
14706f32e7eSjoerg       return true;
14806f32e7eSjoerg 
14906f32e7eSjoerg     if (const PointerType *ptrA = A->getAs<PointerType>())
15006f32e7eSjoerg       if (const PointerType *ptrB = B->getAs<PointerType>()) {
15106f32e7eSjoerg         A = ptrA->getPointeeType();
15206f32e7eSjoerg         B = ptrB->getPointeeType();
15306f32e7eSjoerg         continue;
15406f32e7eSjoerg       }
15506f32e7eSjoerg 
15606f32e7eSjoerg     break;
15706f32e7eSjoerg   }
15806f32e7eSjoerg 
15906f32e7eSjoerg   return false;
16006f32e7eSjoerg }
16106f32e7eSjoerg 
compatibleWithArrayType(ASTContext & C,QualType PT,QualType T)16206f32e7eSjoerg static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
16306f32e7eSjoerg   // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
16406f32e7eSjoerg   while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
16506f32e7eSjoerg     QualType ElemType = AT->getElementType();
16606f32e7eSjoerg     if (typesCompatible(C, PT, AT->getElementType()))
16706f32e7eSjoerg       return true;
16806f32e7eSjoerg     T = ElemType;
16906f32e7eSjoerg   }
17006f32e7eSjoerg 
17106f32e7eSjoerg   return false;
17206f32e7eSjoerg }
17306f32e7eSjoerg 
17406f32e7eSjoerg class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
17506f32e7eSjoerg public:
checkASTCodeBody(const Decl * D,AnalysisManager & mgr,BugReporter & BR) const17606f32e7eSjoerg   void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
17706f32e7eSjoerg                         BugReporter &BR) const {
17806f32e7eSjoerg     AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
17906f32e7eSjoerg     CastedAllocFinder Finder(&BR.getContext());
18006f32e7eSjoerg     Finder.Visit(D->getBody());
18106f32e7eSjoerg     for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
18206f32e7eSjoerg          e = Finder.Calls.end(); i != e; ++i) {
18306f32e7eSjoerg       QualType CastedType = i->CastedExpr->getType();
18406f32e7eSjoerg       if (!CastedType->isPointerType())
18506f32e7eSjoerg         continue;
18606f32e7eSjoerg       QualType PointeeType = CastedType->getPointeeType();
18706f32e7eSjoerg       if (PointeeType->isVoidType())
18806f32e7eSjoerg         continue;
18906f32e7eSjoerg 
19006f32e7eSjoerg       for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
19106f32e7eSjoerg            ae = i->AllocCall->arg_end(); ai != ae; ++ai) {
19206f32e7eSjoerg         if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType())
19306f32e7eSjoerg           continue;
19406f32e7eSjoerg 
19506f32e7eSjoerg         SizeofFinder SFinder;
19606f32e7eSjoerg         SFinder.Visit(*ai);
19706f32e7eSjoerg         if (SFinder.Sizeofs.size() != 1)
19806f32e7eSjoerg           continue;
19906f32e7eSjoerg 
20006f32e7eSjoerg         QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
20106f32e7eSjoerg 
20206f32e7eSjoerg         if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
20306f32e7eSjoerg           continue;
20406f32e7eSjoerg 
20506f32e7eSjoerg         // If the argument to sizeof is an array, the result could be a
20606f32e7eSjoerg         // pointer to any array element.
20706f32e7eSjoerg         if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
20806f32e7eSjoerg           continue;
20906f32e7eSjoerg 
21006f32e7eSjoerg         const TypeSourceInfo *TSI = nullptr;
21106f32e7eSjoerg         if (i->CastedExprParent.is<const VarDecl *>()) {
21206f32e7eSjoerg           TSI =
21306f32e7eSjoerg               i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
21406f32e7eSjoerg         } else {
21506f32e7eSjoerg           TSI = i->ExplicitCastType;
21606f32e7eSjoerg         }
21706f32e7eSjoerg 
21806f32e7eSjoerg         SmallString<64> buf;
21906f32e7eSjoerg         llvm::raw_svector_ostream OS(buf);
22006f32e7eSjoerg 
22106f32e7eSjoerg         OS << "Result of ";
22206f32e7eSjoerg         const FunctionDecl *Callee = i->AllocCall->getDirectCallee();
22306f32e7eSjoerg         if (Callee && Callee->getIdentifier())
22406f32e7eSjoerg           OS << '\'' << Callee->getIdentifier()->getName() << '\'';
22506f32e7eSjoerg         else
22606f32e7eSjoerg           OS << "call";
22706f32e7eSjoerg         OS << " is converted to a pointer of type '"
22806f32e7eSjoerg             << PointeeType.getAsString() << "', which is incompatible with "
22906f32e7eSjoerg             << "sizeof operand type '" << SizeofType.getAsString() << "'";
23006f32e7eSjoerg         SmallVector<SourceRange, 4> Ranges;
23106f32e7eSjoerg         Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
23206f32e7eSjoerg         Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
23306f32e7eSjoerg         if (TSI)
23406f32e7eSjoerg           Ranges.push_back(TSI->getTypeLoc().getSourceRange());
23506f32e7eSjoerg 
23606f32e7eSjoerg         PathDiagnosticLocation L =
23706f32e7eSjoerg             PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
23806f32e7eSjoerg                 BR.getSourceManager(), ADC);
23906f32e7eSjoerg 
24006f32e7eSjoerg         BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
24106f32e7eSjoerg                            categories::UnixAPI, OS.str(), L, Ranges);
24206f32e7eSjoerg       }
24306f32e7eSjoerg     }
24406f32e7eSjoerg   }
24506f32e7eSjoerg };
24606f32e7eSjoerg 
24706f32e7eSjoerg }
24806f32e7eSjoerg 
registerMallocSizeofChecker(CheckerManager & mgr)24906f32e7eSjoerg void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
25006f32e7eSjoerg   mgr.registerChecker<MallocSizeofChecker>();
25106f32e7eSjoerg }
25206f32e7eSjoerg 
shouldRegisterMallocSizeofChecker(const CheckerManager & mgr)253*13fbcb42Sjoerg bool ento::shouldRegisterMallocSizeofChecker(const CheckerManager &mgr) {
25406f32e7eSjoerg   return true;
25506f32e7eSjoerg }
256