blob: abfb971d4ccc6608c4f7d726eff6ffd95eb34388 [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"
Anna Zakse00575f2012-01-31 19:33:39 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/OperationKinds.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/Analysis/AnalysisContext.h"
Anna Zakse00575f2012-01-31 19:33:39 +000020#include "clang/Basic/TargetInfo.h"
21#include "clang/Basic/TypeTraits.h"
Anna Zakse00575f2012-01-31 19:33:39 +000022#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/StaticAnalyzer/Core/Checker.h"
Anna Zakse00575f2012-01-31 19:33:39 +000024#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> {
Stephen Hines651f13c2014-04-23 16:59:28 -070034 const CheckerBase *Checker;
Anna Zakse00575f2012-01-31 19:33:39 +000035 BugReporter &BR;
36 AnalysisDeclContext* AC;
Anna Zakse00575f2012-01-31 19:33:39 +000037
38 /// Check if two expressions refer to the same declaration.
39 inline bool sameDecl(const Expr *A1, const Expr *A2) {
40 if (const DeclRefExpr *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
41 if (const DeclRefExpr *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
42 return D1->getDecl() == D2->getDecl();
43 return false;
44 }
45
46 /// Check if the expression E is a sizeof(WithArg).
47 inline bool isSizeof(const Expr *E, const Expr *WithArg) {
48 if (const UnaryExprOrTypeTraitExpr *UE =
49 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
50 if (UE->getKind() == UETT_SizeOf)
51 return sameDecl(UE->getArgumentExpr(), WithArg);
52 return false;
53 }
54
55 /// Check if the expression E is a strlen(WithArg).
56 inline bool isStrlen(const Expr *E, const Expr *WithArg) {
57 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
58 const FunctionDecl *FD = CE->getDirectCallee();
59 if (!FD)
60 return false;
Jordan Rosed6246072012-11-02 23:49:24 +000061 return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
62 sameDecl(CE->getArg(0), WithArg));
Anna Zakse00575f2012-01-31 19:33:39 +000063 }
64 return false;
65 }
66
67 /// Check if the expression is an integer literal with value 1.
68 inline bool isOne(const Expr *E) {
69 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
70 return (IL->getValue().isIntN(1));
71 return false;
72 }
73
74 inline StringRef getPrintableName(const Expr *E) {
75 if (const DeclRefExpr *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
76 return D->getDecl()->getName();
77 return StringRef();
78 }
79
80 /// Identify erroneous patterns in the last argument to strncat - the number
81 /// of bytes to copy.
82 bool containsBadStrncatPattern(const CallExpr *CE);
83
84public:
Stephen Hines651f13c2014-04-23 16:59:28 -070085 WalkAST(const CheckerBase *checker, BugReporter &br, AnalysisDeclContext *ac)
86 : Checker(checker), BR(br), AC(ac) {}
Anna Zakse00575f2012-01-31 19:33:39 +000087
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) {
Anna Zaksfececcb2013-04-10 22:06:29 +0000104 if (CE->getNumArgs() != 3)
105 return false;
Anna Zakse00575f2012-01-31 19:33:39 +0000106 const Expr *DstArg = CE->getArg(0);
107 const Expr *SrcArg = CE->getArg(1);
108 const Expr *LenArg = CE->getArg(2);
109
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))
118 return true;
119
120 // - sizeof(dst) - 1
121 if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
122 return true;
123 }
124 }
125 // - sizeof(dst)
126 if (isSizeof(LenArg, DstArg))
127 return true;
128
129 // - sizeof(src)
130 if (isSizeof(LenArg, SrcArg))
131 return true;
132 return false;
133}
134
135void WalkAST::VisitCallExpr(CallExpr *CE) {
136 const FunctionDecl *FD = CE->getDirectCallee();
137 if (!FD)
138 return;
139
Jordan Rosed6246072012-11-02 23:49:24 +0000140 if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
Anna Zakse00575f2012-01-31 19:33:39 +0000141 if (containsBadStrncatPattern(CE)) {
142 const Expr *DstArg = CE->getArg(0);
143 const Expr *LenArg = CE->getArg(2);
Anna Zakse00575f2012-01-31 19:33:39 +0000144 PathDiagnosticLocation Loc =
145 PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
146
147 StringRef DstName = getPrintableName(DstArg);
148
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000149 SmallString<256> S;
Anna Zakse00575f2012-01-31 19:33:39 +0000150 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'";
155 os << " or u";
156 } else
157 os << "U";
158 os << "se a safer 'strlcat' API";
159
Stephen Hines651f13c2014-04-23 16:59:28 -0700160 BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
161 "C String API", os.str(), Loc,
162 LenArg->getSourceRange());
Anna Zakse00575f2012-01-31 19:33:39 +0000163 }
164 }
165
166 // Recurse and check children.
167 VisitChildren(CE);
168}
169
170void WalkAST::VisitChildren(Stmt *S) {
171 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
172 ++I)
173 if (Stmt *child = *I)
174 Visit(child);
175}
176
177namespace {
178class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
179public:
180
181 void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
182 BugReporter &BR) const {
Stephen Hines651f13c2014-04-23 16:59:28 -0700183 WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
Anna Zakse00575f2012-01-31 19:33:39 +0000184 walker.Visit(D->getBody());
185 }
186};
187}
188
189void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
190 mgr.registerChecker<CStringSyntaxChecker>();
191}
192