LLVMConventionsChecker.cpp 9.9 KB

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