UncountedLocalVarsChecker.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. //=======- UncountedLocalVarsChecker.cpp -------------------------*- 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. #include "ASTUtils.h"
  9. #include "DiagOutputUtils.h"
  10. #include "PtrTypesSemantics.h"
  11. #include "clang/AST/CXXInheritance.h"
  12. #include "clang/AST/Decl.h"
  13. #include "clang/AST/DeclCXX.h"
  14. #include "clang/AST/ParentMapContext.h"
  15. #include "clang/AST/RecursiveASTVisitor.h"
  16. #include "clang/Basic/SourceLocation.h"
  17. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  19. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  20. #include "clang/StaticAnalyzer/Core/Checker.h"
  21. #include "llvm/ADT/DenseSet.h"
  22. using namespace clang;
  23. using namespace ento;
  24. namespace {
  25. // for ( int a = ...) ... true
  26. // for ( int a : ...) ... true
  27. // if ( int* a = ) ... true
  28. // anything else ... false
  29. bool isDeclaredInForOrIf(const VarDecl *Var) {
  30. assert(Var);
  31. auto &ASTCtx = Var->getASTContext();
  32. auto parent = ASTCtx.getParents(*Var);
  33. if (parent.size() == 1) {
  34. if (auto *DS = parent.begin()->get<DeclStmt>()) {
  35. DynTypedNodeList grandParent = ASTCtx.getParents(*DS);
  36. if (grandParent.size() == 1) {
  37. return grandParent.begin()->get<ForStmt>() ||
  38. grandParent.begin()->get<IfStmt>() ||
  39. grandParent.begin()->get<CXXForRangeStmt>();
  40. }
  41. }
  42. }
  43. return false;
  44. }
  45. // FIXME: should be defined by anotations in the future
  46. bool isRefcountedStringsHack(const VarDecl *V) {
  47. assert(V);
  48. auto safeClass = [](const std::string &className) {
  49. return className == "String" || className == "AtomString" ||
  50. className == "UniquedString" || className == "Identifier";
  51. };
  52. QualType QT = V->getType();
  53. auto *T = QT.getTypePtr();
  54. if (auto *CXXRD = T->getAsCXXRecordDecl()) {
  55. if (safeClass(safeGetName(CXXRD)))
  56. return true;
  57. }
  58. if (T->isPointerType() || T->isReferenceType()) {
  59. if (auto *CXXRD = T->getPointeeCXXRecordDecl()) {
  60. if (safeClass(safeGetName(CXXRD)))
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl *Guarded,
  67. const VarDecl *MaybeGuardian) {
  68. assert(Guarded);
  69. assert(MaybeGuardian);
  70. if (!MaybeGuardian->isLocalVarDecl())
  71. return false;
  72. const CompoundStmt *guardiansClosestCompStmtAncestor = nullptr;
  73. ASTContext &ctx = MaybeGuardian->getASTContext();
  74. for (DynTypedNodeList guardianAncestors = ctx.getParents(*MaybeGuardian);
  75. !guardianAncestors.empty();
  76. guardianAncestors = ctx.getParents(
  77. *guardianAncestors
  78. .begin()) // FIXME - should we handle all of the parents?
  79. ) {
  80. for (auto &guardianAncestor : guardianAncestors) {
  81. if (auto *CStmtParentAncestor = guardianAncestor.get<CompoundStmt>()) {
  82. guardiansClosestCompStmtAncestor = CStmtParentAncestor;
  83. break;
  84. }
  85. }
  86. if (guardiansClosestCompStmtAncestor)
  87. break;
  88. }
  89. if (!guardiansClosestCompStmtAncestor)
  90. return false;
  91. // We need to skip the first CompoundStmt to avoid situation when guardian is
  92. // defined in the same scope as guarded variable.
  93. bool HaveSkippedFirstCompoundStmt = false;
  94. for (DynTypedNodeList guardedVarAncestors = ctx.getParents(*Guarded);
  95. !guardedVarAncestors.empty();
  96. guardedVarAncestors = ctx.getParents(
  97. *guardedVarAncestors
  98. .begin()) // FIXME - should we handle all of the parents?
  99. ) {
  100. for (auto &guardedVarAncestor : guardedVarAncestors) {
  101. if (auto *CStmtAncestor = guardedVarAncestor.get<CompoundStmt>()) {
  102. if (!HaveSkippedFirstCompoundStmt) {
  103. HaveSkippedFirstCompoundStmt = true;
  104. continue;
  105. }
  106. if (CStmtAncestor == guardiansClosestCompStmtAncestor)
  107. return true;
  108. }
  109. }
  110. }
  111. return false;
  112. }
  113. class UncountedLocalVarsChecker
  114. : public Checker<check::ASTDecl<TranslationUnitDecl>> {
  115. BugType Bug{this,
  116. "Uncounted raw pointer or reference not provably backed by "
  117. "ref-counted variable",
  118. "WebKit coding guidelines"};
  119. mutable BugReporter *BR;
  120. public:
  121. void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
  122. BugReporter &BRArg) const {
  123. BR = &BRArg;
  124. // The calls to checkAST* from AnalysisConsumer don't
  125. // visit template instantiations or lambda classes. We
  126. // want to visit those, so we make our own RecursiveASTVisitor.
  127. struct LocalVisitor : public RecursiveASTVisitor<LocalVisitor> {
  128. const UncountedLocalVarsChecker *Checker;
  129. explicit LocalVisitor(const UncountedLocalVarsChecker *Checker)
  130. : Checker(Checker) {
  131. assert(Checker);
  132. }
  133. bool shouldVisitTemplateInstantiations() const { return true; }
  134. bool shouldVisitImplicitCode() const { return false; }
  135. bool VisitVarDecl(VarDecl *V) {
  136. Checker->visitVarDecl(V);
  137. return true;
  138. }
  139. };
  140. LocalVisitor visitor(this);
  141. visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
  142. }
  143. void visitVarDecl(const VarDecl *V) const {
  144. if (shouldSkipVarDecl(V))
  145. return;
  146. const auto *ArgType = V->getType().getTypePtr();
  147. if (!ArgType)
  148. return;
  149. Optional<bool> IsUncountedPtr = isUncountedPtr(ArgType);
  150. if (IsUncountedPtr && *IsUncountedPtr) {
  151. const Expr *const InitExpr = V->getInit();
  152. if (!InitExpr)
  153. return; // FIXME: later on we might warn on uninitialized vars too
  154. const clang::Expr *const InitArgOrigin =
  155. tryToFindPtrOrigin(InitExpr, /*StopAtFirstRefCountedObj=*/false)
  156. .first;
  157. if (!InitArgOrigin)
  158. return;
  159. if (isa<CXXThisExpr>(InitArgOrigin))
  160. return;
  161. if (auto *Ref = llvm::dyn_cast<DeclRefExpr>(InitArgOrigin)) {
  162. if (auto *MaybeGuardian =
  163. dyn_cast_or_null<VarDecl>(Ref->getFoundDecl())) {
  164. const auto *MaybeGuardianArgType =
  165. MaybeGuardian->getType().getTypePtr();
  166. if (!MaybeGuardianArgType)
  167. return;
  168. const CXXRecordDecl *const MaybeGuardianArgCXXRecord =
  169. MaybeGuardianArgType->getAsCXXRecordDecl();
  170. if (!MaybeGuardianArgCXXRecord)
  171. return;
  172. if (MaybeGuardian->isLocalVarDecl() &&
  173. (isRefCounted(MaybeGuardianArgCXXRecord) ||
  174. isRefcountedStringsHack(MaybeGuardian)) &&
  175. isGuardedScopeEmbeddedInGuardianScope(V, MaybeGuardian)) {
  176. return;
  177. }
  178. // Parameters are guaranteed to be safe for the duration of the call
  179. // by another checker.
  180. if (isa<ParmVarDecl>(MaybeGuardian))
  181. return;
  182. }
  183. }
  184. reportBug(V);
  185. }
  186. }
  187. bool shouldSkipVarDecl(const VarDecl *V) const {
  188. assert(V);
  189. if (!V->isLocalVarDecl())
  190. return true;
  191. if (isDeclaredInForOrIf(V))
  192. return true;
  193. return false;
  194. }
  195. void reportBug(const VarDecl *V) const {
  196. assert(V);
  197. SmallString<100> Buf;
  198. llvm::raw_svector_ostream Os(Buf);
  199. Os << "Local variable ";
  200. printQuotedQualifiedName(Os, V);
  201. Os << " is uncounted and unsafe.";
  202. PathDiagnosticLocation BSLoc(V->getLocation(), BR->getSourceManager());
  203. auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
  204. Report->addRange(V->getSourceRange());
  205. BR->emitReport(std::move(Report));
  206. }
  207. };
  208. } // namespace
  209. void ento::registerUncountedLocalVarsChecker(CheckerManager &Mgr) {
  210. Mgr.registerChecker<UncountedLocalVarsChecker>();
  211. }
  212. bool ento::shouldRegisterUncountedLocalVarsChecker(const CheckerManager &) {
  213. return true;
  214. }