1 //== CStringSyntaxChecker.cpp - CoreFoundation containers API *- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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"
29 using namespace clang;
33 class WalkAST: public StmtVisitor<WalkAST> {
35 AnalysisDeclContext* AC;
37 /// Check if two expressions refer to the same declaration.
38 inline bool sameDecl(const Expr *A1, const Expr *A2) {
39 if (const DeclRefExpr *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
40 if (const DeclRefExpr *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
41 return D1->getDecl() == D2->getDecl();
45 /// Check if the expression E is a sizeof(WithArg).
46 inline bool isSizeof(const Expr *E, const Expr *WithArg) {
47 if (const UnaryExprOrTypeTraitExpr *UE =
48 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
49 if (UE->getKind() == UETT_SizeOf)
50 return sameDecl(UE->getArgumentExpr(), WithArg);
54 /// Check if the expression E is a strlen(WithArg).
55 inline bool isStrlen(const Expr *E, const Expr *WithArg) {
56 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
57 const FunctionDecl *FD = CE->getDirectCallee();
60 return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
61 sameDecl(CE->getArg(0), WithArg));
66 /// Check if the expression is an integer literal with value 1.
67 inline bool isOne(const Expr *E) {
68 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
69 return (IL->getValue().isIntN(1));
73 inline StringRef getPrintableName(const Expr *E) {
74 if (const DeclRefExpr *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
75 return D->getDecl()->getName();
79 /// Identify erroneous patterns in the last argument to strncat - the number
81 bool containsBadStrncatPattern(const CallExpr *CE);
84 WalkAST(BugReporter &br, AnalysisDeclContext* ac) :
88 // Statement visitor methods.
89 void VisitChildren(Stmt *S);
90 void VisitStmt(Stmt *S) {
93 void VisitCallExpr(CallExpr *CE);
95 } // end anonymous namespace
97 // The correct size argument should look like following:
98 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
99 // We look for the following anti-patterns:
100 // - strncat(dst, src, sizeof(dst) - strlen(dst));
101 // - strncat(dst, src, sizeof(dst) - 1);
102 // - strncat(dst, src, sizeof(dst));
103 bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
104 if (CE->getNumArgs() != 3)
106 const Expr *DstArg = CE->getArg(0);
107 const Expr *SrcArg = CE->getArg(1);
108 const Expr *LenArg = CE->getArg(2);
110 // Identify wrong size expressions, which are commonly used instead.
111 if (const BinaryOperator *BE =
112 dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
113 // - sizeof(dst) - strlen(dst)
114 if (BE->getOpcode() == BO_Sub) {
115 const Expr *L = BE->getLHS();
116 const Expr *R = BE->getRHS();
117 if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
121 if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
126 if (isSizeof(LenArg, DstArg))
130 if (isSizeof(LenArg, SrcArg))
135 void WalkAST::VisitCallExpr(CallExpr *CE) {
136 const FunctionDecl *FD = CE->getDirectCallee();
140 if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
141 if (containsBadStrncatPattern(CE)) {
142 const Expr *DstArg = CE->getArg(0);
143 const Expr *LenArg = CE->getArg(2);
144 PathDiagnosticLocation Loc =
145 PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
147 StringRef DstName = getPrintableName(DstArg);
150 llvm::raw_svector_ostream os(S);
151 os << "Potential buffer overflow. ";
152 if (!DstName.empty()) {
153 os << "Replace with 'sizeof(" << DstName << ") "
154 "- strlen(" << DstName <<") - 1'";
158 os << "se a safer 'strlcat' API";
160 BR.EmitBasicReport(FD, "Anti-pattern in the argument", "C String API",
161 os.str(), Loc, LenArg->getSourceRange());
165 // Recurse and check children.
169 void WalkAST::VisitChildren(Stmt *S) {
170 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
172 if (Stmt *child = *I)
177 class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
180 void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
181 BugReporter &BR) const {
182 WalkAST walker(BR, Mgr.getAnalysisDeclContext(D));
183 walker.Visit(D->getBody());
188 void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
189 mgr.registerChecker<CStringSyntaxChecker>();