xref: /freebsd-src/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp (revision e25152834cdf3b353892835a4f3b157e066a8ed4)
10b57cec5SDimitry Andric //== CStringSyntaxChecker.cpp - CoreFoundation containers API *- C++ -*-==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // An AST checker that looks for common pitfalls when using C string APIs.
100b57cec5SDimitry Andric //  - Identifies erroneous patterns in the last argument to strncat - the number
110b57cec5SDimitry Andric //    of bytes to copy.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
150b57cec5SDimitry Andric #include "clang/AST/Expr.h"
160b57cec5SDimitry Andric #include "clang/AST/OperationKinds.h"
170b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
180b57cec5SDimitry Andric #include "clang/Analysis/AnalysisDeclContext.h"
190b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
200b57cec5SDimitry Andric #include "clang/Basic/TypeTraits.h"
210b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
220b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
230b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
240b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
250b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
260b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric using namespace clang;
290b57cec5SDimitry Andric using namespace ento;
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric namespace {
320b57cec5SDimitry Andric class WalkAST: public StmtVisitor<WalkAST> {
330b57cec5SDimitry Andric   const CheckerBase *Checker;
340b57cec5SDimitry Andric   BugReporter &BR;
350b57cec5SDimitry Andric   AnalysisDeclContext* AC;
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric   /// Check if two expressions refer to the same declaration.
sameDecl(const Expr * A1,const Expr * A2)380b57cec5SDimitry Andric   bool sameDecl(const Expr *A1, const Expr *A2) {
390b57cec5SDimitry Andric     if (const auto *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
400b57cec5SDimitry Andric       if (const auto *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
410b57cec5SDimitry Andric         return D1->getDecl() == D2->getDecl();
420b57cec5SDimitry Andric     return false;
430b57cec5SDimitry Andric   }
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric   /// Check if the expression E is a sizeof(WithArg).
isSizeof(const Expr * E,const Expr * WithArg)460b57cec5SDimitry Andric   bool isSizeof(const Expr *E, const Expr *WithArg) {
470b57cec5SDimitry Andric     if (const auto *UE = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
480b57cec5SDimitry Andric       if (UE->getKind() == UETT_SizeOf && !UE->isArgumentType())
490b57cec5SDimitry Andric         return sameDecl(UE->getArgumentExpr(), WithArg);
500b57cec5SDimitry Andric     return false;
510b57cec5SDimitry Andric   }
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric   /// Check if the expression E is a strlen(WithArg).
isStrlen(const Expr * E,const Expr * WithArg)540b57cec5SDimitry Andric   bool isStrlen(const Expr *E, const Expr *WithArg) {
550b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<CallExpr>(E)) {
560b57cec5SDimitry Andric       const FunctionDecl *FD = CE->getDirectCallee();
570b57cec5SDimitry Andric       if (!FD)
580b57cec5SDimitry Andric         return false;
590b57cec5SDimitry Andric       return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
600b57cec5SDimitry Andric               sameDecl(CE->getArg(0), WithArg));
610b57cec5SDimitry Andric     }
620b57cec5SDimitry Andric     return false;
630b57cec5SDimitry Andric   }
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   /// Check if the expression is an integer literal with value 1.
isOne(const Expr * E)660b57cec5SDimitry Andric   bool isOne(const Expr *E) {
670b57cec5SDimitry Andric     if (const auto *IL = dyn_cast<IntegerLiteral>(E))
680b57cec5SDimitry Andric       return (IL->getValue().isIntN(1));
690b57cec5SDimitry Andric     return false;
700b57cec5SDimitry Andric   }
710b57cec5SDimitry Andric 
getPrintableName(const Expr * E)720b57cec5SDimitry Andric   StringRef getPrintableName(const Expr *E) {
730b57cec5SDimitry Andric     if (const auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
740b57cec5SDimitry Andric       return D->getDecl()->getName();
750b57cec5SDimitry Andric     return StringRef();
760b57cec5SDimitry Andric   }
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   /// Identify erroneous patterns in the last argument to strncat - the number
790b57cec5SDimitry Andric   /// of bytes to copy.
800b57cec5SDimitry Andric   bool containsBadStrncatPattern(const CallExpr *CE);
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   /// Identify erroneous patterns in the last argument to strlcpy - the number
830b57cec5SDimitry Andric   /// of bytes to copy.
840b57cec5SDimitry Andric   /// The bad pattern checked is when the size is known
850b57cec5SDimitry Andric   /// to be larger than the destination can handle.
860b57cec5SDimitry Andric   ///   char dst[2];
870b57cec5SDimitry Andric   ///   size_t cpy = 4;
880b57cec5SDimitry Andric   ///   strlcpy(dst, "abcd", sizeof("abcd") - 1);
890b57cec5SDimitry Andric   ///   strlcpy(dst, "abcd", 4);
900b57cec5SDimitry Andric   ///   strlcpy(dst + 3, "abcd", 2);
910b57cec5SDimitry Andric   ///   strlcpy(dst, "abcd", cpy);
920b57cec5SDimitry Andric   /// Identify erroneous patterns in the last argument to strlcat - the number
930b57cec5SDimitry Andric   /// of bytes to copy.
940b57cec5SDimitry Andric   /// The bad pattern checked is when the last argument is basically
950b57cec5SDimitry Andric   /// pointing to the destination buffer size or argument larger or
960b57cec5SDimitry Andric   /// equal to.
970b57cec5SDimitry Andric   ///   char dst[2];
980b57cec5SDimitry Andric   ///   strlcat(dst, src2, sizeof(dst));
990b57cec5SDimitry Andric   ///   strlcat(dst, src2, 2);
1000b57cec5SDimitry Andric   ///   strlcat(dst, src2, 10);
1010b57cec5SDimitry Andric   bool containsBadStrlcpyStrlcatPattern(const CallExpr *CE);
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric public:
WalkAST(const CheckerBase * Checker,BugReporter & BR,AnalysisDeclContext * AC)1040b57cec5SDimitry Andric   WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
1050b57cec5SDimitry Andric       : Checker(Checker), BR(BR), AC(AC) {}
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   // Statement visitor methods.
1080b57cec5SDimitry Andric   void VisitChildren(Stmt *S);
VisitStmt(Stmt * S)1090b57cec5SDimitry Andric   void VisitStmt(Stmt *S) {
1100b57cec5SDimitry Andric     VisitChildren(S);
1110b57cec5SDimitry Andric   }
1120b57cec5SDimitry Andric   void VisitCallExpr(CallExpr *CE);
1130b57cec5SDimitry Andric };
1140b57cec5SDimitry Andric } // end anonymous namespace
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric // The correct size argument should look like following:
1170b57cec5SDimitry Andric //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
1180b57cec5SDimitry Andric // We look for the following anti-patterns:
1190b57cec5SDimitry Andric //   - strncat(dst, src, sizeof(dst) - strlen(dst));
1200b57cec5SDimitry Andric //   - strncat(dst, src, sizeof(dst) - 1);
1210b57cec5SDimitry Andric //   - strncat(dst, src, sizeof(dst));
containsBadStrncatPattern(const CallExpr * CE)1220b57cec5SDimitry Andric bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
1230b57cec5SDimitry Andric   if (CE->getNumArgs() != 3)
1240b57cec5SDimitry Andric     return false;
1250b57cec5SDimitry Andric   const Expr *DstArg = CE->getArg(0);
1260b57cec5SDimitry Andric   const Expr *SrcArg = CE->getArg(1);
1270b57cec5SDimitry Andric   const Expr *LenArg = CE->getArg(2);
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   // Identify wrong size expressions, which are commonly used instead.
1300b57cec5SDimitry Andric   if (const auto *BE = dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
1310b57cec5SDimitry Andric     // - sizeof(dst) - strlen(dst)
1320b57cec5SDimitry Andric     if (BE->getOpcode() == BO_Sub) {
1330b57cec5SDimitry Andric       const Expr *L = BE->getLHS();
1340b57cec5SDimitry Andric       const Expr *R = BE->getRHS();
1350b57cec5SDimitry Andric       if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
1360b57cec5SDimitry Andric         return true;
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric       // - sizeof(dst) - 1
1390b57cec5SDimitry Andric       if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
1400b57cec5SDimitry Andric         return true;
1410b57cec5SDimitry Andric     }
1420b57cec5SDimitry Andric   }
1430b57cec5SDimitry Andric   // - sizeof(dst)
1440b57cec5SDimitry Andric   if (isSizeof(LenArg, DstArg))
1450b57cec5SDimitry Andric     return true;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   // - sizeof(src)
1480b57cec5SDimitry Andric   if (isSizeof(LenArg, SrcArg))
1490b57cec5SDimitry Andric     return true;
1500b57cec5SDimitry Andric   return false;
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric 
containsBadStrlcpyStrlcatPattern(const CallExpr * CE)1530b57cec5SDimitry Andric bool WalkAST::containsBadStrlcpyStrlcatPattern(const CallExpr *CE) {
1540b57cec5SDimitry Andric   if (CE->getNumArgs() != 3)
1550b57cec5SDimitry Andric     return false;
1560b57cec5SDimitry Andric   const Expr *DstArg = CE->getArg(0);
1570b57cec5SDimitry Andric   const Expr *LenArg = CE->getArg(2);
1580b57cec5SDimitry Andric 
159a7dea167SDimitry Andric   const auto *DstArgDRE = dyn_cast<DeclRefExpr>(DstArg->IgnoreParenImpCasts());
160a7dea167SDimitry Andric   const auto *LenArgDRE =
161a7dea167SDimitry Andric       dyn_cast<DeclRefExpr>(LenArg->IgnoreParenLValueCasts());
1620b57cec5SDimitry Andric   uint64_t DstOff = 0;
1630b57cec5SDimitry Andric   if (isSizeof(LenArg, DstArg))
1640b57cec5SDimitry Andric     return false;
165a7dea167SDimitry Andric 
1660b57cec5SDimitry Andric   // - size_t dstlen = sizeof(dst)
167a7dea167SDimitry Andric   if (LenArgDRE) {
168a7dea167SDimitry Andric     const auto *LenArgVal = dyn_cast<VarDecl>(LenArgDRE->getDecl());
169a7dea167SDimitry Andric     // If it's an EnumConstantDecl instead, then we're missing out on something.
170a7dea167SDimitry Andric     if (!LenArgVal) {
171a7dea167SDimitry Andric       assert(isa<EnumConstantDecl>(LenArgDRE->getDecl()));
172a7dea167SDimitry Andric       return false;
173a7dea167SDimitry Andric     }
1740b57cec5SDimitry Andric     if (LenArgVal->getInit())
1750b57cec5SDimitry Andric       LenArg = LenArgVal->getInit();
1760b57cec5SDimitry Andric   }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   // - integral value
1790b57cec5SDimitry Andric   // We try to figure out if the last argument is possibly longer
1800b57cec5SDimitry Andric   // than the destination can possibly handle if its size can be defined.
1810b57cec5SDimitry Andric   if (const auto *IL = dyn_cast<IntegerLiteral>(LenArg->IgnoreParenImpCasts())) {
1820b57cec5SDimitry Andric     uint64_t ILRawVal = IL->getValue().getZExtValue();
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric     // Case when there is pointer arithmetic on the destination buffer
1850b57cec5SDimitry Andric     // especially when we offset from the base decreasing the
1860b57cec5SDimitry Andric     // buffer length accordingly.
187a7dea167SDimitry Andric     if (!DstArgDRE) {
188a7dea167SDimitry Andric       if (const auto *BE =
189a7dea167SDimitry Andric               dyn_cast<BinaryOperator>(DstArg->IgnoreParenImpCasts())) {
190a7dea167SDimitry Andric         DstArgDRE = dyn_cast<DeclRefExpr>(BE->getLHS()->IgnoreParenImpCasts());
1910b57cec5SDimitry Andric         if (BE->getOpcode() == BO_Add) {
1920b57cec5SDimitry Andric           if ((IL = dyn_cast<IntegerLiteral>(BE->getRHS()->IgnoreParenImpCasts()))) {
1930b57cec5SDimitry Andric             DstOff = IL->getValue().getZExtValue();
1940b57cec5SDimitry Andric           }
1950b57cec5SDimitry Andric         }
1960b57cec5SDimitry Andric       }
1970b57cec5SDimitry Andric     }
198a7dea167SDimitry Andric     if (DstArgDRE) {
199a7dea167SDimitry Andric       if (const auto *Buffer =
200a7dea167SDimitry Andric               dyn_cast<ConstantArrayType>(DstArgDRE->getType())) {
2010b57cec5SDimitry Andric         ASTContext &C = BR.getContext();
2020b57cec5SDimitry Andric         uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
2030b57cec5SDimitry Andric         auto RemainingBufferLen = BufferLen - DstOff;
2040b57cec5SDimitry Andric         if (RemainingBufferLen < ILRawVal)
2050b57cec5SDimitry Andric           return true;
2060b57cec5SDimitry Andric       }
2070b57cec5SDimitry Andric     }
2080b57cec5SDimitry Andric   }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   return false;
2110b57cec5SDimitry Andric }
2120b57cec5SDimitry Andric 
VisitCallExpr(CallExpr * CE)2130b57cec5SDimitry Andric void WalkAST::VisitCallExpr(CallExpr *CE) {
2140b57cec5SDimitry Andric   const FunctionDecl *FD = CE->getDirectCallee();
2150b57cec5SDimitry Andric   if (!FD)
2160b57cec5SDimitry Andric     return;
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric   if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
2190b57cec5SDimitry Andric     if (containsBadStrncatPattern(CE)) {
2200b57cec5SDimitry Andric       const Expr *DstArg = CE->getArg(0);
2210b57cec5SDimitry Andric       const Expr *LenArg = CE->getArg(2);
2220b57cec5SDimitry Andric       PathDiagnosticLocation Loc =
2230b57cec5SDimitry Andric         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric       StringRef DstName = getPrintableName(DstArg);
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric       SmallString<256> S;
2280b57cec5SDimitry Andric       llvm::raw_svector_ostream os(S);
2290b57cec5SDimitry Andric       os << "Potential buffer overflow. ";
2300b57cec5SDimitry Andric       if (!DstName.empty()) {
2310b57cec5SDimitry Andric         os << "Replace with 'sizeof(" << DstName << ") "
2320b57cec5SDimitry Andric               "- strlen(" << DstName <<") - 1'";
2330b57cec5SDimitry Andric         os << " or u";
2340b57cec5SDimitry Andric       } else
2350b57cec5SDimitry Andric         os << "U";
2360b57cec5SDimitry Andric       os << "se a safer 'strlcat' API";
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
2390b57cec5SDimitry Andric                          "C String API", os.str(), Loc,
2400b57cec5SDimitry Andric                          LenArg->getSourceRange());
2410b57cec5SDimitry Andric     }
2420b57cec5SDimitry Andric   } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy") ||
2430b57cec5SDimitry Andric              CheckerContext::isCLibraryFunction(FD, "strlcat")) {
2440b57cec5SDimitry Andric     if (containsBadStrlcpyStrlcatPattern(CE)) {
2450b57cec5SDimitry Andric       const Expr *DstArg = CE->getArg(0);
2460b57cec5SDimitry Andric       const Expr *LenArg = CE->getArg(2);
2470b57cec5SDimitry Andric       PathDiagnosticLocation Loc =
2480b57cec5SDimitry Andric         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric       StringRef DstName = getPrintableName(DstArg);
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric       SmallString<256> S;
2530b57cec5SDimitry Andric       llvm::raw_svector_ostream os(S);
2540b57cec5SDimitry Andric       os << "The third argument allows to potentially copy more bytes than it should. ";
2550b57cec5SDimitry Andric       os << "Replace with the value ";
2560b57cec5SDimitry Andric       if (!DstName.empty())
2570b57cec5SDimitry Andric           os << "sizeof(" << DstName << ")";
2580b57cec5SDimitry Andric       else
2590b57cec5SDimitry Andric           os << "sizeof(<destination buffer>)";
2600b57cec5SDimitry Andric       os << " or lower";
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
2630b57cec5SDimitry Andric               "C String API", os.str(), Loc,
2640b57cec5SDimitry Andric               LenArg->getSourceRange());
2650b57cec5SDimitry Andric     }
2660b57cec5SDimitry Andric   }
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   // Recurse and check children.
2690b57cec5SDimitry Andric   VisitChildren(CE);
2700b57cec5SDimitry Andric }
2710b57cec5SDimitry Andric 
VisitChildren(Stmt * S)2720b57cec5SDimitry Andric void WalkAST::VisitChildren(Stmt *S) {
2730b57cec5SDimitry Andric   for (Stmt *Child : S->children())
2740b57cec5SDimitry Andric     if (Child)
2750b57cec5SDimitry Andric       Visit(Child);
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric namespace {
2790b57cec5SDimitry Andric class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
2800b57cec5SDimitry Andric public:
2810b57cec5SDimitry Andric 
checkASTCodeBody(const Decl * D,AnalysisManager & Mgr,BugReporter & BR) const2820b57cec5SDimitry Andric   void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
2830b57cec5SDimitry Andric       BugReporter &BR) const {
2840b57cec5SDimitry Andric     WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
2850b57cec5SDimitry Andric     walker.Visit(D->getBody());
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric };
2880b57cec5SDimitry Andric }
2890b57cec5SDimitry Andric 
registerCStringSyntaxChecker(CheckerManager & mgr)2900b57cec5SDimitry Andric void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
2910b57cec5SDimitry Andric   mgr.registerChecker<CStringSyntaxChecker>();
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
shouldRegisterCStringSyntaxChecker(const CheckerManager & mgr)294*5ffd83dbSDimitry Andric bool ento::shouldRegisterCStringSyntaxChecker(const CheckerManager &mgr) {
2950b57cec5SDimitry Andric   return true;
2960b57cec5SDimitry Andric }
297