Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//=== LLVMConventionsChecker.cpp - Check LLVM codebase conventions ---*- 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
// This defines LLVMConventionsChecker, a bunch of small little checks
10
// for checking specific coding conventions in the LLVM/Clang codebase.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/StmtVisitor.h"
17
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18
#include "clang/StaticAnalyzer/Core/Checker.h"
19
#include "llvm/ADT/SmallString.h"
20
#include "llvm/Support/raw_ostream.h"
21
22
using namespace clang;
23
using namespace ento;
24
25
//===----------------------------------------------------------------------===//
26
// Generic type checking routines.
27
//===----------------------------------------------------------------------===//
28
29
4
static bool IsLLVMStringRef(QualType T) {
30
4
  const RecordType *RT = T->getAs<RecordType>();
31
4
  if (!RT)
32
0
    return false;
33
34
4
  return StringRef(QualType(RT, 0).getAsString()) == "class StringRef";
35
4
}
36
37
/// Check whether the declaration is semantically inside the top-level
38
/// namespace named by ns.
39
5
static bool InNamespace(const Decl *D, StringRef NS) {
40
5
  const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext());
41
5
  if (!ND)
42
0
    return false;
43
5
  const IdentifierInfo *II = ND->getIdentifier();
44
5
  if (!II || !II->getName().equals(NS))
45
1
    return false;
46
4
  return isa<TranslationUnitDecl>(ND->getDeclContext());
