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/Analysis/AnalysisContext.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/OperationKinds.h"
  19. #include "clang/AST/StmtVisitor.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/Basic/TypeTraits.h"
  22. #include "clang/StaticAnalyzer/Core/Checker.h"
  23. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.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. BugReporter &BR;
  33. AnalysisDeclContext* AC;
  34. ASTContext &ASTC;
  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", ASTC)
  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(BugReporter &br, AnalysisDeclContext* ac) :
  77. BR(br), AC(ac), ASTC(AC->getASTContext()) {
  78. }
  79. // Statement visitor methods.
  80. void VisitChildren(Stmt *S);
  81. void VisitStmt(Stmt *S) {
  82. VisitChildren(S);
  83. }
  84. void VisitCallExpr(CallExpr *CE);
  85. };
  86. } // end anonymous namespace
  87. // The correct size argument should look like following:
  88. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  89. // We look for the following anti-patterns:
  90. // - strncat(dst, src, sizeof(dst) - strlen(dst));
  91. // - strncat(dst, src, sizeof(dst) - 1);
  92. // - strncat(dst, src, sizeof(dst));
  93. bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
  94. const Expr *DstArg = CE->getArg(0);
  95. const Expr *SrcArg = CE->getArg(1);
  96. const Expr *LenArg = CE->getArg(2);
  97. // Identify wrong size expressions, which are commonly used instead.
  98. if (const BinaryOperator *BE =
  99. dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
  100. // - sizeof(dst) - strlen(dst)
  101. if (BE->getOpcode() == BO_Sub) {
  102. const Expr *L = BE->getLHS();
  103. const Expr *R = BE->getRHS();
  104. if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
  105. return true;
  106. // - sizeof(dst) - 1
  107. if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
  108. return true;
  109. }
  110. }
  111. // - sizeof(dst)
  112. if (isSizeof(LenArg, DstArg))
  113. return true;
  114. // - sizeof(src)
  115. if (isSizeof(LenArg, SrcArg))
  116. return true;
  117. return false;
  118. }
  119. void WalkAST::VisitCallExpr(CallExpr *CE) {
  120. const FunctionDecl *FD = CE->getDirectCallee();
  121. if (!FD)
  122. return;
  123. if (CheckerContext::isCLibraryFunction(FD, "strncat", ASTC)) {
  124. if (containsBadStrncatPattern(CE)) {
  125. const Expr *DstArg = CE->getArg(0);
  126. const Expr *LenArg = CE->getArg(2);
  127. SourceRange R = LenArg->getSourceRange();
  128. PathDiagnosticLocation Loc =
  129. PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
  130. StringRef DstName = getPrintableName(DstArg);
  131. llvm::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("Anti-pattern in the argument", "C String API",
  142. os.str(), Loc, &R, 1);
  143. }
  144. }
  145. // Recurse and check children.
  146. VisitChildren(CE);
  147. }
  148. void WalkAST::VisitChildren(Stmt *S) {
  149. for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
  150. ++I)
  151. if (Stmt *child = *I)
  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(BR, Mgr.getAnalysisDeclContext(D));
  160. walker.Visit(D->getBody());
  161. }
  162. };
  163. }
  164. void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
  165. mgr.registerChecker<CStringSyntaxChecker>();
  166. }