Coverage Report

Created: 2023-09-12 09:32

/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
#include <optional>
26
27
using namespace clang;
28
using namespace ento;
29
30
namespace {
31
// This evaluator checks two SVals for equality. The first SVal is provided via
32
// the constructor, the second is the parameter of the overloaded () operator.
33
// It uses the in-built ConstraintManager to resolve the equlity to possible or
34
// not possible ProgramStates.
35
class ConstraintBasedEQEvaluator {
36
  const DefinedOrUnknownSVal CompareValue;
37
  const ProgramStateRef PS;
38
  SValBuilder &SVB;
39
40
public:
41
  ConstraintBasedEQEvaluator(CheckerContext &C,
42
                             const DefinedOrUnknownSVal CompareValue)
43
108
      : CompareValue(CompareValue), PS(C.getState()), SVB(C.getSValBuilder()) {}
44
45
441
  bool operator()(const llvm::APSInt &EnumDeclInitValue) {
46
441
    DefinedOrUnknownSVal EnumDeclValue = SVB.makeIntVal(EnumDeclInitValue);
47
441
    DefinedOrUnknownSVal ElemEqualsValueToCast =
48
441
        SVB.evalEQ(PS, EnumDeclValue, CompareValue);
49
50
441
    return static_cast<bool>(PS->assume(ElemEqualsValueToCast, true));
51
441
  }
52
};
53
54
// This checker checks CastExpr statements.
55
// If the value provided to the cast is one of the values the enumeration can
56
// represent, the said value matches the enumeration. If the checker can
57
// establish the impossibility of matching it gives a warning.
58
// Being conservative, it does not warn if there is slight possibility the
59
// value can be matching.
60
class EnumCastOutOfRangeChecker : public Checker<check::PreStmt<CastExpr>> {
61
  mutable std::unique_ptr<BugType> EnumValueCastOutOfRange;
62
  void reportWarning(CheckerContext &C) const;
63
64
public:
65
  void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
66
};
67
68
using EnumValueVector = llvm::SmallVector<llvm::APSInt, 6>;
69
70
// Collects all of the values an enum can represent (as SVals).
71
111
EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
72
111
  EnumValueVector DeclValues(
73
111
      std::distance(ED->enumerator_begin(), ED->enumerator_end()));
74
111
  llvm::transform(ED->enumerators(), DeclValues.begin(),
75
540
                 [](const EnumConstantDecl *D) { return D->getInitVal(); });
76
111
  return DeclValues;
77
111
}
78
} // namespace
79
80
58
void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C) const {
81
58
  if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
82
58
    if (!EnumValueCastOutOfRange)
83
2
      EnumValueCastOutOfRange.reset(
84
2
          new BugType(this, "Enum cast out of range"));
85
58
    constexpr llvm::StringLiteral Msg =
86
58
        "The value provided to the cast expression is not in the valid range"
87
58
        " of values for the enum";
88
58
    C.emitReport(std::make_unique<PathSensitiveBugReport>(
89
58
        *EnumValueCastOutOfRange, Msg, N));
90
58
  }
91
58
}
92
93
void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr *CE,
94
136
                                             CheckerContext &C) const {
95
96
  // Only perform enum range check on casts where such checks are valid.  For
97
  // all other cast kinds (where enum range checks are unnecessary or invalid),
98
  // just return immediately.  TODO: The set of casts allowed for enum range
99
  // checking may be incomplete.  Better to add a missing cast kind to enable a
100
  // missing check than to generate false negatives and have to remove those
101
  // later.
102
136
  switch (CE->getCastKind()) {
103
111
  case CK_IntegralCast:
104
111
    break;
105
106
25
  default:
107
25
    return;
108
25
    
break0
;
109
136
  }
110
111
  // Get the value of the expression to cast.
112
111
  const std::optional<DefinedOrUnknownSVal> ValueToCast =
113
111
      C.getSVal(CE->getSubExpr()).getAs<DefinedOrUnknownSVal>();
114
115
  // If the value cannot be reasoned about (not even a DefinedOrUnknownSVal),
116
  // don't analyze further.
117
111
  if (!ValueToCast)
118
0
    return;
119
120
111
  const QualType T = CE->getType();
121
  // Check whether the cast type is an enum.
122
111
  if (!T->isEnumeralType())
123
0
    return;
124
125
  // If the cast is an enum, get its declaration.
126
  // If the isEnumeralType() returned true, then the declaration must exist
127
  // even if it is a stub declaration. It is up to the getDeclValuesForEnum()
128
  // function to handle this.
129
111
  const EnumDecl *ED = T->castAs<EnumType>()->getDecl();
130
131
111
  EnumValueVector DeclValues = getDeclValuesForEnum(ED);
132
133
  // If the declarator list is empty, bail out.
134
  // Every initialization an enum with a fixed underlying type but without any
135
  // enumerators would produce a warning if we were to continue at this point.
136
  // The most notable example is std::byte in the C++17 standard library.
137
111
  if (DeclValues.size() == 0)
138
3
    return;
139
140
  // Check if any of the enum values possibly match.
141
108
  bool PossibleValueMatch = llvm::any_of(
142
108
      DeclValues, ConstraintBasedEQEvaluator(C, *ValueToCast));
143
144
  // If there is no value that can possibly match any of the enum values, then
145
  // warn.
146
108
  if (!PossibleValueMatch)
147
58
    reportWarning(C);
148
108
}
149
150
2
void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {
151
2
  mgr.registerChecker<EnumCastOutOfRangeChecker>();
152
2
}
153
154
4
bool ento::shouldRegisterEnumCastOutOfRangeChecker(const CheckerManager &mgr) {
155
4
  return true;
156
4
}