Coverage Report

Created: 2019-07-24 05:18

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