xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp (revision 4903802fbfff23b27f0a030f6103818f6edb2a16)
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/Analysis/AnalysisContext.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/OperationKinds.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/TypeTraits.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.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   BugReporter &BR;
35   AnalysisDeclContext* AC;
36   ASTContext &ASTC;
37 
38   /// Check if two expressions refer to the same declaration.
39   inline bool sameDecl(const Expr *A1, const Expr *A2) {
40     if (const DeclRefExpr *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
41       if (const DeclRefExpr *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   inline bool isSizeof(const Expr *E, const Expr *WithArg) {
48     if (const UnaryExprOrTypeTraitExpr *UE =
49     dyn_cast<UnaryExprOrTypeTraitExpr>(E))
50       if (UE->getKind() == UETT_SizeOf)
51         return sameDecl(UE->getArgumentExpr(), WithArg);
52     return false;
53   }
54 
55   /// Check if the expression E is a strlen(WithArg).
56   inline bool isStrlen(const Expr *E, const Expr *WithArg) {
57     if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
58       const FunctionDecl *FD = CE->getDirectCallee();
59       if (!FD)
60         return false;
61       return (CheckerContext::isCLibraryFunction(FD, "strlen", ASTC)
62           && sameDecl(CE->getArg(0), WithArg));
63     }
64     return false;
65   }
66 
67   /// Check if the expression is an integer literal with value 1.
68   inline bool isOne(const Expr *E) {
69     if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
70       return (IL->getValue().isIntN(1));
71     return false;
72   }
73 
74   inline StringRef getPrintableName(const Expr *E) {
75     if (const DeclRefExpr *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
76       return D->getDecl()->getName();
77     return StringRef();
78   }
79 
80   /// Identify erroneous patterns in the last argument to strncat - the number
81   /// of bytes to copy.
82   bool containsBadStrncatPattern(const CallExpr *CE);
83 
84 public:
85   WalkAST(BugReporter &br, AnalysisDeclContext* ac) :
86       BR(br), AC(ac), ASTC(AC->getASTContext()) {
87   }
88 
89   // Statement visitor methods.
90   void VisitChildren(Stmt *S);
91   void VisitStmt(Stmt *S) {
92     VisitChildren(S);
93   }
94   void VisitCallExpr(CallExpr *CE);
95 };
96 } // end anonymous namespace
97 
98 // The correct size argument should look like following:
99 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
100 // We look for the following anti-patterns:
101 //   - strncat(dst, src, sizeof(dst) - strlen(dst));
102 //   - strncat(dst, src, sizeof(dst) - 1);
103 //   - strncat(dst, src, sizeof(dst));
104 bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
105   const Expr *DstArg = CE->getArg(0);
106   const Expr *SrcArg = CE->getArg(1);
107   const Expr *LenArg = CE->getArg(2);
108 
109   // Identify wrong size expressions, which are commonly used instead.
110   if (const BinaryOperator *BE =
111               dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
112     // - sizeof(dst) - strlen(dst)
113     if (BE->getOpcode() == BO_Sub) {
114       const Expr *L = BE->getLHS();
115       const Expr *R = BE->getRHS();
116       if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
117         return true;
118 
119       // - sizeof(dst) - 1
120       if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
121         return true;
122     }
123   }
124   // - sizeof(dst)
125   if (isSizeof(LenArg, DstArg))
126     return true;
127 
128   // - sizeof(src)
129   if (isSizeof(LenArg, SrcArg))
130     return true;
131   return false;
132 }
133 
134 void WalkAST::VisitCallExpr(CallExpr *CE) {
135   const FunctionDecl *FD = CE->getDirectCallee();
136   if (!FD)
137     return;
138 
139   if (CheckerContext::isCLibraryFunction(FD, "strncat", ASTC)) {
140     if (containsBadStrncatPattern(CE)) {
141       const Expr *DstArg = CE->getArg(0);
142       const Expr *LenArg = CE->getArg(2);
143       SourceRange R = LenArg->getSourceRange();
144       PathDiagnosticLocation Loc =
145         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
146 
147       StringRef DstName = getPrintableName(DstArg);
148 
149       llvm::SmallString<256> S;
150       llvm::raw_svector_ostream os(S);
151       os << "Potential buffer overflow. ";
152       if (!DstName.empty()) {
153         os << "Replace with 'sizeof(" << DstName << ") "
154               "- strlen(" << DstName <<") - 1'";
155         os << " or u";
156       } else
157         os << "U";
158       os << "se a safer 'strlcat' API";
159 
160       BR.EmitBasicReport("Anti-pattern in the argument", "C String API",
161                          os.str(), Loc, &R, 1);
162     }
163   }
164 
165   // Recurse and check children.
166   VisitChildren(CE);
167 }
168 
169 void WalkAST::VisitChildren(Stmt *S) {
170   for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
171       ++I)
172     if (Stmt *child = *I)
173       Visit(child);
174 }
175 
176 namespace {
177 class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
178 public:
179 
180   void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
181       BugReporter &BR) const {
182     WalkAST walker(BR, Mgr.getAnalysisDeclContext(D));
183     walker.Visit(D->getBody());
184   }
185 };
186 }
187 
188 void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
189   mgr.registerChecker<CStringSyntaxChecker>();
190 }
191 
192