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
15#include "clang/AST/StmtVisitor.h"
16#include "clang/AST/TypeLoc.h"
17#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
18#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19#include "clang/StaticAnalyzer/Core/Checker.h"
20#include "clang/StaticAnalyzer/Core/CheckerManager.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.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(Name: "malloc")),
55 II_calloc(&Ctx->Idents.get(Name: "calloc")),
56 II_realloc(&Ctx->Idents.get(Name: "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(x: CallRecord(Parent, cast<Expr>(Val: 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(Parent: S, S: Child);
69 }
70
71 TypeCallPair VisitCastExpr(const CastExpr *E) {
72 return Visit(S: E->getSubExpr());
73 }
74
75 TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
76 return TypeCallPair(E->getTypeInfoAsWritten(),
77 Visit(S: E->getSubExpr()).second);
78 }
79
80 TypeCallPair VisitParenExpr(const ParenExpr *E) {
81 return Visit(S: 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(S: 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>(Val: I))
103 if (const Expr *Init = VD->getInit())
104 VisitChild(Parent: VD, S: 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(S: E->getLHS());
115 Visit(S: E->getRHS());
116 }
117
118 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
119 return Visit(S: E->getSubExpr());
120 }
121
122 void VisitParenExpr(const ParenExpr *E) {
123 return Visit(S: E->getSubExpr());
124 }
125
126 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
127 if (E->getKind() != UETT_SizeOf)
128 return;
129
130 Sizeofs.push_back(x: 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>(Val: 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(x: F) == Base->field_end() &&
174 C.getCanonicalType(T: (*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, A: PT, B: 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(S: 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(S: Arg);
225 if (SFinder.Sizeofs.size() != 1)
226 continue;
227
228 QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
229
230 if (typesCompatible(C&: BR.getContext(), A: PointeeType, B: 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(C&: BR.getContext(), PT: PointeeType, T: SizeofType))
236 continue;
237
238 const TypeSourceInfo *TSI = nullptr;
239 if (const auto *VD =
240 dyn_cast<const VarDecl *>(Val: 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(Elt: CallRec.AllocCall->getCallee()->getSourceRange());
260 Ranges.push_back(Elt: SFinder.Sizeofs[0]->getSourceRange());
261 if (TSI)
262 Ranges.push_back(Elt: TSI->getTypeLoc().getSourceRange());
263
264 PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
265 S: CallRec.AllocCall->getCallee(), SM: BR.getSourceManager(), SFAC: ADC);
266
267 BR.EmitBasicReport(DeclWithIssue: D, Checker: this, BugName: "Allocator sizeof operand mismatch",
268 BugCategory: categories::UnixAPI, BugStr: OS.str(), Loc: 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}
283