clang 20.0.0git
CStringSyntaxChecker.cpp
Go to the documentation of this file.
1//== CStringSyntaxChecker.cpp - CoreFoundation containers API *- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// An AST checker that looks for common pitfalls when using C string APIs.
10// - Identifies erroneous patterns in the last argument to strncat - the number
11// of bytes to copy.
12//
13//===----------------------------------------------------------------------===//
15#include "clang/AST/Expr.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/Support/raw_ostream.h"
27
28using namespace clang;
29using namespace ento;
30
31namespace {
32class WalkAST: public StmtVisitor<WalkAST> {
33 const CheckerBase *Checker;
34 BugReporter &BR;
36
37 /// Check if two expressions refer to the same declaration.
38 bool sameDecl(const Expr *A1, const Expr *A2) {
39 if (const auto *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
40 if (const auto *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 bool isSizeof(const Expr *E, const Expr *WithArg) {
47 if (const auto *UE = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
48 if (UE->getKind() == UETT_SizeOf && !UE->isArgumentType())
49 return sameDecl(UE->getArgumentExpr(), WithArg);
50 return false;
51 }
52
53 /// Check if the expression E is a strlen(WithArg).
54 bool isStrlen(const Expr *E, const Expr *WithArg) {
55 if (const auto *CE = dyn_cast<CallExpr>(E)) {
56 const FunctionDecl *FD = CE->getDirectCallee();
57 if (!FD)
58 return false;
59 return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
60 sameDecl(CE->getArg(0), WithArg));
61 }
62 return false;
63 }
64
65 /// Check if the expression is an integer literal with value 1.
66 bool isOne(const Expr *E) {
67 if (const auto *IL = dyn_cast<IntegerLiteral>(E))
68 return (IL->getValue().isIntN(1));
69 return false;
70 }
71
72 StringRef getPrintableName(const Expr *E) {
73 if (const auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
74 return D->getDecl()->getName();
75 return StringRef();
76 }
77
78 /// Identify erroneous patterns in the last argument to strncat - the number
79 /// of bytes to copy.
80 bool containsBadStrncatPattern(const CallExpr *CE);
81
82 /// Identify erroneous patterns in the last argument to strlcpy - the number
83 /// of bytes to copy.
84 /// The bad pattern checked is when the size is known
85 /// to be larger than the destination can handle.
86 /// char dst[2];
87 /// size_t cpy = 4;
88 /// strlcpy(dst, "abcd", sizeof("abcd") - 1);
89 /// strlcpy(dst, "abcd", 4);
90 /// strlcpy(dst + 3, "abcd", 2);
91 /// strlcpy(dst, "abcd", cpy);
92 /// Identify erroneous patterns in the last argument to strlcat - the number
93 /// of bytes to copy.
94 /// The bad pattern checked is when the last argument is basically
95 /// pointing to the destination buffer size or argument larger or
96 /// equal to.
97 /// char dst[2];
98 /// strlcat(dst, src2, sizeof(dst));
99 /// strlcat(dst, src2, 2);
100 /// strlcat(dst, src2, 10);
101 bool containsBadStrlcpyStrlcatPattern(const CallExpr *CE);
102
103public:
104 WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
105 : Checker(Checker), BR(BR), AC(AC) {}
106
107 // Statement visitor methods.
108 void VisitChildren(Stmt *S);
109 void VisitStmt(Stmt *S) {
110 VisitChildren(S);
111 }
112 void VisitCallExpr(CallExpr *CE);
113};
114} // end anonymous namespace
115
116// The correct size argument should look like following:
117// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
118// We look for the following anti-patterns:
119// - strncat(dst, src, sizeof(dst) - strlen(dst));
120// - strncat(dst, src, sizeof(dst) - 1);
121// - strncat(dst, src, sizeof(dst));
122bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
123 if (CE->getNumArgs() != 3)
124 return false;
125 const Expr *DstArg = CE->getArg(0);
126 const Expr *SrcArg = CE->getArg(1);
127 const Expr *LenArg = CE->getArg(2);
128
129 // Identify wrong size expressions, which are commonly used instead.
130 if (const auto *BE = dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
131 // - sizeof(dst) - strlen(dst)
132 if (BE->getOpcode() == BO_Sub) {
133 const Expr *L = BE->getLHS();
134 const Expr *R = BE->getRHS();
135 if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
136 return true;
137
138 // - sizeof(dst) - 1
139 if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
140 return true;
141 }
142 }
143 // - sizeof(dst)
144 if (isSizeof(LenArg, DstArg))
145 return true;
146
147 // - sizeof(src)
148 if (isSizeof(LenArg, SrcArg))
149 return true;
150 return false;
151}
152
153bool WalkAST::containsBadStrlcpyStrlcatPattern(const CallExpr *CE) {
154 if (CE->getNumArgs() != 3)
155 return false;
156 const Expr *DstArg = CE->getArg(0);
157 const Expr *LenArg = CE->getArg(2);
158
159 const auto *DstArgDRE = dyn_cast<DeclRefExpr>(DstArg->IgnoreParenImpCasts());
160 const auto *LenArgDRE =
161 dyn_cast<DeclRefExpr>(LenArg->IgnoreParenLValueCasts());
162 uint64_t DstOff = 0;
163 if (isSizeof(LenArg, DstArg))
164 return false;
165
166 // - size_t dstlen = sizeof(dst)
167 if (LenArgDRE) {
168 const auto *LenArgVal = dyn_cast<VarDecl>(LenArgDRE->getDecl());
169 // If it's an EnumConstantDecl instead, then we're missing out on something.
170 if (!LenArgVal) {
171 assert(isa<EnumConstantDecl>(LenArgDRE->getDecl()));
172 return false;
173 }
174 if (LenArgVal->getInit())
175 LenArg = LenArgVal->getInit();
176 }
177
178 // - integral value
179 // We try to figure out if the last argument is possibly longer
180 // than the destination can possibly handle if its size can be defined.
181 if (const auto *IL = dyn_cast<IntegerLiteral>(LenArg->IgnoreParenImpCasts())) {
182 uint64_t ILRawVal = IL->getValue().getZExtValue();
183
184 // Case when there is pointer arithmetic on the destination buffer
185 // especially when we offset from the base decreasing the
186 // buffer length accordingly.
187 if (!DstArgDRE) {
188 if (const auto *BE =
189 dyn_cast<BinaryOperator>(DstArg->IgnoreParenImpCasts())) {
190 DstArgDRE = dyn_cast<DeclRefExpr>(BE->getLHS()->IgnoreParenImpCasts());
191 if (BE->getOpcode() == BO_Add) {
192 if ((IL = dyn_cast<IntegerLiteral>(BE->getRHS()->IgnoreParenImpCasts()))) {
193 DstOff = IL->getValue().getZExtValue();
194 }
195 }
196 }
197 }
198 if (DstArgDRE) {
199 if (const auto *Buffer =
200 dyn_cast<ConstantArrayType>(DstArgDRE->getType())) {
201 ASTContext &C = BR.getContext();
202 uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
203 auto RemainingBufferLen = BufferLen - DstOff;
204 if (RemainingBufferLen < ILRawVal)
205 return true;
206 }
207 }
208 }
209
210 return false;
211}
212
213void WalkAST::VisitCallExpr(CallExpr *CE) {
214 const FunctionDecl *FD = CE->getDirectCallee();
215 if (!FD)
216 return;
217
218 if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
219 if (containsBadStrncatPattern(CE)) {
220 const Expr *DstArg = CE->getArg(0);
221 const Expr *LenArg = CE->getArg(2);
224
225 StringRef DstName = getPrintableName(DstArg);
226
228 llvm::raw_svector_ostream os(S);
229 os << "Potential buffer overflow. ";
230 if (!DstName.empty()) {
231 os << "Replace with 'sizeof(" << DstName << ") "
232 "- strlen(" << DstName <<") - 1'";
233 os << " or u";
234 } else
235 os << "U";
236 os << "se a safer 'strlcat' API";
237
238 BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
239 "C String API", os.str(), Loc,
240 LenArg->getSourceRange());
241 }
242 } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy") ||
243 CheckerContext::isCLibraryFunction(FD, "strlcat")) {
244 if (containsBadStrlcpyStrlcatPattern(CE)) {
245 const Expr *DstArg = CE->getArg(0);
246 const Expr *LenArg = CE->getArg(2);
249
250 StringRef DstName = getPrintableName(DstArg);
251
253 llvm::raw_svector_ostream os(S);
254 os << "The third argument allows to potentially copy more bytes than it should. ";
255 os << "Replace with the value ";
256 if (!DstName.empty())
257 os << "sizeof(" << DstName << ")";
258 else
259 os << "sizeof(<destination buffer>)";
260 os << " or lower";
261
262 BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
263 "C String API", os.str(), Loc,
264 LenArg->getSourceRange());
265 }
266 }
267
268 // Recurse and check children.
269 VisitChildren(CE);
270}
271
272void WalkAST::VisitChildren(Stmt *S) {
273 for (Stmt *Child : S->children())
274 if (Child)
275 Visit(Child);
276}
277
278namespace {
279class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
280public:
281
282 void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
283 BugReporter &BR) const {
284 WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
285 walker.Visit(D->getBody());
286 }
287};
288}
289
290void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
291 mgr.registerChecker<CStringSyntaxChecker>();
292}
293
294bool ento::shouldRegisterCStringSyntaxChecker(const CheckerManager &mgr) {
295 return true;
296}
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
const Decl * D
Expr * E
Defines enumerations for the type traits support.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
AnalysisDeclContext contains the context data for the function, method or block under analysis.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3021
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3008
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1077
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3075
Expr * IgnoreParenLValueCasts() LLVM_READONLY
Skip past any parentheses and lvalue casts which might surround this expression until reaching a fixe...
Definition: Expr.cpp:3087
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Represents a function declaration or definition.
Definition: Decl.h:1932
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:585
const SourceManager & getSourceManager()
Definition: BugReporter.h:623
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges=std::nullopt, ArrayRef< FixItHint > Fixits=std::nullopt)
ASTContext & getContext()
Definition: BugReporter.h:621
static bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name=StringRef())
Returns true if the given function is an externally-visible function in the top-level namespace,...
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
unsigned long uint64_t