xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp (revision c30cedfcc0f96390a10816fec3d7c8e6d1dc2b86)
1 //== 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/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"
28 
29 using namespace clang;
30 using namespace ento;
31 
32 namespace {
33 class WalkAST: public StmtVisitor<WalkAST> {
34   const CheckerBase *Checker;
35   BugReporter &BR;
36   AnalysisDeclContext* AC;
37 
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();
43     return false;
44   }
45 
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);
51     return false;
52   }
53 
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();
58       if (!FD)
59         return false;
60       return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
61               sameDecl(CE->getArg(0), WithArg));
62     }
63     return false;
64   }
65 
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));
70     return false;
71   }
72 
73   StringRef getPrintableName(const Expr *E) {
74     if (const auto *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 
83   /// Identify erroneous patterns in the last argument to strlcpy - the number
84   /// of bytes to copy.
85   /// The bad pattern checked is when the size is known
86   /// to be larger than the destination can handle.
87   ///   char dst[2];
88   ///   size_t cpy = 4;
89   ///   strlcpy(dst, "abcd", sizeof("abcd") - 1);
90   ///   strlcpy(dst, "abcd", 4);
91   ///   strlcpy(dst, "abcd", cpy);
92   bool containsBadStrlcpyPattern(const CallExpr *CE);
93 
94 public:
95   WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
96       : Checker(Checker), BR(BR), AC(AC) {}
97 
98   // Statement visitor methods.
99   void VisitChildren(Stmt *S);
100   void VisitStmt(Stmt *S) {
101     VisitChildren(S);
102   }
103   void VisitCallExpr(CallExpr *CE);
104 };
105 } // end anonymous namespace
106 
107 // The correct size argument should look like following:
108 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
109 // We look for the following anti-patterns:
110 //   - strncat(dst, src, sizeof(dst) - strlen(dst));
111 //   - strncat(dst, src, sizeof(dst) - 1);
112 //   - strncat(dst, src, sizeof(dst));
113 bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
114   if (CE->getNumArgs() != 3)
115     return false;
116   const Expr *DstArg = CE->getArg(0);
117   const Expr *SrcArg = CE->getArg(1);
118   const Expr *LenArg = CE->getArg(2);
119 
120   // Identify wrong size expressions, which are commonly used instead.
121   if (const auto *BE = dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
122     // - sizeof(dst) - strlen(dst)
123     if (BE->getOpcode() == BO_Sub) {
124       const Expr *L = BE->getLHS();
125       const Expr *R = BE->getRHS();
126       if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
127         return true;
128 
129       // - sizeof(dst) - 1
130       if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
131         return true;
132     }
133   }
134   // - sizeof(dst)
135   if (isSizeof(LenArg, DstArg))
136     return true;
137 
138   // - sizeof(src)
139   if (isSizeof(LenArg, SrcArg))
140     return true;
141   return false;
142 }
143 
144 bool WalkAST::containsBadStrlcpyPattern(const CallExpr *CE) {
145   if (CE->getNumArgs() != 3)
146     return false;
147   const Expr *DstArg = CE->getArg(0);
148   const Expr *LenArg = CE->getArg(2);
149 
150   const auto *DstArgDecl = dyn_cast<DeclRefExpr>(DstArg->IgnoreParenImpCasts());
151   const auto *LenArgDecl = dyn_cast<DeclRefExpr>(LenArg->IgnoreParenLValueCasts());
152   // - size_t dstlen = sizeof(dst)
153   if (LenArgDecl) {
154     const auto *LenArgVal = dyn_cast<VarDecl>(LenArgDecl->getDecl());
155     if (LenArgVal->getInit())
156       LenArg = LenArgVal->getInit();
157   }
158 
159   // - integral value
160   // We try to figure out if the last argument is possibly longer
161   // than the destination can possibly handle if its size can be defined
162   if (const auto *IL = dyn_cast<IntegerLiteral>(LenArg->IgnoreParenImpCasts())) {
163     uint64_t ILRawVal = IL->getValue().getZExtValue();
164     if (DstArgDecl) {
165       if (const auto *Buffer = dyn_cast<ConstantArrayType>(DstArgDecl->getType())) {
166         ASTContext &C = BR.getContext();
167         uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
168         if (BufferLen < ILRawVal)
169           return true;
170       }
171     }
172   }
173 
174   return false;
175 }
176 
177 void WalkAST::VisitCallExpr(CallExpr *CE) {
178   const FunctionDecl *FD = CE->getDirectCallee();
179   if (!FD)
180     return;
181 
182   if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
183     if (containsBadStrncatPattern(CE)) {
184       const Expr *DstArg = CE->getArg(0);
185       const Expr *LenArg = CE->getArg(2);
186       PathDiagnosticLocation Loc =
187         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
188 
189       StringRef DstName = getPrintableName(DstArg);
190 
191       SmallString<256> S;
192       llvm::raw_svector_ostream os(S);
193       os << "Potential buffer overflow. ";
194       if (!DstName.empty()) {
195         os << "Replace with 'sizeof(" << DstName << ") "
196               "- strlen(" << DstName <<") - 1'";
197         os << " or u";
198       } else
199         os << "U";
200       os << "se a safer 'strlcat' API";
201 
202       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
203                          "C String API", os.str(), Loc,
204                          LenArg->getSourceRange());
205     }
206   } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy")) {
207     if (containsBadStrlcpyPattern(CE)) {
208       const Expr *DstArg = CE->getArg(0);
209       const Expr *LenArg = CE->getArg(2);
210       PathDiagnosticLocation Loc =
211         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
212 
213       StringRef DstName = getPrintableName(DstArg);
214 
215       SmallString<256> S;
216       llvm::raw_svector_ostream os(S);
217       os << "The third argument is larger than the size of the input buffer. ";
218       if (!DstName.empty())
219         os << "Replace with the value 'sizeof(" << DstName << ")` or lower";
220 
221       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
222                          "C String API", os.str(), Loc,
223                          LenArg->getSourceRange());
224     }
225   }
226 
227   // Recurse and check children.
228   VisitChildren(CE);
229 }
230 
231 void WalkAST::VisitChildren(Stmt *S) {
232   for (Stmt *Child : S->children())
233     if (Child)
234       Visit(Child);
235 }
236 
237 namespace {
238 class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
239 public:
240 
241   void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
242       BugReporter &BR) const {
243     WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
244     walker.Visit(D->getBody());
245   }
246 };
247 }
248 
249 void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
250   mgr.registerChecker<CStringSyntaxChecker>();
251 }
252 
253