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