Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- EnumCastOutOfRangeChecker.cpp ---------------------------*- 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
// The EnumCastOutOfRangeChecker is responsible for checking integer to
10
// enumeration casts that could result in undefined values. This could happen
11
// if the value that we cast from is out of the value range of the enumeration.
12
// Reference:
13
// [ISO/IEC 14882-2014] ISO/IEC 14882-2014.
14
//   Programming Languages — C++, Fourth Edition. 2014.
15
// C++ Standard, [dcl.enum], in paragraph 8, which defines the range of an enum
16
// C++ Standard, [expr.static.cast], paragraph 10, which defines the behaviour
17
//   of casting an integer value that is out of range
18
// SEI CERT C++ Coding Standard, INT50-CPP. Do not cast to an out-of-range
19
//   enumeration value
20
//===----------------------------------------------------------------------===//
21
22
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
23
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
25
26
using namespace clang;
27
using namespace ento;
28
29
namespace {
30
// This evaluator checks two SVals for equality. The first SVal is provided via
31
// the constructor, the second is the parameter of the overloaded () operator.
32
// It uses the in-built ConstraintManager to resolve the equlity to possible or
33
// not possible ProgramStates.
34
class ConstraintBasedEQEvaluator {
35
  const DefinedOrUnknownSVal CompareValue;
36
  const ProgramStateRef PS;
37
  SValBuilder &SVB;
38
39
public:
40
  ConstraintBasedEQEvaluator(CheckerContext &C,
41
                             const DefinedOrUnknownSVal CompareValue)
42
108
      : CompareValue(CompareValue), PS(C.getState()), SVB(C.getSValBuilder()) {}
43
44
441
  bool operator()(const llvm::APSInt &EnumDeclInitValue) {
45
441
    DefinedOrUnknownSVal EnumDeclValue = SVB.makeIntVal(EnumDeclInitValue);
46
441
    DefinedOrUnknownSVal ElemEqualsValueToCast =
47
441
        SVB.evalEQ(PS, EnumDeclValue, CompareValue);
48
49
441
    return static_cast<bool>(PS->assume(ElemEqualsValueToCast, true));
50
441
  }
51
};
52
53
// This checker checks CastExpr statements.
54
// If the value provided to the cast is one of the values the enumeration can
55
// represent, the said value matches the enumeration. If the checker can
56
// establish the impossibility of matching it gives a warning.
57
// Being conservative, it does not warn if there is slight possibility the
58
// value can be matching.
59
class EnumCastOutOfRangeChecker : public Checker<check::PreStmt<CastExpr>> {
60
  mutable std::unique_ptr<BuiltinBug> EnumValueCastOutOfRange;
61
  void reportWarning(CheckerContext &C) const;
62
63
public:
64
  void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
65
};
66
67
using EnumValueVector = llvm::SmallVector<llvm::APSInt, 6>;
68
69
// Collects all of the values an enum can represent (as SVals).
70
108
EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
71
108
  EnumValueVector DeclValues(
72
108
      std::distance(ED->enumerator_begin(), ED->enumerator_end()));
73
108
  llvm::transform(ED->enumerators(), DeclValues.begin(),
74
540
                 [](const EnumConstantDecl *D) { return D->getInitVal(); });
75
108
  return DeclValues;
76
108
}
77
} // namespace
78
79
58
void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C) const {
80
58
  if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
81
58
    if (!EnumValueCastOutOfRange)
82
2
      EnumValueCastOutOfRange.reset(
83
2
          new BuiltinBug(this, "Enum cast out of range",
84
2
                         "The value provided to the cast expression is not in "
85
2
                         "the valid range of values for the enum"));
86
58
    C.emitReport(std::make_unique<PathSensitiveBugReport>(
87
58
        *EnumValueCastOutOfRange, EnumValueCastOutOfRange->getDescription(),
88
58
        N));
89
58
  }
90
58
}
91
92
void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr *CE,
93
129
                                             CheckerContext &C) const {
94
95
  // Only perform enum range check on casts where such checks are valid.  For
96
  // all other cast kinds (where enum range checks are unnecessary or invalid),
97
  // just return immediately.  TODO: The set of casts allowed for enum range
98
  // checking may be incomplete.  Better to add a missing cast kind to enable a
99
  // missing check than to generate false negatives and have to remove those
100
  // later.
101
129
  switch (CE->getCastKind()) {
102
108
  case CK_IntegralCast:
103
108
    break;
104
105
21
  default:
106
21
    return;
107
21
    
break0
;
108
129
  }
109
110
  // Get the value of the expression to cast.
111
108
  const llvm::Optional<DefinedOrUnknownSVal> ValueToCast =
112
108
      C.getSVal(CE->getSubExpr()).getAs<DefinedOrUnknownSVal>();
113
114
  // If the value cannot be reasoned about (not even a DefinedOrUnknownSVal),
115
  // don't analyze further.
116
108
  if (!ValueToCast)
117
0
    return;
118
119
108
  const QualType T = CE->getType();
120
  // Check whether the cast type is an enum.
121
108
  if (!T->isEnumeralType())
122
0
    return;
123
124
  // If the cast is an enum, get its declaration.
125
  // If the isEnumeralType() returned true, then the declaration must exist
126
  // even if it is a stub declaration. It is up to the getDeclValuesForEnum()
127
  // function to handle this.
128
108
  const EnumDecl *ED = T->castAs<EnumType>()->getDecl();
129
130
108
  EnumValueVector DeclValues = getDeclValuesForEnum(ED);
131
  // Check if any of the enum values possibly match.
132
108
  bool PossibleValueMatch = llvm::any_of(
133
108
      DeclValues, ConstraintBasedEQEvaluator(C, *ValueToCast));
134
135
  // If there is no value that can possibly match any of the enum values, then
136
  // warn.
137
108
  if (!PossibleValueMatch)
138
58
    reportWarning(C);
139
108
}
140
141
2
void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {
142
2
  mgr.registerChecker<EnumCastOutOfRangeChecker>();
143
2
}
144
145
4
bool ento::shouldRegisterEnumCastOutOfRangeChecker(const CheckerManager &mgr) {
146
4
  return true;
147
4
}