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/AST/Expr.h"
00017 #include "clang/AST/OperationKinds.h"
00018 #include "clang/AST/StmtVisitor.h"
00019 #include "clang/Analysis/AnalysisContext.h"
00020 #include "clang/Basic/TargetInfo.h"
00021 #include "clang/Basic/TypeTraits.h"
00022 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
00023 #include "clang/StaticAnalyzer/Core/Checker.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   const CheckerBase *Checker;
00035   BugReporter &BR;
00036   AnalysisDeclContext* AC;
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") &&
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(const CheckerBase *checker, BugReporter &br, AnalysisDeclContext *ac)
00086       : Checker(checker), BR(br), AC(ac) {}
00087 
00088   // Statement visitor methods.
00089   void VisitChildren(Stmt *S);
00090   void VisitStmt(Stmt *S) {
00091     VisitChildren(S);
00092   }
00093   void VisitCallExpr(CallExpr *CE);
00094 };
00095 } // end anonymous namespace
00096 
00097 // The correct size argument should look like following:
00098 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
00099 // We look for the following anti-patterns:
00100 //   - strncat(dst, src, sizeof(dst) - strlen(dst));
00101 //   - strncat(dst, src, sizeof(dst) - 1);
00102 //   - strncat(dst, src, sizeof(dst));
00103 bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
00104   if (CE->getNumArgs() != 3)
00105     return false;
00106   const Expr *DstArg = CE->getArg(0);
00107   const Expr *SrcArg = CE->getArg(1);
00108   const Expr *LenArg = CE->getArg(2);
00109 
00110   // Identify wrong size expressions, which are commonly used instead.
00111   if (const BinaryOperator *BE =
00112               dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
00113     // - sizeof(dst) - strlen(dst)
00114     if (BE->getOpcode() == BO_Sub) {
00115       const Expr *L = BE->getLHS();
00116       const Expr *R = BE->getRHS();
00117       if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
00118         return true;
00119 
00120       // - sizeof(dst) - 1
00121       if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
00122         return true;
00123     }
00124   }
00125   // - sizeof(dst)
00126   if (isSizeof(LenArg, DstArg))
00127     return true;
00128 
00129   // - sizeof(src)
00130   if (isSizeof(LenArg, SrcArg))
00131     return true;
00132   return false;
00133 }
00134 
00135 void WalkAST::VisitCallExpr(CallExpr *CE) {
00136   const FunctionDecl *FD = CE->getDirectCallee();
00137   if (!FD)
00138     return;
00139 
00140   if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
00141     if (containsBadStrncatPattern(CE)) {
00142       const Expr *DstArg = CE->getArg(0);
00143       const Expr *LenArg = CE->getArg(2);
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, Checker, "Anti-pattern in the argument",
00161                          "C String API", os.str(), Loc,
00162                          LenArg->getSourceRange());
00163     }
00164   }
00165 
00166   // Recurse and check children.
00167   VisitChildren(CE);
00168 }
00169 
00170 void WalkAST::VisitChildren(Stmt *S) {
00171   for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
00172       ++I)
00173     if (Stmt *child = *I)
00174       Visit(child);
00175 }
00176 
00177 namespace {
00178 class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
00179 public:
00180 
00181   void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
00182       BugReporter &BR) const {
00183     WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
00184     walker.Visit(D->getBody());
00185   }
00186 };
00187 }
00188 
00189 void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
00190   mgr.registerChecker<CStringSyntaxChecker>();
00191 }
00192