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/AnalysisDeclContext.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> {
34 const CheckerBase *Checker;
36 AnalysisDeclContext* AC;
38 /// Check if two expressions refer to the same declaration.
39 bool sameDecl(const Expr *A1, const Expr *A2) {
40 if (const auto *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
41 if (const auto *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
42 return D1->getDecl() == D2->getDecl();
46 /// Check if the expression E is a sizeof(WithArg).
47 bool isSizeof(const Expr *E, const Expr *WithArg) {
48 if (const auto *UE = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
49 if (UE->getKind() == UETT_SizeOf && !UE->isArgumentType())
50 return sameDecl(UE->getArgumentExpr(), WithArg);
54 /// Check if the expression E is a strlen(WithArg).
55 bool isStrlen(const Expr *E, const Expr *WithArg) {
56 if (const auto *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 bool isOne(const Expr *E) {
68 if (const auto *IL = dyn_cast<IntegerLiteral>(E))
69 return (IL->getValue().isIntN(1));
73 StringRef getPrintableName(const Expr *E) {
74 if (const auto *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);
83 /// Identify erroneous patterns in the last argument to strlcpy - the number
85 /// The bad pattern checked is when the size is known
86 /// to be larger than the destination can handle.
89 /// strlcpy(dst, "abcd", sizeof("abcd") - 1);
90 /// strlcpy(dst, "abcd", 4);
91 /// strlcpy(dst + 3, "abcd", 2);
92 /// strlcpy(dst, "abcd", cpy);
93 bool containsBadStrlcpyPattern(const CallExpr *CE);
96 WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
97 : Checker(Checker), BR(BR), AC(AC) {}
99 // Statement visitor methods.
100 void VisitChildren(Stmt *S);
101 void VisitStmt(Stmt *S) {
104 void VisitCallExpr(CallExpr *CE);
106 } // end anonymous namespace
108 // The correct size argument should look like following:
109 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
110 // We look for the following anti-patterns:
111 // - strncat(dst, src, sizeof(dst) - strlen(dst));
112 // - strncat(dst, src, sizeof(dst) - 1);
113 // - strncat(dst, src, sizeof(dst));
114 bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
115 if (CE->getNumArgs() != 3)
117 const Expr *DstArg = CE->getArg(0);
118 const Expr *SrcArg = CE->getArg(1);
119 const Expr *LenArg = CE->getArg(2);
121 // Identify wrong size expressions, which are commonly used instead.
122 if (const auto *BE = dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
123 // - sizeof(dst) - strlen(dst)
124 if (BE->getOpcode() == BO_Sub) {
125 const Expr *L = BE->getLHS();
126 const Expr *R = BE->getRHS();
127 if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
131 if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
136 if (isSizeof(LenArg, DstArg))
140 if (isSizeof(LenArg, SrcArg))
145 bool WalkAST::containsBadStrlcpyPattern(const CallExpr *CE) {
146 if (CE->getNumArgs() != 3)
148 const Expr *DstArg = CE->getArg(0);
149 const Expr *LenArg = CE->getArg(2);
151 const auto *DstArgDecl = dyn_cast<DeclRefExpr>(DstArg->IgnoreParenImpCasts());
152 const auto *LenArgDecl = dyn_cast<DeclRefExpr>(LenArg->IgnoreParenLValueCasts());
154 // - size_t dstlen = sizeof(dst)
156 const auto *LenArgVal = dyn_cast<VarDecl>(LenArgDecl->getDecl());
157 if (LenArgVal->getInit())
158 LenArg = LenArgVal->getInit();
162 // We try to figure out if the last argument is possibly longer
163 // than the destination can possibly handle if its size can be defined.
164 if (const auto *IL = dyn_cast<IntegerLiteral>(LenArg->IgnoreParenImpCasts())) {
165 uint64_t ILRawVal = IL->getValue().getZExtValue();
167 // Case when there is pointer arithmetic on the destination buffer
168 // especially when we offset from the base decreasing the
169 // buffer length accordingly.
171 if (const auto *BE = dyn_cast<BinaryOperator>(DstArg->IgnoreParenImpCasts())) {
172 DstArgDecl = dyn_cast<DeclRefExpr>(BE->getLHS()->IgnoreParenImpCasts());
173 if (BE->getOpcode() == BO_Add) {
174 if ((IL = dyn_cast<IntegerLiteral>(BE->getRHS()->IgnoreParenImpCasts()))) {
175 DstOff = IL->getValue().getZExtValue();
181 if (const auto *Buffer = dyn_cast<ConstantArrayType>(DstArgDecl->getType())) {
182 ASTContext &C = BR.getContext();
183 uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
184 if ((BufferLen - DstOff) < ILRawVal)
193 void WalkAST::VisitCallExpr(CallExpr *CE) {
194 const FunctionDecl *FD = CE->getDirectCallee();
198 if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
199 if (containsBadStrncatPattern(CE)) {
200 const Expr *DstArg = CE->getArg(0);
201 const Expr *LenArg = CE->getArg(2);
202 PathDiagnosticLocation Loc =
203 PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
205 StringRef DstName = getPrintableName(DstArg);
208 llvm::raw_svector_ostream os(S);
209 os << "Potential buffer overflow. ";
210 if (!DstName.empty()) {
211 os << "Replace with 'sizeof(" << DstName << ") "
212 "- strlen(" << DstName <<") - 1'";
216 os << "se a safer 'strlcat' API";
218 BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
219 "C String API", os.str(), Loc,
220 LenArg->getSourceRange());
222 } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy")) {
223 if (containsBadStrlcpyPattern(CE)) {
224 const Expr *DstArg = CE->getArg(0);
225 const Expr *LenArg = CE->getArg(2);
226 PathDiagnosticLocation Loc =
227 PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
229 StringRef DstName = getPrintableName(DstArg);
232 llvm::raw_svector_ostream os(S);
233 os << "The third argument is larger than the size of the input buffer. ";
234 if (!DstName.empty())
235 os << "Replace with the value 'sizeof(" << DstName << ")` or lower";
237 BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
238 "C String API", os.str(), Loc,
239 LenArg->getSourceRange());
243 // Recurse and check children.
247 void WalkAST::VisitChildren(Stmt *S) {
248 for (Stmt *Child : S->children())
254 class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
257 void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
258 BugReporter &BR) const {
259 WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
260 walker.Visit(D->getBody());
265 void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
266 mgr.registerChecker<CStringSyntaxChecker>();