Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
Line
Count
Source (jump to first uncovered line)
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/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16
#include "clang/AST/StmtVisitor.h"
17
#include "clang/AST/TypeLoc.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/ADT/SmallString.h"
23
#include "llvm/Support/raw_ostream.h"
24
25
using namespace clang;
26
using namespace ento;
27
28
namespace {
29
30
typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair;
31
typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent;
32
33
class CastedAllocFinder
34
  : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> {
35
  IdentifierInfo *II_malloc, *II_calloc, *II_realloc;
36
37
public:
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
286
        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
474
    II_realloc(&Ctx->Idents.get("realloc")) {}
58
59
6.73k
  void VisitChild(ExprParent Parent, const Stmt *S) {
60
6.73k
    TypeCallPair AllocCall = Visit(S);
61
6.73k
    if (AllocCall.second && 
AllocCall.second != S316
)
62
286
      Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first,
63
286
                                 AllocCall.second));
64
6.73k
  }
65
66
6.57k
  void VisitChildren(const Stmt *S) {
67
6.57k
    for (const Stmt *Child : S->children())
68
6.23k
      if (Child)
69
6.22k
        VisitChild(S, Child);
70
6.57k
  }
71
72
3.70k
  TypeCallPair VisitCastExpr(const CastExpr *E) {
73
3.70k
    return Visit(E->getSubExpr());
74
3.70k
  }
75
76
145
  TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) {
77
145
    return TypeCallPair(E->getTypeInfoAsWritten(),
78
145
                        Visit(E->getSubExpr()).second);
79
145
  }
80
81
33
  TypeCallPair VisitParenExpr(const ParenExpr *E) {
82
33
    return Visit(E->getSubExpr());
83
33
  }
84
85
5.35k
  TypeCallPair VisitStmt(const Stmt *S) {
86
5.35k
    VisitChildren(S);
87
5.35k
    return TypeCallPair();
88
5.35k
  }
89
90
1.21k
  TypeCallPair VisitCallExpr(const CallExpr *E) {
91
1.21k
    VisitChildren(E);
92
1.21k
    const FunctionDecl *FD = E->getDirectCallee();
93
1.21k
    if (FD) {
94
1.21k
      IdentifierInfo *II = FD->getIdentifier();
95
1.21k
      if (II == II_malloc || 
II == II_calloc949
||
II == II_realloc934
)
96
316
        return TypeCallPair((const TypeSourceInfo *)nullptr, E);
97
1.21k
    }
98
897
    return TypeCallPair();
99
1.21k
  }
100
101
636
  TypeCallPair VisitDeclStmt(const DeclStmt *S) {
102
636
    for (const auto *I : S->decls())
103
674
      if (const VarDecl *VD = dyn_cast<VarDecl>(I))
104
578
        if (const Expr *Init = VD->getInit())
105
505
          VisitChild(VD, Init);
106
636
    return TypeCallPair();
107
636
  }
108
};
109
110
class SizeofFinder : public ConstStmtVisitor<SizeofFinder> {
111
public:
112
  std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs;
113
114
22
  void VisitBinMul(const BinaryOperator *E) {
115
22
    Visit(E->getLHS());
116
22
    Visit(E->getRHS());
117
22
  }
118
119
223
  void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
120
223
    return Visit(E->getSubExpr());
121
223
  }
122
123
0
  void VisitParenExpr(const ParenExpr *E) {
124
0
    return Visit(E->getSubExpr());
125
0
  }
126
127
99
  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
128
99
    if (E->getKind() != UETT_SizeOf)
129
0
      return;
130
131
99
    Sizeofs.push_back(E);
132
99
  }
