clang API Documentation

CStringSyntaxChecker.cpp
Go to the documentation of this file.
00001 //== CStringSyntaxChecker.cpp - CoreFoundation containers API *- C++ -*-==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // An AST checker that looks for common pitfalls when using C string APIs.
00011 //  - Identifies erroneous patterns in the last argument to strncat - the number
00012 //    of bytes to copy.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 #include "ClangSACheckers.h"
00016 #include "clang/Analysis/AnalysisContext.h"
00017 #include "clang/AST/Expr.h"
00018 #include "clang/AST/OperationKinds.h"
00019 #include "clang/AST/StmtVisitor.h"
00020 #include "clang/Basic/TargetInfo.h"
00021 #include "clang/Basic/TypeTraits.h"
00022 #include "clang/StaticAnalyzer/Core/Checker.h"
00023 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
00024 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
00025 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
00026 #include "llvm/ADT/SmallString.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 
00029 using namespace clang;
00030 using namespace ento;
00031 
00032 namespace {
00033 class WalkAST: public StmtVisitor<WalkAST> {
00034   BugReporter &BR;
00035   AnalysisDeclContext* AC;
00036   ASTContext &ASTC;
00037 
00038   /// Check if two expressions refer to the same declaration.
00039   inline bool sameDecl(const Expr *A1, const Expr *A2) {
00040     if (const DeclRefExpr *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
00041       if (const DeclRefExpr *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
00042         return D1->getDecl() == D2->getDecl();
00043     return false;
00044   }
00045 
00046   /// Check if the expression E is a sizeof(WithArg).
00047   inline bool isSizeof(const Expr *E, const Expr *WithArg) {
00048     if (const UnaryExprOrTypeTraitExpr *UE =
00049     dyn_cast<UnaryExprOrTypeTraitExpr>(E))
00050       if (UE->getKind() == UETT_SizeOf)
00051         return sameDecl(UE->getArgumentExpr(), WithArg);
00052     return false;
00053   }
00054 
00055   /// Check if the expression E is a strlen(WithArg).
00056   inline bool isStrlen(const Expr *E, const Expr *WithArg) {
00057     if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
00058       const FunctionDecl *FD = CE->getDirectCallee();
00059       if (!FD)
00060         return false;
00061       return (CheckerContext::isCLibraryFunction(FD, "strlen", ASTC)
00062           && sameDecl(CE->getArg(0), WithArg));
00063     }
00064     return false;
00065   }
00066 
00067   /// Check if the expression is an integer literal with value 1.
00068   inline bool isOne(const Expr *E) {
00069     if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
00070       return (IL->getValue().isIntN(1));
00071     return false;
00072   }
00073 
00074   inline StringRef getPrintableName(const Expr *E) {
00075     if (const DeclRefExpr *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
00076       return D->getDecl()->getName();
00077     return StringRef();
00078   }
00079 
00080   /// Identify erroneous patterns in the last argument to strncat - the number
00081   /// of bytes to copy.
00082   bool containsBadStrncatPattern(const CallExpr *CE);
00083 
00084 public:
00085   WalkAST(BugReporter &br, AnalysisDeclContext* ac) :
00086       BR(br), AC(ac), ASTC(AC->getASTContext()) {
00087   }
00088 
00089   // Statement visitor methods.
00090   void VisitChildren(Stmt *S);
00091   void VisitStmt(Stmt *S) {
00092     VisitChildren(S);
00093   }
00094   void VisitCallExpr(CallExpr *CE);
00095 };
00096 } // end anonymous namespace
00097 
00098 // The correct size argument should look like following:
00099 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
00100 // We look for the following anti-patterns:
00101 //   - strncat(dst, src, sizeof(dst) - strlen(dst));
00102 //   - strncat(dst, src, sizeof(dst) - 1);
00103 //   - strncat(dst, src, sizeof(dst));
00104 bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
00105   const Expr *DstArg = CE->getArg(0);
00106   const Expr *SrcArg = CE->getArg(1);
00107   const Expr *LenArg = CE->getArg(2);
00108 
00109   // Identify wrong size expressions, which are commonly used instead.
00110   if (const BinaryOperator *BE =
00111               dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
00112     // - sizeof(dst) - strlen(dst)
00113     if (BE->getOpcode() == BO_Sub) {
00114       const Expr *L = BE->getLHS();
00115       const Expr *R = BE->getRHS();
00116       if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
00117         return true;
00118 
00119       // - sizeof(dst) - 1
00120       if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
00121         return true;
00122     }
00123   }
00124   // - sizeof(dst)
00125   if (isSizeof(LenArg, DstArg))
00126     return true;
00127 
00128   // - sizeof(src)
00129   if (isSizeof(LenArg, SrcArg))
00130     return true;
00131   return false;
00132 }
00133 
00134 void WalkAST::VisitCallExpr(CallExpr *CE) {
00135   const FunctionDecl *FD = CE->getDirectCallee();
00136   if (!FD)
00137     return;
00138 
00139   if (CheckerContext::isCLibraryFunction(FD, "strncat", ASTC)) {
00140     if (containsBadStrncatPattern(CE)) {
00141       const Expr *DstArg = CE->getArg(0);
00142       const Expr *LenArg = CE->getArg(2);
00143       SourceRange R = LenArg->getSourceRange();
00144       PathDiagnosticLocation Loc =
00145         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
00146 
00147       StringRef DstName = getPrintableName(DstArg);
00148 
00149       SmallString<256> S;
00150       llvm::raw_svector_ostream os(S);
00151       os << "Potential buffer overflow. ";
00152       if (!DstName.empty()) {
00153         os << "Replace with 'sizeof(" << DstName << ") "
00154               "- strlen(" << DstName <<") - 1'";
00155         os << " or u";
00156       } else
00157         os << "U";
00158       os << "se a safer 'strlcat' API";
00159 
00160       BR.EmitBasicReport(FD, "Anti-pattern in the argument", "C String API",
00161                          os.str(), Loc, &R, 1);
00162     }
00163   }
00164 
00165   // Recurse and check children.
00166   VisitChildren(CE);
00167 }
00168 
00169 void WalkAST::VisitChildren(Stmt *S) {
00170   for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
00171       ++I)
00172     if (Stmt *child = *I)
00173       Visit(child);
00174 }
00175 
00176 namespace {
00177 class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
00178 public:
00179 
00180   void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
00181       BugReporter &BR) const {
00182     WalkAST walker(BR, Mgr.getAnalysisDeclContext(D));
00183     walker.Visit(D->getBody());
00184   }
00185 };
00186 }
00187 
00188 void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
00189   mgr.registerChecker<CStringSyntaxChecker>();
00190 }
00191