blob: 8b6e9c8a2c59c7814c8a002b99298ba4c0dab652 [file] [log] [blame]
Peter Collingbourne266e3dd2011-12-08 08:31:14 +00001// MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- C++ -*-=//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Peter Collingbourne266e3dd2011-12-08 08:31:14 +00006//
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
Kristof Umann76a21502018-12-15 16:23:51 +000015#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/StmtVisitor.h"
17#include "clang/AST/TypeLoc.h"
Peter Collingbourne266e3dd2011-12-08 08:31:14 +000018#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"
Benjamin Kramer49038022012-02-04 13:45:25 +000022#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000023#include "llvm/Support/raw_ostream.h"
Peter Collingbourne266e3dd2011-12-08 08:31:14 +000024
25using namespace clang;
26using namespace ento;
27
28namespace {
29
30typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
31typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
32
33class CastedAllocFinder
34 : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
35 IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
36
37public:
38 struct CallRecord {
39 ExprParent CastedExprParent;
40 const Expr *CastedExpr;
41 const TypeSourceInfo *ExplicitCastType;
42 const CallExpr *AllocCall;
43
44 CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr,
45 const TypeSourceInfo *ExplicitCastType,
46 const CallExpr *AllocCall)
47 : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr),
48 ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {}
49 };
50
51 typedef std::vector<CallRecord> CallVec;
52 CallVec Calls;
53
54 CastedAllocFinder(ASTContext *Ctx) :
55 II_malloc(&Ctx->Idents.get("malloc")),
56 II_calloc(&Ctx->Idents.get("calloc")),
57 II_realloc(&Ctx->Idents.get("realloc")) {}
58
59 void VisitChild(ExprParent Parent, const Stmt *S) {
60 TypeCallPair AllocCall = Visit(S);
61 if (AllocCall.second && AllocCall.second != S)
62 Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
63 AllocCall.second));
64 }
65
66 void VisitChildren(const Stmt *S) {
Benjamin Kramer973431b2015-07-03 15:12:24 +000067 for (const Stmt *Child : S->children())
68 if (Child)
69 VisitChild(S, Child);
Peter Collingbourne266e3dd2011-12-08 08:31:14 +000070 }
71
72 TypeCallPair VisitCastExpr(const CastExpr *E) {
73 return Visit(E->getSubExpr());
74 }
75
76 TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
77 return TypeCallPair(E->getTypeInfoAsWritten(),
78 Visit(E->getSubExpr()).second);
79 }
80
81 TypeCallPair VisitParenExpr(const ParenExpr *E) {
82 return Visit(E->getSubExpr());
83 }
84
85 TypeCallPair VisitStmt(const Stmt *S) {
86 VisitChildren(S);
87 return TypeCallPair();
88 }
89
90 TypeCallPair VisitCallExpr(const CallExpr *E) {
91 VisitChildren(E);
92 const FunctionDecl *FD = E->getDirectCallee();
93 if (FD) {
94 IdentifierInfo *II = FD->getIdentifier();
95 if (II == II_malloc || II == II_calloc || II == II_realloc)
Craig Topper0dbb7832014-05-27 02:45:47 +000096 return TypeCallPair((const TypeSourceInfo *)nullptr, E);
Peter Collingbourne266e3dd2011-12-08 08:31:14 +000097 }
98 return TypeCallPair();
99 }
100
101 TypeCallPair VisitDeclStmt(const DeclStmt *S) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000102 for (const auto *I : S->decls())
103 if (const VarDecl *VD = dyn_cast<VarDecl>(I))
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000104 if (const Expr *Init = VD->getInit())
105 VisitChild(VD, Init);
106 return TypeCallPair();
107 }
108};
109
110class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
111public:
112 std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
113
114 void VisitBinMul(const BinaryOperator *E) {
115 Visit(E->getLHS());
116 Visit(E->getRHS());
117 }
118
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000119 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
120 return Visit(E->getSubExpr());
121 }
122
123 void VisitParenExpr(const ParenExpr *E) {
124 return Visit(E->getSubExpr());
125 }
126
127 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
128 if (E->getKind() != UETT_SizeOf)
129 return;
130
131 Sizeofs.push_back(E);
132 }
133};
134
Ted Kremenekad8cd302012-05-01 00:10:19 +0000135// Determine if the pointee and sizeof types are compatible. Here
136// we ignore constness of pointer types.
137static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
Ted Kremenek0c28bc22014-10-19 07:30:55 +0000138 // sizeof(void*) is compatible with any other pointer.
139 if (B->isVoidPointerType() && A->getAs<PointerType>())
140 return true;
141
Ted Kremenekad8cd302012-05-01 00:10:19 +0000142 while (true) {
143 A = A.getCanonicalType();
144 B = B.getCanonicalType();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000145
Ted Kremenekad8cd302012-05-01 00:10:19 +0000146 if (A.getTypePtr() == B.getTypePtr())
147 return true;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000148
Ted Kremenekad8cd302012-05-01 00:10:19 +0000149 if (const PointerType *ptrA = A->getAs<PointerType>())
150 if (const PointerType *ptrB = B->getAs<PointerType>()) {
Ted Kremeneka0658792012-09-04 22:48:59 +0000151 A = ptrA->getPointeeType();
152 B = ptrB->getPointeeType();
153 continue;
Ted Kremenekad8cd302012-05-01 00:10:19 +0000154 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000155
Ted Kremenekad8cd302012-05-01 00:10:19 +0000156 break;
157 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000158
Ted Kremenekad8cd302012-05-01 00:10:19 +0000159 return false;
160}
161
Anna Zaks044f3e22012-09-08 00:09:02 +0000162static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
163 // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
164 while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
165 QualType ElemType = AT->getElementType();
166 if (typesCompatible(C, PT, AT->getElementType()))
167 return true;
168 T = ElemType;
169 }
170
171 return false;
172}
173
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000174class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
175public:
176 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
177 BugReporter &BR) const {
178 AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
179 CastedAllocFinder Finder(&BR.getContext());
180 Finder.Visit(D->getBody());
181 for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
182 e = Finder.Calls.end(); i != e; ++i) {
183 QualType CastedType = i->CastedExpr->getType();
184 if (!CastedType->isPointerType())
185 continue;
186 QualType PointeeType = CastedType->getAs<PointerType>()->getPointeeType();
187 if (PointeeType->isVoidType())
188 continue;
189
190 for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
191 ae = i->AllocCall->arg_end(); ai != ae; ++ai) {
Jordan Rose61e221f2013-04-09 02:30:33 +0000192 if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType())
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000193 continue;
194
195 SizeofFinder SFinder;
196 SFinder.Visit(*ai);
197 if (SFinder.Sizeofs.size() != 1)
198 continue;
199
200 QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000201
Anna Zaks694be012012-09-07 19:20:13 +0000202 if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
203 continue;
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000204
Anna Zaks694be012012-09-07 19:20:13 +0000205 // If the argument to sizeof is an array, the result could be a
Anna Zaks044f3e22012-09-08 00:09:02 +0000206 // pointer to any array element.
207 if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
208 continue;
Anna Zaks694be012012-09-07 19:20:13 +0000209
Craig Topper0dbb7832014-05-27 02:45:47 +0000210 const TypeSourceInfo *TSI = nullptr;
Anna Zaks694be012012-09-07 19:20:13 +0000211 if (i->CastedExprParent.is<const VarDecl *>()) {
212 TSI =
213 i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
214 } else {
215 TSI = i->ExplicitCastType;
216 }
217
218 SmallString<64> buf;
219 llvm::raw_svector_ostream OS(buf);
220
221 OS << "Result of ";
222 const FunctionDecl *Callee = i->AllocCall->getDirectCallee();
223 if (Callee && Callee->getIdentifier())
224 OS << '\'' << Callee->getIdentifier()->getName() << '\'';
225 else
226 OS << "call";
227 OS << " is converted to a pointer of type '"
228 << PointeeType.getAsString() << "', which is incompatible with "
229 << "sizeof operand type '" << SizeofType.getAsString() << "'";
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000230 SmallVector<SourceRange, 4> Ranges;
Anna Zaks694be012012-09-07 19:20:13 +0000231 Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
232 Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
233 if (TSI)
234 Ranges.push_back(TSI->getTypeLoc().getSourceRange());
235
236 PathDiagnosticLocation L =
237 PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
238 BR.getSourceManager(), ADC);
239
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000240 BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
241 categories::UnixAPI, OS.str(), L, Ranges);
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000242 }
243 }
244 }
245};
246
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000247}
Peter Collingbourne266e3dd2011-12-08 08:31:14 +0000248
249void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
250 mgr.registerChecker<MallocSizeofChecker>();
251}