clang 20.0.0git
MallocSizeofChecker.cpp
Go to the documentation of this file.
1// MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- C++ -*-=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Reports inconsistencies between the casted type of the return value of a
10// malloc/calloc/realloc call and the operand of any sizeof expressions
11// contained within its argument(s).
12//
13//===----------------------------------------------------------------------===//
14
16#include "clang/AST/TypeLoc.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace clang;
27using namespace ento;
28
29namespace {
30
31typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
32typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
33
34class CastedAllocFinder
35 : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
36 IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
37
38public:
39 struct CallRecord {
40 ExprParent CastedExprParent;
41 const Expr *CastedExpr;
42 const TypeSourceInfo *ExplicitCastType;
43 const CallExpr *AllocCall;
44
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) {}
50 };
51
52 typedef std::vector<CallRecord> CallVec;
53 CallVec Calls;
54
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")) {}
59
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,
64 AllocCall.second));
65 }
66
67 void VisitChildren(const Stmt *S) {
68 for (const Stmt *Child : S->children())
69 if (Child)
70 VisitChild(S, Child);
71 }
72
73 TypeCallPair VisitCastExpr(const CastExpr *E) {
74 return Visit(E->getSubExpr());
75 }
76
77 TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
78 return TypeCallPair(E->getTypeInfoAsWritten(),
79 Visit(E->getSubExpr()).second);
80 }
81
82 TypeCallPair VisitParenExpr(const ParenExpr *E) {
83 return Visit(E->getSubExpr());
84 }
85
86 TypeCallPair VisitStmt(const Stmt *S) {
87 VisitChildren(S);
88 return TypeCallPair();
89 }
90
91 TypeCallPair VisitCallExpr(const CallExpr *E) {
92 VisitChildren(E);
93 const FunctionDecl *FD = E->getDirectCallee();
94 if (FD) {
95 IdentifierInfo *II = FD->getIdentifier();
96 if (II == II_malloc || II == II_calloc || II == II_realloc)
97 return TypeCallPair((const TypeSourceInfo *)nullptr, E);
98 }
99 return TypeCallPair();
100 }
101
102 TypeCallPair VisitDeclStmt(const DeclStmt *S) {
103 for (const auto *I : S->decls())
104 if (const VarDecl *VD = dyn_cast<VarDecl>(I))
105 if (const Expr *Init = VD->getInit())
106 VisitChild(VD, Init);
107 return TypeCallPair();
108 }
109};
110
111class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
112public:
113 std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
114
115 void VisitBinMul(const BinaryOperator *E) {
116 Visit(E->getLHS());
117 Visit(E->getRHS());
118 }
119
120 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
121 return Visit(E->getSubExpr());
122 }
123
124 void VisitParenExpr(const ParenExpr *E) {
125 return Visit(E->getSubExpr());
126 }
127
128 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
129 if (E->getKind() != UETT_SizeOf)
130 return;
131
132 Sizeofs.push_back(E);
133 }
134};
135
136// Determine if the pointee and sizeof types are compatible. Here
137// we ignore constness of pointer types.
138static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
139 // sizeof(void*) is compatible with any other pointer.
140 if (B->isVoidPointerType() && A->getAs<PointerType>())
141 return true;
142
143 // sizeof(pointer type) is compatible with void*
144 if (A->isVoidPointerType() && B->getAs<PointerType>())
145 return true;
146
147 while (true) {
148 A = A.getCanonicalType();
149 B = B.getCanonicalType();
150
151 if (A.getTypePtr() == B.getTypePtr())
152 return true;
153
154 if (const PointerType *ptrA = A->getAs<PointerType>())
155 if (const PointerType *ptrB = B->getAs<PointerType>()) {
156 A = ptrA->getPointeeType();
157 B = ptrB->getPointeeType();
158 continue;
159 }
160
161 break;
162 }
163
164 return false;
165}
166
167static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
168 // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
169 while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
170 QualType ElemType = AT->getElementType();
171 if (typesCompatible(C, PT, AT->getElementType()))
172 return true;
173 T = ElemType;
174 }
175
176 return false;
177}
178
179class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
180public:
181 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
182 BugReporter &BR) const {
184 CastedAllocFinder Finder(&BR.getContext());
185 Finder.Visit(D->getBody());
186 for (const auto &CallRec : Finder.Calls) {
187 QualType CastedType = CallRec.CastedExpr->getType();
188 if (!CastedType->isPointerType())
189 continue;
190 QualType PointeeType = CastedType->getPointeeType();
191 if (PointeeType->isVoidType())
192 continue;
193
194 for (const Expr *Arg : CallRec.AllocCall->arguments()) {
195 if (!Arg->getType()->isIntegralOrUnscopedEnumerationType())
196 continue;
197
198 SizeofFinder SFinder;
199 SFinder.Visit(Arg);
200 if (SFinder.Sizeofs.size() != 1)
201 continue;
202
203 QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
204
205 if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
206 continue;
207
208 // If the argument to sizeof is an array, the result could be a
209 // pointer to any array element.
210 if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
211 continue;
212
213 const TypeSourceInfo *TSI = nullptr;
214 if (const auto *VD =
215 dyn_cast<const VarDecl *>(CallRec.CastedExprParent)) {
216 TSI = VD->getTypeSourceInfo();
217 } else {
218 TSI = CallRec.ExplicitCastType;
219 }
220
221 SmallString<64> buf;
222 llvm::raw_svector_ostream OS(buf);
223
224 OS << "Result of ";
225 const FunctionDecl *Callee = CallRec.AllocCall->getDirectCallee();
226 if (Callee && Callee->getIdentifier())
227 OS << '\'' << Callee->getIdentifier()->getName() << '\'';
228 else
229 OS << "call";
230 OS << " is converted to a pointer of type '" << PointeeType
231 << "', which is incompatible with "
232 << "sizeof operand type '" << SizeofType << "'";
234 Ranges.push_back(CallRec.AllocCall->getCallee()->getSourceRange());
235 Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
236 if (TSI)
237 Ranges.push_back(TSI->getTypeLoc().getSourceRange());
238
240 CallRec.AllocCall->getCallee(), BR.getSourceManager(), ADC);
241
242 BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
243 categories::UnixAPI, OS.str(), L, Ranges);
244 }
245 }
246 }
247};
248
249}
250
251void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
252 mgr.registerChecker<MallocSizeofChecker>();
253}
254
255bool ento::shouldRegisterMallocSizeofChecker(const CheckerManager &mgr) {
256 return true;
257}
NodeId Parent
Definition: ASTDiff.cpp:191
const Decl * D
Expr * E
Defines the clang::TypeLoc interface and its subclasses.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3547
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1529
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1076
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3799
This represents one expression.
Definition: Expr.h:110
Represents a function declaration or definition.
Definition: Decl.h:1935
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
A (possibly-)qualified type.
Definition: Type.h:929
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
QualType getCanonicalType() const
Definition: Type.h:7983
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition: StmtVisitor.h:44
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
A container of type source information.
Definition: Type.h:7902
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
bool isVoidType() const
Definition: Type.h:8510
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isPointerType() const
Definition: Type.h:8186
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8786
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2622
Represents a variable declaration or definition.
Definition: Decl.h:882
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:585
const SourceManager & getSourceManager()
Definition: BugReporter.h:623
ASTContext & getContext()
Definition: BugReporter.h:621
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T