1 //=== LLVMConventionsChecker.cpp - Check LLVM codebase conventions ---*- C++ -*-
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines LLVMConventionsChecker, a bunch of small little checks
11 // for checking specific coding conventions in the LLVM/Clang codebase.
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // Generic type checking routines.
28 //===----------------------------------------------------------------------===//
30 static bool IsLLVMStringRef(QualType T) {
31 const RecordType *RT = T->getAs<RecordType>();
35 return StringRef(QualType(RT, 0).getAsString()) == "class StringRef";
38 /// Check whether the declaration is semantically inside the top-level
39 /// namespace named by ns.
40 static bool InNamespace(const Decl *D, StringRef NS) {
41 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext());
44 const IdentifierInfo *II = ND->getIdentifier();
45 if (!II || !II->getName().equals(NS))
47 return isa<TranslationUnitDecl>(ND->getDeclContext());
50 static bool IsStdString(QualType T) {
51 if (const ElaboratedType *QT = T->getAs<ElaboratedType>())
52 T = QT->getNamedType();
54 const TypedefType *TT = T->getAs<TypedefType>();
58 const TypedefNameDecl *TD = TT->getDecl();
60 if (!TD->isInStdNamespace())
63 return TD->getName() == "string";
66 static bool IsClangType(const RecordDecl *RD) {
67 return RD->getName() == "Type" && InNamespace(RD, "clang");
70 static bool IsClangDecl(const RecordDecl *RD) {
71 return RD->getName() == "Decl" && InNamespace(RD, "clang");
74 static bool IsClangStmt(const RecordDecl *RD) {
75 return RD->getName() == "Stmt" && InNamespace(RD, "clang");
78 static bool IsClangAttr(const RecordDecl *RD) {
79 return RD->getName() == "Attr" && InNamespace(RD, "clang");
82 static bool IsStdVector(QualType T) {
83 const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
87 TemplateName TM = TS->getTemplateName();
88 TemplateDecl *TD = TM.getAsTemplateDecl();
90 if (!TD || !InNamespace(TD, "std"))
93 return TD->getName() == "vector";
96 static bool IsSmallVector(QualType T) {
97 const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
101 TemplateName TM = TS->getTemplateName();
102 TemplateDecl *TD = TM.getAsTemplateDecl();
104 if (!TD || !InNamespace(TD, "llvm"))
107 return TD->getName() == "SmallVector";
110 //===----------------------------------------------------------------------===//
111 // CHECK: a StringRef should not be bound to a temporary std::string whose
112 // lifetime is shorter than the StringRef's.
113 //===----------------------------------------------------------------------===//
116 class StringRefCheckerVisitor : public StmtVisitor<StringRefCheckerVisitor> {
117 const Decl *DeclWithIssue;
119 const CheckerBase *Checker;
122 StringRefCheckerVisitor(const Decl *declWithIssue, BugReporter &br,
123 const CheckerBase *checker)
124 : DeclWithIssue(declWithIssue), BR(br), Checker(checker) {}
125 void VisitChildren(Stmt *S) {
126 for (Stmt *Child : S->children())
130 void VisitStmt(Stmt *S) { VisitChildren(S); }
131 void VisitDeclStmt(DeclStmt *DS);
133 void VisitVarDecl(VarDecl *VD);
135 } // end anonymous namespace
137 static void CheckStringRefAssignedTemporary(const Decl *D, BugReporter &BR,
138 const CheckerBase *Checker) {
139 StringRefCheckerVisitor walker(D, BR, Checker);
140 walker.Visit(D->getBody());
143 void StringRefCheckerVisitor::VisitDeclStmt(DeclStmt *S) {
146 for (auto *I : S->decls())
147 if (VarDecl *VD = dyn_cast<VarDecl>(I))
151 void StringRefCheckerVisitor::VisitVarDecl(VarDecl *VD) {
152 Expr *Init = VD->getInit();
156 // Pattern match for:
157 // StringRef x = call() (where call returns std::string)
158 if (!IsLLVMStringRef(VD->getType()))
160 ExprWithCleanups *Ex1 = dyn_cast<ExprWithCleanups>(Init);
163 CXXConstructExpr *Ex2 = dyn_cast<CXXConstructExpr>(Ex1->getSubExpr());
164 if (!Ex2 || Ex2->getNumArgs() != 1)
166 ImplicitCastExpr *Ex3 = dyn_cast<ImplicitCastExpr>(Ex2->getArg(0));
169 CXXConstructExpr *Ex4 = dyn_cast<CXXConstructExpr>(Ex3->getSubExpr());
170 if (!Ex4 || Ex4->getNumArgs() != 1)
172 ImplicitCastExpr *Ex5 = dyn_cast<ImplicitCastExpr>(Ex4->getArg(0));
175 CXXBindTemporaryExpr *Ex6 = dyn_cast<CXXBindTemporaryExpr>(Ex5->getSubExpr());
176 if (!Ex6 || !IsStdString(Ex6->getType()))
179 // Okay, badness! Report an error.
180 const char *desc = "StringRef should not be bound to temporary "
181 "std::string that it outlives";
182 PathDiagnosticLocation VDLoc =
183 PathDiagnosticLocation::createBegin(VD, BR.getSourceManager());
184 BR.EmitBasicReport(DeclWithIssue, Checker, desc, "LLVM Conventions", desc,
185 VDLoc, Init->getSourceRange());
188 //===----------------------------------------------------------------------===//
189 // CHECK: Clang AST nodes should not have fields that can allocate
191 //===----------------------------------------------------------------------===//
193 static bool AllocatesMemory(QualType T) {
194 return IsStdVector(T) || IsStdString(T) || IsSmallVector(T);
197 // This type checking could be sped up via dynamic programming.
198 static bool IsPartOfAST(const CXXRecordDecl *R) {
199 if (IsClangStmt(R) || IsClangType(R) || IsClangDecl(R) || IsClangAttr(R))
202 for (const auto &BS : R->bases()) {
203 QualType T = BS.getType();
204 if (const RecordType *baseT = T->getAs<RecordType>()) {
205 CXXRecordDecl *baseD = cast<CXXRecordDecl>(baseT->getDecl());
206 if (IsPartOfAST(baseD))
215 class ASTFieldVisitor {
216 SmallVector<FieldDecl*, 10> FieldChain;
217 const CXXRecordDecl *Root;
219 const CheckerBase *Checker;
222 ASTFieldVisitor(const CXXRecordDecl *root, BugReporter &br,
223 const CheckerBase *checker)
224 : Root(root), BR(br), Checker(checker) {}
226 void Visit(FieldDecl *D);
227 void ReportError(QualType T);
229 } // end anonymous namespace
231 static void CheckASTMemory(const CXXRecordDecl *R, BugReporter &BR,
232 const CheckerBase *Checker) {
236 for (auto *I : R->fields()) {
237 ASTFieldVisitor walker(R, BR, Checker);
242 void ASTFieldVisitor::Visit(FieldDecl *D) {
243 FieldChain.push_back(D);
245 QualType T = D->getType();
247 if (AllocatesMemory(T))
250 if (const RecordType *RT = T->getAs<RecordType>()) {
251 const RecordDecl *RD = RT->getDecl()->getDefinition();
252 for (auto *I : RD->fields())
256 FieldChain.pop_back();
259 void ASTFieldVisitor::ReportError(QualType T) {
260 SmallString<1024> buf;
261 llvm::raw_svector_ostream os(buf);
263 os << "AST class '" << Root->getName() << "' has a field '"
264 << FieldChain.front()->getName() << "' that allocates heap memory";
265 if (FieldChain.size() > 1) {
266 os << " via the following chain: ";
268 for (SmallVectorImpl<FieldDecl*>::iterator I=FieldChain.begin(),
269 E=FieldChain.end(); I!=E; ++I) {
274 os << (*I)->getName();
277 os << " (type " << FieldChain.back()->getType().getAsString() << ")";
279 // Note that this will fire for every translation unit that uses this
280 // class. This is suboptimal, but at least scan-build will merge
281 // duplicate HTML reports. In the future we need a unified way of merging
282 // duplicate reports across translation units. For C++ classes we cannot
283 // just report warnings when we see an out-of-line method definition for a
284 // class, as that heuristic doesn't always work (the complete definition of
285 // the class may be in the header file, for example).
286 PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
287 FieldChain.front(), BR.getSourceManager());
288 BR.EmitBasicReport(Root, Checker, "AST node allocates heap memory",
289 "LLVM Conventions", os.str(), L);
292 //===----------------------------------------------------------------------===//
293 // LLVMConventionsChecker
294 //===----------------------------------------------------------------------===//
297 class LLVMConventionsChecker : public Checker<
298 check::ASTDecl<CXXRecordDecl>,
299 check::ASTCodeBody > {
301 void checkASTDecl(const CXXRecordDecl *R, AnalysisManager& mgr,
302 BugReporter &BR) const {
303 if (R->isCompleteDefinition())
304 CheckASTMemory(R, BR, this);
307 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
308 BugReporter &BR) const {
309 CheckStringRefAssignedTemporary(D, BR, this);
314 void ento::registerLLVMConventionsChecker(CheckerManager &mgr) {
315 mgr.registerChecker<LLVMConventionsChecker>();