blob: f1a3aacc7c4ce99b90385e79d46d279b3c1b91de [file] [log] [blame]
Anna Zakse00575f2012-01-31 19:33:39 +00001//== 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"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Anna Zakse00575f2012-01-31 19:33:39 +000027#include "llvm/Support/raw_ostream.h"
28
29using namespace clang;
30using namespace ento;
31
32namespace {
33class WalkAST: public StmtVisitor<WalkAST> {
34 BugReporter &BR;
35 AnalysisDeclContext* AC;
Anna Zakse00575f2012-01-31 19:33:39 +000036
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();
42 return false;
43 }
44
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);
51 return false;
52 }
53
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();
58 if (!FD)
59 return false;
Jordan Rosed6246072012-11-02 23:49:24 +000060 return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
61 sameDecl(CE->getArg(0), WithArg));
Anna Zakse00575f2012-01-31 19:33:39 +000062 }
63 return false;
64 }
65
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));
70 return false;
71 }
72
73 inline StringRef getPrintableName(const Expr *E) {
74 if (const DeclRefExpr *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
75 return D->getDecl()->getName();
76 return StringRef();
77 }
78
79 /// Identify erroneous patterns in the last argument to strncat - the number
80 /// of bytes to copy.
81 bool containsBadStrncatPattern(const CallExpr *CE);
82
83public:
84 WalkAST(BugReporter &br, AnalysisDeclContext* ac) :
Jordan Rosed6246072012-11-02 23:49:24 +000085 BR(br), AC(ac) {
Anna Zakse00575f2012-01-31 19:33:39 +000086 }
87
88 // Statement visitor methods.
89 void VisitChildren(Stmt *S);
90 void VisitStmt(Stmt *S) {
91 VisitChildren(S);
92 }
93 void VisitCallExpr(CallExpr *CE);
94};
95} // end anonymous namespace
96
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));
103bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
104 const Expr *DstArg = CE->getArg(0);
105 const Expr *SrcArg = CE->getArg(1);
106 const Expr *LenArg = CE->getArg(2);
107
108 // Identify wrong size expressions, which are commonly used instead.
109 if (const BinaryOperator *BE =
110 dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
111 // - sizeof(dst) - strlen(dst)
112 if (BE->getOpcode() == BO_Sub) {
113 const Expr *L = BE->getLHS();
114 const Expr *R = BE->getRHS();
115 if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
116 return true;
117
118 // - sizeof(dst) - 1
119 if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
120 return true;
121 }
122 }
123 // - sizeof(dst)
124 if (isSizeof(LenArg, DstArg))
125 return true;
126
127 // - sizeof(src)
128 if (isSizeof(LenArg, SrcArg))
129 return true;
130 return false;
131}
132
133void WalkAST::VisitCallExpr(CallExpr *CE) {
134 const FunctionDecl *FD = CE->getDirectCallee();
135 if (!FD)
136 return;
137
Jordan Rosed6246072012-11-02 23:49:24 +0000138 if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
Anna Zakse00575f2012-01-31 19:33:39 +0000139 if (containsBadStrncatPattern(CE)) {
140 const Expr *DstArg = CE->getArg(0);
141 const Expr *LenArg = CE->getArg(2);
142 SourceRange R = LenArg->getSourceRange();
143 PathDiagnosticLocation Loc =
144 PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
145
146 StringRef DstName = getPrintableName(DstArg);
147
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000148 SmallString<256> S;
Anna Zakse00575f2012-01-31 19:33:39 +0000149 llvm::raw_svector_ostream os(S);
150 os << "Potential buffer overflow. ";
151 if (!DstName.empty()) {
152 os << "Replace with 'sizeof(" << DstName << ") "
153 "- strlen(" << DstName <<") - 1'";
154 os << " or u";
155 } else
156 os << "U";
157 os << "se a safer 'strlcat' API";
158
Ted Kremenek07189522012-04-04 18:11:35 +0000159 BR.EmitBasicReport(FD, "Anti-pattern in the argument", "C String API",
Anna Zakse00575f2012-01-31 19:33:39 +0000160 os.str(), Loc, &R, 1);
161 }
162 }
163
164 // Recurse and check children.
165 VisitChildren(CE);
166}
167
168void WalkAST::VisitChildren(Stmt *S) {
169 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
170 ++I)
171 if (Stmt *child = *I)
172 Visit(child);
173}
174
175namespace {
176class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
177public:
178
179 void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
180 BugReporter &BR) const {
181 WalkAST walker(BR, Mgr.getAnalysisDeclContext(D));
182 walker.Visit(D->getBody());
183 }
184};
185}
186
187void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
188 mgr.registerChecker<CStringSyntaxChecker>();
189}
190