clang 23.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/Support/raw_ostream.h"
23
24using namespace clang;
25using namespace ento;
26
27namespace {
28
29typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
30typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
31
32class CastedAllocFinder
33 : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
34 IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
35
36public:
37 struct CallRecord {
38 ExprParent CastedExprParent;
39 const Expr *CastedExpr;
40 const TypeSourceInfo *ExplicitCastType;
41 const CallExpr *AllocCall;
42
43 CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr,
44 const TypeSourceInfo *ExplicitCastType,
45 const CallExpr *AllocCall)
46 : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr),
47 ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {}
48 };
49
50 typedef std::vector<CallRecord> CallVec;
51 CallVec Calls;
52
53 CastedAllocFinder(ASTContext *Ctx) :
54 II_malloc(&Ctx->Idents.get("malloc")),
55 II_calloc(&Ctx->Idents.get("calloc")),
56 II_realloc(&Ctx->Idents.get("realloc")) {}
57
58 void VisitChild(ExprParent Parent, const Stmt *S) {
59 TypeCallPair AllocCall = Visit(S);
60 if (AllocCall.second && AllocCall.second != S)
61 Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
62 AllocCall.second));
63 }
64
65 void VisitChildren(const Stmt *S) {
66 for (const Stmt *Child : S->children())
67 if (Child)
68 VisitChild(S, Child);
69 }
70
71 TypeCallPair VisitCastExpr(const CastExpr *E) {
72 return Visit(E->getSubExpr());
73 }
74
75 TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
76 return TypeCallPair(E->getTypeInfoAsWritten(),
77 Visit(E->getSubExpr()).second);
78 }
79
80 TypeCallPair VisitParenExpr(const ParenExpr *E) {
81 return Visit(E->getSubExpr());
82 }
83
84 TypeCallPair VisitStmt(const Stmt *S) {
85 VisitChildren(S);
86 return TypeCallPair();
87 }
88
89 TypeCallPair VisitCallExpr(const CallExpr *E) {
90 VisitChildren(E);
91 const FunctionDecl *FD = E->getDirectCallee();
92 if (FD) {
93 IdentifierInfo *II = FD->getIdentifier();
94 if (II == II_malloc || II == II_calloc || II == II_realloc)
95 return TypeCallPair((const TypeSourceInfo *)nullptr, E);
96 }
97 return TypeCallPair();
98 }
99
100 TypeCallPair VisitDeclStmt(const DeclStmt *S) {
101 for (const auto *I : S->decls())
102 if (const VarDecl *VD = dyn_cast<VarDecl>(I))
103 if (const Expr *Init = VD->getInit())
104 VisitChild(VD, Init);
105 return TypeCallPair();
106 }
107};
108
109class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
110public:
111 std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
112
113 void VisitBinMul(const BinaryOperator *E) {
114 Visit(E->getLHS());
115 Visit(E->getRHS());
116 }
117
118 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
119 return Visit(E->getSubExpr());
120 }
121
122 void VisitParenExpr(const ParenExpr *E) {
123 return Visit(E->getSubExpr());
124 }
125
126 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
127 if (E->getKind() != UETT_SizeOf)
128 return;
129
130 Sizeofs.push_back(E);
131 }
132};
133
134// Determine if the pointee and sizeof types are compatible. Here
135// we ignore constness of pointer types.
136static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
137 // sizeof(void*) is compatible with any other pointer.
138 if (B->isVoidPointerType() && A->getAs<PointerType>())
139 return true;
140
141 // sizeof(pointer type) is compatible with void*
142 if (A->isVoidPointerType() && B->getAs<PointerType>())
143 return true;
144
145 while (true) {
146 A = A.getCanonicalType();
147 B = B.getCanonicalType();
148
149 if (A.getTypePtr() == B.getTypePtr())
150 return true;
151
152 const PointerType *ptrA = A->getAs<PointerType>();
153 const PointerType *ptrB = B->getAs<PointerType>();
154
155 // When neither type is a pointer and exactly one is a record type, check
156 // target-specific size and alignment. This avoids false positives for
157 // types that wrap another type with the same layout (e.g.
158 // std::atomic<int32_t> vs int32_t, or struct{int32_t x;} vs int32_t),
159 // while preserving warnings for unrelated types that happen to share a
160 // size (e.g. long vs double, struct A vs struct B).
161 if (!ptrA && !ptrB && (A->isRecordType() != B->isRecordType()) &&
162 !A->isIncompleteType() && !B->isIncompleteType()) {
163 const RecordType *RecTy = A->getAs<RecordType>();
164 QualType Scalar = B;
165 if (!RecTy) {
166 RecTy = B->getAs<RecordType>();
167 Scalar = A;
168 }
169 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RecTy->getDecl())) {
170 if (RD->isStandardLayout()) {
171 const CXXRecordDecl *Base = RD->getStandardLayoutBaseWithFields();
172 auto F = Base->field_begin();
173 if (F != Base->field_end() && std::next(F) == Base->field_end() &&
174 C.getCanonicalType((*F)->getType()) == Scalar)
175 return true;
176 }
177 }
178 }
179
180 if (ptrA && ptrB) {
181 A = ptrA->getPointeeType();
182 B = ptrB->getPointeeType();
183 continue;
184 }
185
186 break;
187 }
188
189 return false;
190}
191
192static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
193 // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
194 while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
195 QualType ElemType = AT->getElementType();
196 if (typesCompatible(C, PT, AT->getElementType()))
197 return true;
198 T = ElemType;
199 }
200
201 return false;
202}
203
204class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
205public:
206 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
207 BugReporter &BR) const {
208 AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
209 CastedAllocFinder Finder(&BR.getContext());
210 Finder.Visit(D->getBody());
211 for (const auto &CallRec : Finder.Calls) {
212 QualType CastedType = CallRec.CastedExpr->getType();
213 if (!CastedType->isPointerType())
214 continue;
215 QualType PointeeType = CastedType->getPointeeType();
216 if (PointeeType->isVoidType())
217 continue;
218
219 for (const Expr *Arg : CallRec.AllocCall->arguments()) {
220 if (!Arg->getType()->isIntegralOrUnscopedEnumerationType())
221 continue;
222
223 SizeofFinder SFinder;
224 SFinder.Visit(Arg);
225 if (SFinder.Sizeofs.size() != 1)
226 continue;
227
228 QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
229
230 if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
231 continue;
232
233 // If the argument to sizeof is an array, the result could be a
234 // pointer to any array element.
235 if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
236 continue;
237
238 const TypeSourceInfo *TSI = nullptr;
239 if (const auto *VD =
240 dyn_cast<const VarDecl *>(CallRec.CastedExprParent)) {
241 TSI = VD->getTypeSourceInfo();
242 } else {
243 TSI = CallRec.ExplicitCastType;
244 }
245
246 SmallString<64> buf;
247 llvm::raw_svector_ostream OS(buf);
248
249 OS << "Result of ";
250 const FunctionDecl *Callee = CallRec.AllocCall->getDirectCallee();
251 if (Callee && Callee->getIdentifier())
252 OS << '\'' << Callee->getIdentifier()->getName() << '\'';
253 else
254 OS << "call";
255 OS << " is converted to a pointer of type '" << PointeeType
256 << "', which is incompatible with "
257 << "sizeof operand type '" << SizeofType << "'";
258 SmallVector<SourceRange, 4> Ranges;
259 Ranges.push_back(CallRec.AllocCall->getCallee()->getSourceRange());
260 Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
261 if (TSI)
262 Ranges.push_back(TSI->getTypeLoc().getSourceRange());
263
264 PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
265 CallRec.AllocCall->getCallee(), BR.getSourceManager(), ADC);
266
267 BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
268 categories::UnixAPI, OS.str(), L, Ranges);
269 }
270 }
271 }
272};
273
274}
275
276void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
277 mgr.registerChecker<MallocSizeofChecker>();
278}
279
280bool ento::shouldRegisterMallocSizeofChecker(const CheckerManager &mgr) {
281 return true;
282}
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:223
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
Expr * getLHS() const
Definition Expr.h:4094
Expr * getRHS() const
Definition Expr.h:4096
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
Expr * getSubExpr()
Definition Expr.h:3732
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
decl_range decls()
Definition Stmt.h:1689
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:1100
TypeSourceInfo * getTypeInfoAsWritten() const
getTypeInfoAsWritten - Returns the type source info for the type that this expression is casting to.
Definition Expr.h:3956
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
const Expr * getSubExpr() const
Definition Expr.h:2205
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
A (possibly-)qualified type.
Definition TypeBase.h:937
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
QualType getCanonicalType() const
Definition TypeBase.h:8499
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
bool isVoidType() const
Definition TypeBase.h:9050
bool isVoidPointerType() const
Definition Type.cpp:749
bool isPointerType() const
Definition TypeBase.h:8684
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isRecordType() const
Definition TypeBase.h:8811
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2663
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
const SourceManager & getSourceManager()
ASTContext & getContext()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
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.
U cast(CodeGen::Address addr)
Definition Address.h:327