Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
Line
Count
Source (jump to first uncovered line)
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
//===----------------------------------------------------------------------===//
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "clang/AST/Expr.h"
16
#include "clang/AST/OperationKinds.h"
17
#include "clang/AST/StmtVisitor.h"
18
#include "clang/Analysis/AnalysisDeclContext.h"
19
#include "clang/Basic/TargetInfo.h"
20
#include "clang/Basic/TypeTraits.h"
21
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
22
#include "clang/StaticAnalyzer/Core/Checker.h"
23
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
24
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
25
#include "llvm/ADT/SmallString.h"
26
#include "llvm/Support/raw_ostream.h"
27
28
using namespace clang;
29
using namespace ento;
30
31
namespace {
32
class WalkAST: public StmtVisitor<WalkAST> {
33
  const CheckerBase *Checker;
34
  BugReporter &BR;
35
  AnalysisDeclContext* AC;
36
37
  /// Check if two expressions refer to the same declaration.
38
48
  bool sameDecl(const Expr *A1, const Expr *A2) {
39
48
    if (const auto *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
40
48
      if (const auto *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
41
48
        return D1->getDecl() == D2->getDecl();
42
0
    return false;
43
0
  }
44
45
  /// Check if the expression E is a sizeof(WithArg).
46
224
  bool isSizeof(const Expr *E, const Expr *WithArg) {
47
224
    if (const auto *UE = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
48
52
      if (UE->getKind() == UETT_SizeOf && !UE->isArgumentType())
49
44
        return sameDecl(UE->getArgumentExpr(), WithArg);
50
180
    return false;
51
180
  }
52
53
  /// Check if the expression E is a strlen(WithArg).
54
8
  bool isStrlen(const Expr *E, const Expr *WithArg) {
55
8
    if (const auto *CE = dyn_cast<CallExpr>(E)) {
56
4
      const FunctionDecl *FD = CE->getDirectCallee();
57
4
      if (!FD)
58
0
        return false;
59
4
      return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
60
4
              sameDecl(CE->getArg(0), WithArg));
61
4
    }
62
4
    return false;
63
4
  }
64
65
  /// Check if the expression is an integer literal with value 1.
66
4
  bool isOne(const Expr *E) {
67
4
    if (const auto *IL = dyn_cast<IntegerLiteral>(E))
68
4
      return (IL->getValue().isIntN(1));
69
0
    return false;
70
0
  }
71
72
36
  StringRef getPrintableName(const Expr *E) {
73
36
    if (const auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
74
28
      return D->getDecl()->getName();
75
8
    return StringRef();
76
8
  }
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
103
public:
104
  WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
105
1.34k
      : Checker(Checker), BR(BR), AC(AC) {}
106
107
  // Statement visitor methods.
108
  void VisitChildren(Stmt *S);
109
35.0k
  void VisitStmt(Stmt *S) {
110
35.0k
    VisitChildren(S);
111
35.0k
  }
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));
122
113
bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
123
113
  if (CE->getNumArgs() != 3)
124
41
    return false;
125
72
  const Expr *DstArg = CE->getArg(0);
126
72
  const Expr *SrcArg = CE->getArg(1);
127
72
  const Expr *LenArg = CE->getArg(2);
128
72
129
72
  // Identify wrong size expressions, which are commonly used instead.
130
72
  if (const auto *BE = dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
131
8
    // - sizeof(dst) - strlen(dst)
132
8
    if (BE->getOpcode() == BO_Sub) {
133
8
      const Expr *L = BE->getLHS();
134
8
      const Expr *R = BE->getRHS();
135
8
      if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
136
4
        return true;
137
4
138
4
      // - sizeof(dst) - 1
139
4
      if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
140
4
        return true;
141
64
    }
142
8
  }
143
64
  // - sizeof(dst)
144
64
  if (isSizeof(LenArg, DstArg))
145
4
    return true;
146
60
147
60
  // - sizeof(src)
148
60
  if (isSizeof(LenArg, SrcArg))
149
4
    return true;
150
56
  return false;
151
56
}
152
153
88
bool WalkAST::containsBadStrlcpyStrlcatPattern(const CallExpr *CE) {
154
88
  if (CE->getNumArgs() != 3)
155
0
    return false;
156
88
  const Expr *DstArg = CE->getArg(0);
157
88
  const Expr *LenArg = CE->getArg(2);
158
88
159
88
  const auto *DstArgDecl = dyn_cast<DeclRefExpr>(DstArg->IgnoreParenImpCasts());
160
88
  const auto *LenArgDecl = dyn_cast<DeclRefExpr>(LenArg->IgnoreParenLValueCasts());
161
88
  uint64_t DstOff = 0;
162
88
  if (isSizeof(LenArg, DstArg))
163
20
    return false;
164
68
  // - size_t dstlen = sizeof(dst)
165
68
  if (LenArgDecl) {
166
24
    const auto *LenArgVal = dyn_cast<VarDecl>(LenArgDecl->getDecl());
167
24
    if (LenArgVal->getInit())
168
16
      LenArg = LenArgVal->getInit();
169
24
  }
170
68
171
68
  // - integral value
172
68
  // We try to figure out if the last argument is possibly longer
173
68
  // than the destination can possibly handle if its size can be defined.
174
68
  if (const auto *IL = dyn_cast<IntegerLiteral>(LenArg->IgnoreParenImpCasts())) {
175
40
    uint64_t ILRawVal = IL->getValue().getZExtValue();
176
40
177
40
    // Case when there is pointer arithmetic on the destination buffer
178
40
    // especially when we offset from the base decreasing the
179
40
    // buffer length accordingly.
180
40
    if (!DstArgDecl) {
181
12
      if (const auto *BE = dyn_cast<BinaryOperator>(DstArg->IgnoreParenImpCasts())) {
182
12
        DstArgDecl = dyn_cast<DeclRefExpr>(BE->getLHS()->IgnoreParenImpCasts());
183
12
        if (BE->getOpcode() == BO_Add) {
184
12
          if ((IL = dyn_cast<IntegerLiteral>(BE->getRHS()->IgnoreParenImpCasts()))) {
185
12
            DstOff = IL->getValue().getZExtValue();
186
12
          }
187
12
        }
188
12
      }
189
12
    }
190
40
    if (DstArgDecl) {
191
40
      if (const auto *Buffer = dyn_cast<ConstantArrayType>(DstArgDecl->getType())) {
192
40
        ASTContext &C = BR.getContext();
193
40
        uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
194
40
        auto RemainingBufferLen = BufferLen - DstOff;
195
40
        if (RemainingBufferLen < ILRawVal)
196
20
          return true;
197
48
      }
198
40
    }
199
40
  }
200
48
201
48
  return false;
202
48
}
203
204
3.50k
void WalkAST::VisitCallExpr(CallExpr *CE) {
205
3.50k
  const FunctionDecl *FD = CE->getDirectCallee();
206
3.50k
  if (!FD)
207
9
    return;
208
3.50k
209
3.50k
  if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
210
113
    if (containsBadStrncatPattern(CE)) {
211
16
      const Expr *DstArg = CE->getArg(0);
212
16
      const Expr *LenArg = CE->getArg(2);
213
16
      PathDiagnosticLocation Loc =
214
16
        PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
215
16
216
16
      StringRef DstName = getPrintableName(DstArg);
217
16
218
16
      SmallString<256> S;
219
16
      llvm::raw_svector_ostream os(S);
220
16
      os << "Potential buffer overflow. ";
221
16
      if (!DstName.empty()) {
222
16
        os << "Replace with 'sizeof(" << DstName << ") "
223
16
              "- strlen(" << DstName <<") - 1'";
224
16
        os << " or u";
225
16
      } else
226
0
        os << "U";
227
16
      os << "se a safer 'strlcat' API";
228
16
229
16
      BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
230
16
                         "C String API", os.str(), Loc,
231
16
                         LenArg->getSourceRange());
232
16
    }
233
3.38k
  } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy") ||
234
3.38k
             
CheckerContext::isCLibraryFunction(FD, "strlcat")3.33k
) {
235
88
    if (containsBadStrlcpyStrlcatPattern(CE)) {
236
20
      const Expr *DstArg = CE->getArg(0);
237
20
      const Expr *LenArg = CE->getArg(2);
238
20
      PathDiagnosticLocation Loc =
239
20
        PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
240
20
241
20
      StringRef DstName = getPrintableName(DstArg);
242
20
243
20
      SmallString<256> S;
244
20
      llvm::raw_svector_ostream os(S);
245
20
      os << "The third argument allows to potentially copy more bytes than it should. ";
246
20
      os << "Replace with the value ";
247
20
      if (!DstName.empty())
248
12
          os << "sizeof(" << DstName << ")";
249
8
      else
250
8
          os << "sizeof(<destination buffer>)";
251
20
      os << " or lower";
252
20
253
20
      BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
254
20
              "C String API", os.str(), Loc,
255
20
              LenArg->getSourceRange());
256
20
    }
257
88
  }
258
3.50k
259
3.50k
  // Recurse and check children.
260
3.50k
  VisitChildren(CE);
261
3.50k
}
262
263
38.5k
void WalkAST::VisitChildren(Stmt *S) {
264
38.5k
  for (Stmt *Child : S->children())
265
37.1k
    if (Child)
266
37.1k
      Visit(Child);
267
38.5k
}
268
269
namespace {
270
class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
271
public:
272
273
  void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
274
1.34k
      BugReporter &BR) const {
275
1.34k
    WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
276
1.34k
    walker.Visit(D->getBody());
277
1.34k
  }
278
};
279
}
280
281
52
void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
282
52
  mgr.registerChecker<CStringSyntaxChecker>();
283
52
}
284
285
52
bool ento::shouldRegisterCStringSyntaxChecker(const LangOptions &LO) {
286
52
  return true;
287
52
}