133
};
134
135
// Determine if the pointee and sizeof types are compatible.  Here
136
// we ignore constness of pointer types.
137
104
static bool typesCompatible(ASTContext &C, QualType A, QualType B) {
138
  // sizeof(void*) is compatible with any other pointer.
139
104
  if (B->isVoidPointerType() && 
A->getAs<PointerType>()2
)
140
1
    return true;
141
142
  // sizeof(pointer type) is compatible with void*
143
103
  if (A->isVoidPointerType() && 
B->getAs<PointerType>()1
)
144
1
    return true;
145
146
104
  
while (102
true) {
147
104
    A = A.getCanonicalType();
148
104
    B = B.getCanonicalType();
149
150
104
    if (A.getTypePtr() == B.getTypePtr())
151
87
      return true;
152
153
17
    if (const PointerType *ptrA = A->getAs<PointerType>())
154
3
      if (const PointerType *ptrB = B->getAs<PointerType>()) {
155
2
        A = ptrA->getPointeeType();
156
2
        B = ptrB->getPointeeType();
157
2
        continue;
158
2
      }
159
160
15
    break;
161
17
  }
162
163
15
  return false;
164
102
}
165
166
13
static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) {
167
  // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'.
168
15
  while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) {
169
5
    QualType ElemType = AT->getElementType();
170
5
    if (typesCompatible(C, PT, AT->getElementType()))
171
3
      return true;
172
2
    T = ElemType;
173
2
  }
174
175
10
  return false;
176
13
}
177
178
class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
179
public:
180
  void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
181
474
                        BugReporter &BR) const {
182
474
    AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
183
474
    CastedAllocFinder Finder(&BR.getContext());
184
474
    Finder.Visit(D->getBody());
185
474
    for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
186
760
         e = Finder.Calls.end(); i != e; 
++i286
) {
187
286
      QualType CastedType = i->CastedExpr->getType();
188
286
      if (!CastedType->isPointerType())
189
1
        continue;
190
285
      QualType PointeeType = CastedType->getPointeeType();
191
285
      if (PointeeType->isVoidType())
192
0
        continue;
193
194
285
      for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
195
619
           ae = i->AllocCall->arg_end(); ai != ae; 
++ai334
) {
196
334
        if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType())
197
34
          continue;
198
199
300
        SizeofFinder SFinder;
200
300
        SFinder.Visit(*ai);
201
300
        if (SFinder.Sizeofs.size() != 1)
202
201
          continue;
203
204
99
        QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument();
205
206
99
        if (typesCompatible(BR.getContext(), PointeeType, SizeofType))
207
86
          continue;
208
209
        // If the argument to sizeof is an array, the result could be a
210
        // pointer to any array element.
211
13
        if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType))
212
3
          continue;
213
214
10
        const TypeSourceInfo *TSI = nullptr;
215
10
        if (i->CastedExprParent.is<const VarDecl *>()) {
216
10
          TSI =
217
10
              i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
218
10
        } else {
219
0
          TSI = i->ExplicitCastType;
220
0
        }
221
222
10
        SmallString<64> buf;
223
10
        llvm::raw_svector_ostream OS(buf);
224
225
10
        OS << "Result of ";
226
10
        const FunctionDecl *Callee = i->AllocCall->getDirectCallee();
227
10
        if (Callee && Callee->getIdentifier())
228
10
          OS << '\'' << Callee->getIdentifier()->getName() << '\'';
229
0
        else
230
0
          OS << "call";
231
10
        OS << " is converted to a pointer of type '"
232
10
            << PointeeType.getAsString() << "', which is incompatible with "
233
10
            << "sizeof operand type '" << SizeofType.getAsString() << "'";
234
10
        SmallVector<SourceRange, 4> Ranges;
235
10
        Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
236
10
        Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
237
10
        if (TSI)
238
10
          Ranges.push_back(TSI->getTypeLoc().getSourceRange());
239
240
10
        PathDiagnosticLocation L =
241
10
            PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
242
10
                BR.getSourceManager(), ADC);
243
244
10
        BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
245
10
                           categories::UnixAPI, OS.str(), L, Ranges);
246
10
      }
247
285
    }
248
474
  }
249
};
250
251
}
252
253
65
void ento::registerMallocSizeofChecker(CheckerManager &mgr) {
254
65
  mgr.registerChecker<MallocSizeofChecker>();
255
65
}
256
257
134
bool ento::shouldRegisterMallocSizeofChecker(const CheckerManager &mgr) {
258
134
  return true;
259
134
}