10b57cec5SDimitry Andric // MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- C++ -*-=//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Reports inconsistencies between the casted type of the return value of a
100b57cec5SDimitry Andric // malloc/calloc/realloc call and the operand of any sizeof expressions
110b57cec5SDimitry Andric // contained within its argument(s).
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric
150b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
160b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
17*06c3fb27SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
180b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
190b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
200b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
210b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
23*06c3fb27SDimitry Andric #include "llvm/ADT/iterator_range.h"
240b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
250b57cec5SDimitry Andric
260b57cec5SDimitry Andric using namespace clang;
270b57cec5SDimitry Andric using namespace ento;
280b57cec5SDimitry Andric
290b57cec5SDimitry Andric namespace {
300b57cec5SDimitry Andric
310b57cec5SDimitry Andric typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
320b57cec5SDimitry Andric typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
330b57cec5SDimitry Andric
340b57cec5SDimitry Andric class CastedAllocFinder
350b57cec5SDimitry Andric : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
360b57cec5SDimitry Andric IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
370b57cec5SDimitry Andric
380b57cec5SDimitry Andric public:
390b57cec5SDimitry Andric struct CallRecord {
400b57cec5SDimitry Andric ExprParent CastedExprParent;
410b57cec5SDimitry Andric const Expr *CastedExpr;
420b57cec5SDimitry Andric const TypeSourceInfo *ExplicitCastType;
430b57cec5SDimitry Andric const CallExpr *AllocCall;
440b57cec5SDimitry Andric
CallRecord__anon7b2079cb0111::CastedAllocFinder::CallRecord450b57cec5SDimitry Andric CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr,
460b57cec5SDimitry Andric const TypeSourceInfo *ExplicitCastType,
470b57cec5SDimitry Andric const CallExpr *AllocCall)
480b57cec5SDimitry Andric : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr),
490b57cec5SDimitry Andric ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {}
500b57cec5SDimitry Andric };
510b57cec5SDimitry Andric
520b57cec5SDimitry Andric typedef std::vector<CallRecord> CallVec;
530b57cec5SDimitry Andric CallVec Calls;
540b57cec5SDimitry Andric
CastedAllocFinder(ASTContext * Ctx)550b57cec5SDimitry Andric CastedAllocFinder(ASTContext *Ctx) :
560b57cec5SDimitry Andric II_malloc(&Ctx->Idents.get("malloc")),
570b57cec5SDimitry Andric II_calloc(&Ctx->Idents.get("calloc")),
580b57cec5SDimitry Andric II_realloc(&Ctx->Idents.get("realloc")) {}
590b57cec5SDimitry Andric
VisitChild(ExprParent Parent,const Stmt * S)600b57cec5SDimitry Andric void VisitChild(ExprParent Parent, const Stmt *S) {
610b57cec5SDimitry Andric TypeCallPair AllocCall = Visit(S);
620b57cec5SDimitry Andric if (AllocCall.second && AllocCall.second != S)
630b57cec5SDimitry Andric Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
640b57cec5SDimitry Andric AllocCall.second));
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric
VisitChildren(const Stmt * S)670b57cec5SDimitry Andric void VisitChildren(const Stmt *S) {
680b57cec5SDimitry Andric for (const Stmt *Child : S->children())
690b57cec5SDimitry Andric if (Child)
700b57cec5SDimitry Andric VisitChild(S, Child);
710b57cec5SDimitry Andric }
720b57cec5SDimitry Andric
VisitCastExpr(const CastExpr * E)730b57cec5SDimitry Andric TypeCallPair VisitCastExpr(const CastExpr *E) {
740b57cec5SDimitry Andric return Visit(E->getSubExpr());
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric
VisitExplicitCastExpr(const ExplicitCastExpr * E)770b57cec5SDimitry Andric TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
780b57cec5SDimitry Andric return TypeCallPair(E->getTypeInfoAsWritten(),
790b57cec5SDimitry Andric Visit(E->getSubExpr()).second);
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric
VisitParenExpr(const ParenExpr * E)820b57cec5SDimitry Andric TypeCallPair VisitParenExpr(const ParenExpr *E) {
830b57cec5SDimitry Andric return Visit(E->getSubExpr());
840b57cec5SDimitry Andric }
850b57cec5SDimitry Andric
VisitStmt(const Stmt * S)860b57cec5SDimitry Andric TypeCallPair VisitStmt(const Stmt *S) {
870b57cec5SDimitry Andric VisitChildren(S);
880b57cec5SDimitry Andric return TypeCallPair();
890b57cec5SDimitry Andric }
900b57cec5SDimitry Andric
VisitCallExpr(const CallExpr * E)910b57cec5SDimitry Andric TypeCallPair VisitCallExpr(const CallExpr *E) {
920b57cec5SDimitry Andric VisitChildren(E);
930b57cec5SDimitry Andric const FunctionDecl *FD = E->getDirectCallee();
940b57cec5SDimitry Andric if (FD) {
950b57cec5SDimitry Andric IdentifierInfo *II = FD->getIdentifier();
960b57cec5SDimitry Andric if (II == II_malloc || II == II_calloc || II == II_realloc)
970b57cec5SDimitry Andric return TypeCallPair((const TypeSourceInfo *)nullptr, E);
980b57cec5SDimitry Andric }
990b57cec5SDimitry Andric return TypeCallPair();
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric
VisitDeclStmt(const DeclStmt * S)1020b57cec5SDimitry Andric TypeCallPair VisitDeclStmt(const DeclStmt *S) {
1030b57cec5SDimitry Andric for (const auto *I : S->decls())
1040b57cec5SDimitry Andric if (const VarDecl *VD = dyn_cast<VarDecl>(I))
1050b57cec5SDimitry Andric if (const Expr *Init = VD->getInit())
1060b57cec5SDimitry Andric VisitChild(VD, Init);
1070b57cec5SDimitry Andric return TypeCallPair();
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric };
1100b57cec5SDimitry Andric
1110b57cec5SDimitry Andric class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
1120b57cec5SDimitry Andric public:
1130b57cec5SDimitry Andric std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
1140b57cec5SDimitry Andric
VisitBinMul(const BinaryOperator * E)1150b57cec5SDimitry Andric void VisitBinMul(const BinaryOperator *E) {
1160b57cec5SDimitry Andric Visit(E->getLHS());
1170b57cec5SDimitry Andric Visit(E->getRHS());
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric
VisitImplicitCastExpr(const ImplicitCastExpr * E)1200b57cec5SDimitry Andric void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
1210b57cec5SDimitry Andric return Visit(E->getSubExpr());
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric
VisitParenExpr(const ParenExpr * E)1240b57cec5SDimitry Andric void VisitParenExpr(const ParenExpr *E) {
1250b57cec5SDimitry Andric return Visit(E->getSubExpr());
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)1280b57cec5SDimitry Andric void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
1290b57cec5SDimitry Andric if (E->getKind() != UETT_SizeOf)
1300b57cec5SDimitry Andric return;
1310b57cec5SDimitry Andric
1320b57cec5SDimitry Andric Sizeofs.push_back(E);
1330b57cec5SDimitry Andric }
1340b57cec5SDimitry Andric };
1350b57cec5SDimitry Andric
1360b57cec5SDimitry Andric // Determine if the pointee and sizeof types are compatible. Here
1370b57cec5SDimitry Andric // we ignore constness of pointer types.
typesCompatible(ASTContext & C,QualType A,QualType B)1380b57cec5SDimitry Andric static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
1390b57cec5SDimitry Andric // sizeof(void*) is compatible with any other pointer.
1400b57cec5SDimitry Andric if (B->isVoidPointerType() && A->getAs<PointerType>())
1410b57cec5SDimitry Andric return true;
1420b57cec5SDimitry Andric
143fe6060f1SDimitry Andric // sizeof(pointer type) is compatible with void*
144fe6060f1SDimitry Andric if (A->isVoidPointerType() && B->getAs<PointerType>())
145fe6060f1SDimitry Andric return true;
146fe6060f1SDimitry Andric
1470b57cec5SDimitry Andric while (true) {
1480b57cec5SDimitry Andric A = A.getCanonicalType();
1490b57cec5SDimitry Andric B = B.getCanonicalType();
1500b57cec5SDimitry Andric
1510b57cec5SDimitry Andric if (A.getTypePtr() == B.getTypePtr())
1520b57cec5SDimitry Andric return true;
1530b57cec5SDimitry Andric
1540b57cec5SDimitry Andric if (const PointerType *ptrA = A->getAs<PointerType>())
1550b57cec5SDimitry Andric if (const PointerType *ptrB = B->getAs<PointerType>()) {
1560b57cec5SDimitry Andric A = ptrA->getPointeeType();
1570b57cec5SDimitry Andric B = ptrB->getPointeeType();
1580b57cec5SDimitry Andric continue;
1590b57cec5SDimitry Andric }
1600b57cec5SDimitry Andric
1610b57cec5SDimitry Andric break;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric
1640b57cec5SDimitry Andric return false;
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric
compatibleWithArrayType(ASTContext & C,QualType PT,QualType T)1670b57cec5SDimitry Andric static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
1680b57cec5SDimitry Andric // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
1690b57cec5SDimitry Andric while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
1700b57cec5SDimitry Andric QualType ElemType = AT->getElementType();
1710b57cec5SDimitry Andric if (typesCompatible(C, PT, AT->getElementType()))
1720b57cec5SDimitry Andric return true;
1730b57cec5SDimitry Andric T = ElemType;
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric
1760b57cec5SDimitry Andric return false;
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric
1790b57cec5SDimitry Andric class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
1800b57cec5SDimitry Andric public:
checkASTCodeBody(const Decl * D,AnalysisManager & mgr,BugReporter & BR) const1810b57cec5SDimitry Andric void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
1820b57cec5SDimitry Andric BugReporter &BR) const {
1830b57cec5SDimitry Andric AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
1840b57cec5SDimitry Andric CastedAllocFinder Finder(&BR.getContext());
1850b57cec5SDimitry Andric Finder.Visit(D->getBody());
186*06c3fb27SDimitry Andric for (const auto &CallRec : Finder.Calls) {
187*06c3fb27SDimitry Andric QualType CastedType = CallRec.CastedExpr->getType();
1880b57cec5SDimitry Andric if (!CastedType->isPointerType())
1890b57cec5SDimitry Andric continue;
190a7dea167SDimitry Andric QualType PointeeType = CastedType->getPointeeType();
1910b57cec5SDimitry Andric if (PointeeType->isVoidType())
1920b57cec5SDimitry Andric continue;
1930b57cec5SDimitry Andric
194*06c3fb27SDimitry Andric for (const Expr *Arg : CallRec.AllocCall->arguments()) {
195*06c3fb27SDimitry Andric if (!Arg->getType()->isIntegralOrUnscopedEnumerationType())
1960b57cec5SDimitry Andric continue;
1970b57cec5SDimitry Andric
1980b57cec5SDimitry Andric SizeofFinder SFinder;
199*06c3fb27SDimitry Andric SFinder.Visit(Arg);
2000b57cec5SDimitry Andric if (SFinder.Sizeofs.size() != 1)
2010b57cec5SDimitry Andric continue;
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
2040b57cec5SDimitry Andric
2050b57cec5SDimitry Andric if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
2060b57cec5SDimitry Andric continue;
2070b57cec5SDimitry Andric
2080b57cec5SDimitry Andric // If the argument to sizeof is an array, the result could be a
2090b57cec5SDimitry Andric // pointer to any array element.
2100b57cec5SDimitry Andric if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
2110b57cec5SDimitry Andric continue;
2120b57cec5SDimitry Andric
2130b57cec5SDimitry Andric const TypeSourceInfo *TSI = nullptr;
214*06c3fb27SDimitry Andric if (CallRec.CastedExprParent.is<const VarDecl *>()) {
215*06c3fb27SDimitry Andric TSI = CallRec.CastedExprParent.get<const VarDecl *>()
216*06c3fb27SDimitry Andric ->getTypeSourceInfo();
2170b57cec5SDimitry Andric } else {
218*06c3fb27SDimitry Andric TSI = CallRec.ExplicitCastType;
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric
2210b57cec5SDimitry Andric SmallString<64> buf;
2220b57cec5SDimitry Andric llvm::raw_svector_ostream OS(buf);
2230b57cec5SDimitry Andric
2240b57cec5SDimitry Andric OS << "Result of ";
225*06c3fb27SDimitry Andric const FunctionDecl *Callee = CallRec.AllocCall->getDirectCallee();
2260b57cec5SDimitry Andric if (Callee && Callee->getIdentifier())
2270b57cec5SDimitry Andric OS << '\'' << Callee->getIdentifier()->getName() << '\'';
2280b57cec5SDimitry Andric else
2290b57cec5SDimitry Andric OS << "call";
23081ad6265SDimitry Andric OS << " is converted to a pointer of type '" << PointeeType
23181ad6265SDimitry Andric << "', which is incompatible with "
23281ad6265SDimitry Andric << "sizeof operand type '" << SizeofType << "'";
2330b57cec5SDimitry Andric SmallVector<SourceRange, 4> Ranges;
234*06c3fb27SDimitry Andric Ranges.push_back(CallRec.AllocCall->getCallee()->getSourceRange());
2350b57cec5SDimitry Andric Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
2360b57cec5SDimitry Andric if (TSI)
2370b57cec5SDimitry Andric Ranges.push_back(TSI->getTypeLoc().getSourceRange());
2380b57cec5SDimitry Andric
239*06c3fb27SDimitry Andric PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
240*06c3fb27SDimitry Andric CallRec.AllocCall->getCallee(), BR.getSourceManager(), ADC);
2410b57cec5SDimitry Andric
2420b57cec5SDimitry Andric BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
2430b57cec5SDimitry Andric categories::UnixAPI, OS.str(), L, Ranges);
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric };
2480b57cec5SDimitry Andric
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric
registerMallocSizeofChecker(CheckerManager & mgr)2510b57cec5SDimitry Andric void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
2520b57cec5SDimitry Andric mgr.registerChecker<MallocSizeofChecker>();
2530b57cec5SDimitry Andric }
2540b57cec5SDimitry Andric
shouldRegisterMallocSizeofChecker(const CheckerManager & mgr)2555ffd83dbSDimitry Andric bool ento::shouldRegisterMallocSizeofChecker(const CheckerManager &mgr) {
2560b57cec5SDimitry Andric return true;
2570b57cec5SDimitry Andric }
258