xref: /src/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
1dbe13110SDimitry Andric //== CStringSyntaxChecker.cpp - CoreFoundation containers API *- C++ -*-==//
2dbe13110SDimitry Andric //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dbe13110SDimitry Andric //
7dbe13110SDimitry Andric //===----------------------------------------------------------------------===//
8dbe13110SDimitry Andric //
9dbe13110SDimitry Andric // An AST checker that looks for common pitfalls when using C string APIs.
10dbe13110SDimitry Andric //  - Identifies erroneous patterns in the last argument to strncat - the number
11dbe13110SDimitry Andric //    of bytes to copy.
12dbe13110SDimitry Andric //
13dbe13110SDimitry Andric //===----------------------------------------------------------------------===//
14676fbe81SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15dbe13110SDimitry Andric #include "clang/AST/Expr.h"
16dbe13110SDimitry Andric #include "clang/AST/OperationKinds.h"
17dbe13110SDimitry Andric #include "clang/AST/StmtVisitor.h"
18461a67faSDimitry Andric #include "clang/Analysis/AnalysisDeclContext.h"
19dbe13110SDimitry Andric #include "clang/Basic/TargetInfo.h"
20dbe13110SDimitry Andric #include "clang/Basic/TypeTraits.h"
21dbe13110SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
22809500fcSDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
23dbe13110SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
24dbe13110SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
25dbe13110SDimitry Andric #include "llvm/ADT/SmallString.h"
26dbe13110SDimitry Andric #include "llvm/Support/raw_ostream.h"
27dbe13110SDimitry Andric 
28dbe13110SDimitry Andric using namespace clang;
29dbe13110SDimitry Andric using namespace ento;
30dbe13110SDimitry Andric 
31dbe13110SDimitry Andric namespace {
32dbe13110SDimitry Andric class WalkAST: public StmtVisitor<WalkAST> {
339f4dbff6SDimitry Andric   const CheckerBase *Checker;
34dbe13110SDimitry Andric   BugReporter &BR;
35dbe13110SDimitry Andric   AnalysisDeclContext* AC;
36dbe13110SDimitry Andric 
37dbe13110SDimitry Andric   /// Check if two expressions refer to the same declaration.
sameDecl(const Expr * A1,const Expr * A2)387442d6faSDimitry Andric   bool sameDecl(const Expr *A1, const Expr *A2) {
397442d6faSDimitry Andric     if (const auto *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
407442d6faSDimitry Andric       if (const auto *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
41dbe13110SDimitry Andric         return D1->getDecl() == D2->getDecl();
42dbe13110SDimitry Andric     return false;
43dbe13110SDimitry Andric   }
44dbe13110SDimitry Andric 
45dbe13110SDimitry Andric   /// Check if the expression E is a sizeof(WithArg).
isSizeof(const Expr * E,const Expr * WithArg)467442d6faSDimitry Andric   bool isSizeof(const Expr *E, const Expr *WithArg) {
477442d6faSDimitry Andric     if (const auto *UE = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
487442d6faSDimitry Andric       if (UE->getKind() == UETT_SizeOf && !UE->isArgumentType())
49dbe13110SDimitry Andric         return sameDecl(UE->getArgumentExpr(), WithArg);
50dbe13110SDimitry Andric     return false;
51dbe13110SDimitry Andric   }
52dbe13110SDimitry Andric 
53dbe13110SDimitry Andric   /// Check if the expression E is a strlen(WithArg).
isStrlen(const Expr * E,const Expr * WithArg)547442d6faSDimitry Andric   bool isStrlen(const Expr *E, const Expr *WithArg) {
557442d6faSDimitry Andric     if (const auto *CE = dyn_cast<CallExpr>(E)) {
56dbe13110SDimitry Andric       const FunctionDecl *FD = CE->getDirectCallee();
57dbe13110SDimitry Andric       if (!FD)
58dbe13110SDimitry Andric         return false;
5913cc256eSDimitry Andric       return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
6013cc256eSDimitry Andric               sameDecl(CE->getArg(0), WithArg));
61dbe13110SDimitry Andric     }
62dbe13110SDimitry Andric     return false;
63dbe13110SDimitry Andric   }
64dbe13110SDimitry Andric 
65dbe13110SDimitry Andric   /// Check if the expression is an integer literal with value 1.
isOne(const Expr * E)667442d6faSDimitry Andric   bool isOne(const Expr *E) {
677442d6faSDimitry Andric     if (const auto *IL = dyn_cast<IntegerLiteral>(E))
68dbe13110SDimitry Andric       return (IL->getValue().isIntN(1));
69dbe13110SDimitry Andric     return false;
70dbe13110SDimitry Andric   }
71dbe13110SDimitry Andric 
getPrintableName(const Expr * E)727442d6faSDimitry Andric   StringRef getPrintableName(const Expr *E) {
737442d6faSDimitry Andric     if (const auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
74dbe13110SDimitry Andric       return D->getDecl()->getName();
75dbe13110SDimitry Andric     return StringRef();
76dbe13110SDimitry Andric   }
77dbe13110SDimitry Andric 
78dbe13110SDimitry Andric   /// Identify erroneous patterns in the last argument to strncat - the number
79dbe13110SDimitry Andric   /// of bytes to copy.
80dbe13110SDimitry Andric   bool containsBadStrncatPattern(const CallExpr *CE);
81dbe13110SDimitry Andric 
8248675466SDimitry Andric   /// Identify erroneous patterns in the last argument to strlcpy - the number
8348675466SDimitry Andric   /// of bytes to copy.
8448675466SDimitry Andric   /// The bad pattern checked is when the size is known
8548675466SDimitry Andric   /// to be larger than the destination can handle.
8648675466SDimitry Andric   ///   char dst[2];
8748675466SDimitry Andric   ///   size_t cpy = 4;
8848675466SDimitry Andric   ///   strlcpy(dst, "abcd", sizeof("abcd") - 1);
8948675466SDimitry Andric   ///   strlcpy(dst, "abcd", 4);
9048675466SDimitry Andric   ///   strlcpy(dst + 3, "abcd", 2);
9148675466SDimitry Andric   ///   strlcpy(dst, "abcd", cpy);
92676fbe81SDimitry Andric   /// Identify erroneous patterns in the last argument to strlcat - the number
93676fbe81SDimitry Andric   /// of bytes to copy.
94676fbe81SDimitry Andric   /// The bad pattern checked is when the last argument is basically
95676fbe81SDimitry Andric   /// pointing to the destination buffer size or argument larger or
96676fbe81SDimitry Andric   /// equal to.
97676fbe81SDimitry Andric   ///   char dst[2];
98676fbe81SDimitry Andric   ///   strlcat(dst, src2, sizeof(dst));
99676fbe81SDimitry Andric   ///   strlcat(dst, src2, 2);
100676fbe81SDimitry Andric   ///   strlcat(dst, src2, 10);
101676fbe81SDimitry Andric   bool containsBadStrlcpyStrlcatPattern(const CallExpr *CE);
10248675466SDimitry Andric 
103dbe13110SDimitry Andric public:
WalkAST(const CheckerBase * Checker,BugReporter & BR,AnalysisDeclContext * AC)1047442d6faSDimitry Andric   WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
1057442d6faSDimitry Andric       : Checker(Checker), BR(BR), AC(AC) {}
106dbe13110SDimitry Andric 
107dbe13110SDimitry Andric   // Statement visitor methods.
108dbe13110SDimitry Andric   void VisitChildren(Stmt *S);
VisitStmt(Stmt * S)109dbe13110SDimitry Andric   void VisitStmt(Stmt *S) {
110dbe13110SDimitry Andric     VisitChildren(S);
111dbe13110SDimitry Andric   }
112dbe13110SDimitry Andric   void VisitCallExpr(CallExpr *CE);
113dbe13110SDimitry Andric };
114dbe13110SDimitry Andric } // end anonymous namespace
115dbe13110SDimitry Andric 
116dbe13110SDimitry Andric // The correct size argument should look like following:
117dbe13110SDimitry Andric //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
118dbe13110SDimitry Andric // We look for the following anti-patterns:
119dbe13110SDimitry Andric //   - strncat(dst, src, sizeof(dst) - strlen(dst));
120dbe13110SDimitry Andric //   - strncat(dst, src, sizeof(dst) - 1);
121dbe13110SDimitry Andric //   - strncat(dst, src, sizeof(dst));
containsBadStrncatPattern(const CallExpr * CE)122dbe13110SDimitry Andric bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
1236a037251SDimitry Andric   if (CE->getNumArgs() != 3)
1246a037251SDimitry Andric     return false;
125dbe13110SDimitry Andric   const Expr *DstArg = CE->getArg(0);
126dbe13110SDimitry Andric   const Expr *SrcArg = CE->getArg(1);
127dbe13110SDimitry Andric   const Expr *LenArg = CE->getArg(2);
128dbe13110SDimitry Andric 
129dbe13110SDimitry Andric   // Identify wrong size expressions, which are commonly used instead.
1307442d6faSDimitry Andric   if (const auto *BE = dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
131dbe13110SDimitry Andric     // - sizeof(dst) - strlen(dst)
132dbe13110SDimitry Andric     if (BE->getOpcode() == BO_Sub) {
133dbe13110SDimitry Andric       const Expr *L = BE->getLHS();
134dbe13110SDimitry Andric       const Expr *R = BE->getRHS();
135dbe13110SDimitry Andric       if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
136dbe13110SDimitry Andric         return true;
137dbe13110SDimitry Andric 
138dbe13110SDimitry Andric       // - sizeof(dst) - 1
139dbe13110SDimitry Andric       if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
140dbe13110SDimitry Andric         return true;
141dbe13110SDimitry Andric     }
142dbe13110SDimitry Andric   }
143dbe13110SDimitry Andric   // - sizeof(dst)
144dbe13110SDimitry Andric   if (isSizeof(LenArg, DstArg))
145dbe13110SDimitry Andric     return true;
146dbe13110SDimitry Andric 
147dbe13110SDimitry Andric   // - sizeof(src)
148dbe13110SDimitry Andric   if (isSizeof(LenArg, SrcArg))
149dbe13110SDimitry Andric     return true;
150dbe13110SDimitry Andric   return false;
151dbe13110SDimitry Andric }
152dbe13110SDimitry Andric 
containsBadStrlcpyStrlcatPattern(const CallExpr * CE)153676fbe81SDimitry Andric bool WalkAST::containsBadStrlcpyStrlcatPattern(const CallExpr *CE) {
15448675466SDimitry Andric   if (CE->getNumArgs() != 3)
15548675466SDimitry Andric     return false;
15648675466SDimitry Andric   const Expr *DstArg = CE->getArg(0);
15748675466SDimitry Andric   const Expr *LenArg = CE->getArg(2);
15848675466SDimitry Andric 
159519fc96cSDimitry Andric   const auto *DstArgDRE = dyn_cast<DeclRefExpr>(DstArg->IgnoreParenImpCasts());
160519fc96cSDimitry Andric   const auto *LenArgDRE =
161519fc96cSDimitry Andric       dyn_cast<DeclRefExpr>(LenArg->IgnoreParenLValueCasts());
16248675466SDimitry Andric   uint64_t DstOff = 0;
163676fbe81SDimitry Andric   if (isSizeof(LenArg, DstArg))
164676fbe81SDimitry Andric     return false;
165519fc96cSDimitry Andric 
16648675466SDimitry Andric   // - size_t dstlen = sizeof(dst)
167519fc96cSDimitry Andric   if (LenArgDRE) {
168519fc96cSDimitry Andric     const auto *LenArgVal = dyn_cast<VarDecl>(LenArgDRE->getDecl());
169519fc96cSDimitry Andric     // If it's an EnumConstantDecl instead, then we're missing out on something.
170519fc96cSDimitry Andric     if (!LenArgVal) {
171519fc96cSDimitry Andric       assert(isa<EnumConstantDecl>(LenArgDRE->getDecl()));
172519fc96cSDimitry Andric       return false;
173519fc96cSDimitry Andric     }
17448675466SDimitry Andric     if (LenArgVal->getInit())
17548675466SDimitry Andric       LenArg = LenArgVal->getInit();
17648675466SDimitry Andric   }
17748675466SDimitry Andric 
17848675466SDimitry Andric   // - integral value
17948675466SDimitry Andric   // We try to figure out if the last argument is possibly longer
18048675466SDimitry Andric   // than the destination can possibly handle if its size can be defined.
18148675466SDimitry Andric   if (const auto *IL = dyn_cast<IntegerLiteral>(LenArg->IgnoreParenImpCasts())) {
18248675466SDimitry Andric     uint64_t ILRawVal = IL->getValue().getZExtValue();
18348675466SDimitry Andric 
18448675466SDimitry Andric     // Case when there is pointer arithmetic on the destination buffer
18548675466SDimitry Andric     // especially when we offset from the base decreasing the
18648675466SDimitry Andric     // buffer length accordingly.
187519fc96cSDimitry Andric     if (!DstArgDRE) {
188519fc96cSDimitry Andric       if (const auto *BE =
189519fc96cSDimitry Andric               dyn_cast<BinaryOperator>(DstArg->IgnoreParenImpCasts())) {
190519fc96cSDimitry Andric         DstArgDRE = dyn_cast<DeclRefExpr>(BE->getLHS()->IgnoreParenImpCasts());
19148675466SDimitry Andric         if (BE->getOpcode() == BO_Add) {
19248675466SDimitry Andric           if ((IL = dyn_cast<IntegerLiteral>(BE->getRHS()->IgnoreParenImpCasts()))) {
19348675466SDimitry Andric             DstOff = IL->getValue().getZExtValue();
19448675466SDimitry Andric           }
19548675466SDimitry Andric         }
19648675466SDimitry Andric       }
19748675466SDimitry Andric     }
198519fc96cSDimitry Andric     if (DstArgDRE) {
199519fc96cSDimitry Andric       if (const auto *Buffer =
200519fc96cSDimitry Andric               dyn_cast<ConstantArrayType>(DstArgDRE->getType())) {
20148675466SDimitry Andric         ASTContext &C = BR.getContext();
20248675466SDimitry Andric         uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
203676fbe81SDimitry Andric         auto RemainingBufferLen = BufferLen - DstOff;
204676fbe81SDimitry Andric         if (RemainingBufferLen < ILRawVal)
205676fbe81SDimitry Andric           return true;
206676fbe81SDimitry Andric       }
20748675466SDimitry Andric     }
20848675466SDimitry Andric   }
20948675466SDimitry Andric 
21048675466SDimitry Andric   return false;
21148675466SDimitry Andric }
21248675466SDimitry Andric 
VisitCallExpr(CallExpr * CE)213dbe13110SDimitry Andric void WalkAST::VisitCallExpr(CallExpr *CE) {
214dbe13110SDimitry Andric   const FunctionDecl *FD = CE->getDirectCallee();
215dbe13110SDimitry Andric   if (!FD)
216dbe13110SDimitry Andric     return;
217dbe13110SDimitry Andric 
21813cc256eSDimitry Andric   if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
219dbe13110SDimitry Andric     if (containsBadStrncatPattern(CE)) {
220dbe13110SDimitry Andric       const Expr *DstArg = CE->getArg(0);
221dbe13110SDimitry Andric       const Expr *LenArg = CE->getArg(2);
222dbe13110SDimitry Andric       PathDiagnosticLocation Loc =
223dbe13110SDimitry Andric         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
224dbe13110SDimitry Andric 
225dbe13110SDimitry Andric       StringRef DstName = getPrintableName(DstArg);
226dbe13110SDimitry Andric 
227dbe13110SDimitry Andric       SmallString<256> S;
228dbe13110SDimitry Andric       llvm::raw_svector_ostream os(S);
229dbe13110SDimitry Andric       os << "Potential buffer overflow. ";
230dbe13110SDimitry Andric       if (!DstName.empty()) {
231dbe13110SDimitry Andric         os << "Replace with 'sizeof(" << DstName << ") "
232dbe13110SDimitry Andric               "- strlen(" << DstName <<") - 1'";
233dbe13110SDimitry Andric         os << " or u";
234dbe13110SDimitry Andric       } else
235dbe13110SDimitry Andric         os << "U";
236dbe13110SDimitry Andric       os << "se a safer 'strlcat' API";
237dbe13110SDimitry Andric 
2389f4dbff6SDimitry Andric       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
2399f4dbff6SDimitry Andric                          "C String API", os.str(), Loc,
2409f4dbff6SDimitry Andric                          LenArg->getSourceRange());
241dbe13110SDimitry Andric     }
242676fbe81SDimitry Andric   } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy") ||
243676fbe81SDimitry Andric              CheckerContext::isCLibraryFunction(FD, "strlcat")) {
244676fbe81SDimitry Andric     if (containsBadStrlcpyStrlcatPattern(CE)) {
24548675466SDimitry Andric       const Expr *DstArg = CE->getArg(0);
24648675466SDimitry Andric       const Expr *LenArg = CE->getArg(2);
24748675466SDimitry Andric       PathDiagnosticLocation Loc =
24848675466SDimitry Andric         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
24948675466SDimitry Andric 
25048675466SDimitry Andric       StringRef DstName = getPrintableName(DstArg);
25148675466SDimitry Andric 
25248675466SDimitry Andric       SmallString<256> S;
25348675466SDimitry Andric       llvm::raw_svector_ostream os(S);
254676fbe81SDimitry Andric       os << "The third argument allows to potentially copy more bytes than it should. ";
255676fbe81SDimitry Andric       os << "Replace with the value ";
25648675466SDimitry Andric       if (!DstName.empty())
257676fbe81SDimitry Andric           os << "sizeof(" << DstName << ")";
258676fbe81SDimitry Andric       else
259676fbe81SDimitry Andric           os << "sizeof(<destination buffer>)";
260676fbe81SDimitry Andric       os << " or lower";
26148675466SDimitry Andric 
26248675466SDimitry Andric       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
26348675466SDimitry Andric               "C String API", os.str(), Loc,
26448675466SDimitry Andric               LenArg->getSourceRange());
26548675466SDimitry Andric     }
266dbe13110SDimitry Andric   }
267dbe13110SDimitry Andric 
268dbe13110SDimitry Andric   // Recurse and check children.
269dbe13110SDimitry Andric   VisitChildren(CE);
270dbe13110SDimitry Andric }
271dbe13110SDimitry Andric 
VisitChildren(Stmt * S)272dbe13110SDimitry Andric void WalkAST::VisitChildren(Stmt *S) {
273c192b3dcSDimitry Andric   for (Stmt *Child : S->children())
274c192b3dcSDimitry Andric     if (Child)
275c192b3dcSDimitry Andric       Visit(Child);
276dbe13110SDimitry Andric }
277dbe13110SDimitry Andric 
278dbe13110SDimitry Andric namespace {
279dbe13110SDimitry Andric class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
280dbe13110SDimitry Andric public:
281dbe13110SDimitry Andric 
checkASTCodeBody(const Decl * D,AnalysisManager & Mgr,BugReporter & BR) const282dbe13110SDimitry Andric   void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
283dbe13110SDimitry Andric       BugReporter &BR) const {
2849f4dbff6SDimitry Andric     WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
285dbe13110SDimitry Andric     walker.Visit(D->getBody());
286dbe13110SDimitry Andric   }
287dbe13110SDimitry Andric };
288dbe13110SDimitry Andric }
289dbe13110SDimitry Andric 
registerCStringSyntaxChecker(CheckerManager & mgr)290dbe13110SDimitry Andric void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
291dbe13110SDimitry Andric   mgr.registerChecker<CStringSyntaxChecker>();
292dbe13110SDimitry Andric }
293dbe13110SDimitry Andric 
shouldRegisterCStringSyntaxChecker(const CheckerManager & mgr)294cfca06d7SDimitry Andric bool ento::shouldRegisterCStringSyntaxChecker(const CheckerManager &mgr) {
29522989816SDimitry Andric   return true;
29622989816SDimitry Andric }
297