CStringSyntaxChecker.cpp 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. //== CStringSyntaxChecker.cpp - CoreFoundation containers API *- 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. // An AST checker that looks for common pitfalls when using C string APIs.
  11. // - Identifies erroneous patterns in the last argument to strncat - the number
  12. // of bytes to copy.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "ClangSACheckers.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/OperationKinds.h"
  18. #include "clang/AST/StmtVisitor.h"
  19. #include "clang/Analysis/AnalysisContext.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/Basic/TypeTraits.h"
  22. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  23. #include "clang/StaticAnalyzer/Core/Checker.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  26. #include "llvm/ADT/SmallString.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. using namespace clang;
  29. using namespace ento;
  30. namespace {
  31. class WalkAST: public StmtVisitor<WalkAST> {
  32. const CheckerBase *Checker;
  33. BugReporter &BR;
  34. AnalysisDeclContext* AC;
  35. /// Check if two expressions refer to the same declaration.
  36. inline bool sameDecl(const Expr *A1, const Expr *A2) {
  37. if (const DeclRefExpr *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
  38. if (const DeclRefExpr *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
  39. return D1->getDecl() == D2->getDecl();
  40. return false;
  41. }
  42. /// Check if the expression E is a sizeof(WithArg).
  43. inline bool isSizeof(const Expr *E, const Expr *WithArg) {
  44. if (const UnaryExprOrTypeTraitExpr *UE =
  45. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  46. if (UE->getKind() == UETT_SizeOf)
  47. return sameDecl(UE->getArgumentExpr(), WithArg);
  48. return false;
  49. }
  50. /// Check if the expression E is a strlen(WithArg).
  51. inline bool isStrlen(const Expr *E, const Expr *WithArg) {
  52. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  53. const FunctionDecl *FD = CE->getDirectCallee();
  54. if (!FD)
  55. return false;
  56. return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
  57. sameDecl(CE->getArg(0), WithArg));
  58. }
  59. return false;
  60. }
  61. /// Check if the expression is an integer literal with value 1.
  62. inline bool isOne(const Expr *E) {
  63. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
  64. return (IL->getValue().isIntN(1));
  65. return false;
  66. }
  67. inline StringRef getPrintableName(const Expr *E) {
  68. if (const DeclRefExpr *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  69. return D->getDecl()->getName();
  70. return StringRef();
  71. }
  72. /// Identify erroneous patterns in the last argument to strncat - the number
  73. /// of bytes to copy.
  74. bool containsBadStrncatPattern(const CallExpr *CE);
  75. public:
  76. WalkAST(const CheckerBase *checker, BugReporter &br, AnalysisDeclContext *ac)
  77. : Checker(checker), BR(br), AC(ac) {}
  78. // Statement visitor methods.
  79. void VisitChildren(Stmt *S);
  80. void VisitStmt(Stmt *S) {
  81. VisitChildren(S);
  82. }
  83. void VisitCallExpr(CallExpr *CE);
  84. };
  85. } // end anonymous namespace
  86. // The correct size argument should look like following:
  87. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  88. // We look for the following anti-patterns:
  89. // - strncat(dst, src, sizeof(dst) - strlen(dst));
  90. // - strncat(dst, src, sizeof(dst) - 1);
  91. // - strncat(dst, src, sizeof(dst));
  92. bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
  93. if (CE->getNumArgs() != 3)
  94. return false;
  95. const Expr *DstArg = CE->getArg(0);
  96. const Expr *SrcArg = CE->getArg(1);
  97. const Expr *LenArg = CE->getArg(2);
  98. // Identify wrong size expressions, which are commonly used instead.
  99. if (const BinaryOperator *BE =
  100. dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
  101. // - sizeof(dst) - strlen(dst)
  102. if (BE->getOpcode() == BO_Sub) {
  103. const Expr *L = BE->getLHS();
  104. const Expr *R = BE->getRHS();
  105. if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
  106. return true;
  107. // - sizeof(dst) - 1
  108. if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
  109. return true;
  110. }
  111. }
  112. // - sizeof(dst)
  113. if (isSizeof(LenArg, DstArg))
  114. return true;
  115. // - sizeof(src)
  116. if (isSizeof(LenArg, SrcArg))
  117. return true;
  118. return false;
  119. }
  120. void WalkAST::VisitCallExpr(CallExpr *CE) {
  121. const FunctionDecl *FD = CE->getDirectCallee();
  122. if (!FD)
  123. return;
  124. if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
  125. if (containsBadStrncatPattern(CE)) {
  126. const Expr *DstArg = CE->getArg(0);
  127. const Expr *LenArg = CE->getArg(2);
  128. PathDiagnosticLocation Loc =
  129. PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
  130. StringRef DstName = getPrintableName(DstArg);
  131. SmallString<256> S;
  132. llvm::raw_svector_ostream os(S);
  133. os << "Potential buffer overflow. ";
  134. if (!DstName.empty()) {
  135. os << "Replace with 'sizeof(" << DstName << ") "
  136. "- strlen(" << DstName <<") - 1'";
  137. os << " or u";
  138. } else
  139. os << "U";
  140. os << "se a safer 'strlcat' API";
  141. BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
  142. "C String API", os.str(), Loc,
  143. LenArg->getSourceRange());
  144. }
  145. }
  146. // Recurse and check children.
  147. VisitChildren(CE);
  148. }
  149. void WalkAST::VisitChildren(Stmt *S) {
  150. for (Stmt *Child : S->children())
  151. if (Child)
  152. Visit(Child);
  153. }
  154. namespace {
  155. class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
  156. public:
  157. void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
  158. BugReporter &BR) const {
  159. WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
  160. walker.Visit(D->getBody());
  161. }
  162. };
  163. }
  164. void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
  165. mgr.registerChecker<CStringSyntaxChecker>();
  166. }