47
5
}
48
49
2
static bool IsStdString(QualType T) {
50
2
  if (const ElaboratedType *QT = T->getAs<ElaboratedType>())
51
2
    T = QT->getNamedType();
52
53
2
  const TypedefType *TT = T->getAs<TypedefType>();
54
2
  if (!TT)
55
1
    return false;
56
57
1
  const TypedefNameDecl *TD = TT->getDecl();
58
59
1
  if (!TD->isInStdNamespace())
60
0
    return false;
61
62
1
  return TD->getName() == "string";
63
1
}
64
65
5
static bool IsClangType(const RecordDecl *RD) {
66
5
  return RD->getName() == "Type" && 
InNamespace(RD, "clang")1
;
67
5
}
68
69
4
static bool IsClangDecl(const RecordDecl *RD) {
70
4
  return RD->getName() == "Decl" && 
InNamespace(RD, "clang")1
;
71
4
}
72
73
5
static bool IsClangStmt(const RecordDecl *RD) {
74
5
  return RD->getName() == "Stmt" && 
InNamespace(RD, "clang")0
;
75
5
}
76
77
3
static bool IsClangAttr(const RecordDecl *RD) {
78
3
  return RD->getName() == "Attr" && 
InNamespace(RD, "clang")0
;
79
3
}
80
81
2
static bool IsStdVector(QualType T) {
82
2
  const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
83
2
  if (!TS)
84
0
    return false;
85
86
2
  TemplateName TM = TS->getTemplateName();
87
2
  TemplateDecl *TD = TM.getAsTemplateDecl();
88
89
2
  if (!TD || !InNamespace(TD, "std"))
90
1
    return false;
91
92
1
  return TD->getName() == "vector";
93
2
}
94
95
1
static bool IsSmallVector(QualType T) {
96
1
  const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
97
1
  if (!TS)
98
0
    return false;
99
100
1
  TemplateName TM = TS->getTemplateName();
101
1
  TemplateDecl *TD = TM.getAsTemplateDecl();
102
103
1
  if (!TD || !InNamespace(TD, "llvm"))
104
0
    return false;
105
106
1
  return TD->getName() == "SmallVector";
107
1
}
108
109
//===----------------------------------------------------------------------===//
110
// CHECK: a StringRef should not be bound to a temporary std::string whose
111
// lifetime is shorter than the StringRef's.
112
//===----------------------------------------------------------------------===//
113
114
namespace {
115
class StringRefCheckerVisitor : public StmtVisitor<StringRefCheckerVisitor> {
116
  const Decl *DeclWithIssue;
117
  BugReporter &BR;
118
  const CheckerBase *Checker;
119
120
public:
121
  StringRefCheckerVisitor(const Decl *declWithIssue, BugReporter &br,
122
                          const CheckerBase *checker)
123
5
      : DeclWithIssue(declWithIssue), BR(br), Checker(checker) {}
124
60
  void VisitChildren(Stmt *S) {
125
60
    for (Stmt *Child : S->children())
126
55
      if (Child)
127
55
        Visit(Child);
128
60
  }
129
56
  void VisitStmt(Stmt *S) { VisitChildren(S); }
130
  void VisitDeclStmt(DeclStmt *DS);
131
private:
132
  void VisitVarDecl(VarDecl *VD);
133
};
134
} // end anonymous namespace
135
136
static void CheckStringRefAssignedTemporary(const Decl *D, BugReporter &BR,
137
5
                                            const CheckerBase *Checker) {
138
5
  StringRefCheckerVisitor walker(D, BR, Checker);
139
5
  walker.Visit(D->getBody());
140
5
}
141
142
4
void StringRefCheckerVisitor::VisitDeclStmt(DeclStmt *S) {
143
4
  VisitChildren(S);
144
145
4
  for (auto *I : S->decls())
146
4
    if (VarDecl *VD = dyn_cast<VarDecl>(I))
147
4
      VisitVarDecl(VD);
148
4
}
149
150
4
void StringRefCheckerVisitor::VisitVarDecl(VarDecl *VD) {
151
4
  Expr *Init = VD->getInit();
152
4
  if (!Init)
153
0
    return;
154
155
  // Pattern match for:
156
  // StringRef x = call() (where call returns std::string)
157
4
  if (!IsLLVMStringRef(VD->getType()))
158
4
    return;
159
0
  ExprWithCleanups *Ex1 = dyn_cast<ExprWithCleanups>(Init);
160
0
  if (!Ex1)
161
0
    return;
162
0
  CXXConstructExpr *Ex2 = dyn_cast<CXXConstructExpr>(Ex1->getSubExpr());
163
0
  if (!Ex2 || Ex2->getNumArgs() != 1)
164
0
    return;
165
0
  ImplicitCastExpr *Ex3 = dyn_cast<ImplicitCastExpr>(Ex2->getArg(0));
166
0
  if (!Ex3)
167
0
    return;
168
0
  CXXConstructExpr *Ex4 = dyn_cast<CXXConstructExpr>(Ex3->getSubExpr());
169
0
  if (!Ex4 || Ex4->getNumArgs() != 1)
170
0
    return;
171
0
  ImplicitCastExpr *Ex5 = dyn_cast<ImplicitCastExpr>(Ex4->getArg(0));
172
0
  if (!Ex5)
173
0
    return;
174
0
  CXXBindTemporaryExpr *Ex6 = dyn_cast<CXXBindTemporaryExpr>(Ex5->getSubExpr());
175
0
  if (!Ex6 || !IsStdString(Ex6->getType()))
176
0
    return;
177
178
  // Okay, badness!  Report an error.
179
0
  const char *desc = "StringRef should not be bound to temporary "
180
0
                     "std::string that it outlives";
181
0
  PathDiagnosticLocation VDLoc =
182
0
    PathDiagnosticLocation::createBegin(VD, BR.getSourceManager());
183
0
  BR.EmitBasicReport(DeclWithIssue, Checker, desc, "LLVM Conventions", desc,
184
0
                     VDLoc, Init->getSourceRange());
185
0
}
186
187
//===----------------------------------------------------------------------===//
188
// CHECK: Clang AST nodes should not have fields that can allocate
189
//   memory.
190
//===----------------------------------------------------------------------===//
191
192
2
static bool AllocatesMemory(QualType T) {
193
2
  return IsStdVector(T) || IsStdString(T) || 
IsSmallVector(T)1
;
194
2
}
195
196
// This type checking could be sped up via dynamic programming.
197
5
static bool IsPartOfAST(const CXXRecordDecl *R) {
198
5
  if (IsClangStmt(R) || IsClangType(R) || 
IsClangDecl(R)4
||
IsClangAttr(R)3
)
199
2
    return true;
200
201
3
  for (const auto &BS : R->bases()) {
202
0
    QualType T = BS.getType();
203
0
    if (const RecordType *baseT = T->getAs<RecordType>()) {
204
0
      CXXRecordDecl *baseD = cast<CXXRecordDecl>(baseT->getDecl());
205
0
      if (IsPartOfAST(baseD))
206
0
        return true;
207
0
    }
208
0
  }
209
210
3
  return false;
211
3
}
212
213
namespace {
214
class ASTFieldVisitor {
215
  SmallVector<FieldDecl*, 10> FieldChain;
216
  const CXXRecordDecl *Root;
217
  BugReporter &BR;
218
  const CheckerBase *Checker;
219
220
public:
221
  ASTFieldVisitor(const CXXRecordDecl *root, BugReporter &br,
222
                  const CheckerBase *checker)
223
2
      : Root(root), BR(br), Checker(checker) {}
224
225
  void Visit(FieldDecl *D);
226
  void ReportError(QualType T);
227
};
228
} // end anonymous namespace
229
230
static void CheckASTMemory(const CXXRecordDecl *R, BugReporter &BR,
231
5
                           const CheckerBase *Checker) {
232
5
  if (!IsPartOfAST(R))
233
3
    return;
234
235
2
  for (auto *I : R->fields()) {
236
2
    ASTFieldVisitor walker(R, BR, Checker);
237
2
    walker.Visit(I);
238
2
  }
239
2
}
240
241
2
void ASTFieldVisitor::Visit(FieldDecl *D) {
242
2
  FieldChain.push_back(D);
243
244
2
  QualType T = D->getType();
245
246
2
  if (AllocatesMemory(T))
247
2
    ReportError(T);
248
249
2
  if (const RecordType *RT = T->getAs<RecordType>()) {
250
2
    const RecordDecl *RD = RT->getDecl()->getDefinition();
251
2
    for (auto *I : RD->fields())
252
0
      Visit(I);
253
2
  }
254
255
2
  FieldChain.pop_back();
256
2
}
257
258
2
void ASTFieldVisitor::ReportError(QualType T) {
259
2
  SmallString<1024> buf;
260
2
  llvm::raw_svector_ostream os(buf);
261
262
2
  os << "AST class '" << Root->getName() << "' has a field '"
263
2
     << FieldChain.front()->getName() << "' that allocates heap memory";
264
2
  if (FieldChain.size() > 1) {
265
0
    os << " via the following chain: ";
266
0
    bool isFirst = true;
267
0
    for (SmallVectorImpl<FieldDecl*>::iterator I=FieldChain.begin(),
268
0
         E=FieldChain.end(); I!=E; ++I) {
269
0
      if (!isFirst)
270
0
        os << '.';
271
0
      else
272
0
        isFirst = false;
273
0
      os << (*I)->getName();
274
0
    }
275
0
  }
276
2
  os << " (type " << FieldChain.back()->getType() << ")";
277
278
  // Note that this will fire for every translation unit that uses this
279
  // class.  This is suboptimal, but at least scan-build will merge
280
  // duplicate HTML reports.  In the future we need a unified way of merging
281
  // duplicate reports across translation units.  For C++ classes we cannot
282
  // just report warnings when we see an out-of-line method definition for a
283
  // class, as that heuristic doesn't always work (the complete definition of
284
  // the class may be in the header file, for example).
285
2
  PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
286
2
                               FieldChain.front(), BR.getSourceManager());
287
2
  BR.EmitBasicReport(Root, Checker, "AST node allocates heap memory",
288
2
                     "LLVM Conventions", os.str(), L);
289
2
}
290
291
//===----------------------------------------------------------------------===//
292
// LLVMConventionsChecker
293
//===----------------------------------------------------------------------===//
294
295
namespace {
296
class LLVMConventionsChecker : public Checker<
297
                                                check::ASTDecl<CXXRecordDecl>,
298
                                                check::ASTCodeBody > {
299
public:
300
  void checkASTDecl(const CXXRecordDecl *R, AnalysisManager& mgr,
301
14
                    BugReporter &BR) const {
302
14
    if (R->isCompleteDefinition())
303
5
      CheckASTMemory(R, BR, this);
304
14
  }
305
306
  void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
307
5
                        BugReporter &BR) const {
308
5
    CheckStringRefAssignedTemporary(D, BR, this);
309
5
  }
310
};
311
}
312
313
1
void ento::registerLLVMConventionsChecker(CheckerManager &mgr) {
314
1
  mgr.registerChecker<LLVMConventionsChecker>();
315
1
}
316
317
2
bool ento::shouldRegisterLLVMConventionsChecker(const CheckerManager &mgr) {
318
2
  return true;
319
2
}