clang 18.0.0git
EnumCastOutOfRangeChecker.cpp
Go to the documentation of this file.
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
25#include <optional>
26
27using namespace clang;
28using namespace ento;
29
30namespace {
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.
35class ConstraintBasedEQEvaluator {
36 const DefinedOrUnknownSVal CompareValue;
37 const ProgramStateRef PS;
38 SValBuilder &SVB;
39
40public:
41 ConstraintBasedEQEvaluator(CheckerContext &C,
42 const DefinedOrUnknownSVal CompareValue)
43 : CompareValue(CompareValue), PS(C.getState()), SVB(C.getSValBuilder()) {}
44
45 bool operator()(const llvm::APSInt &EnumDeclInitValue) {
46 DefinedOrUnknownSVal EnumDeclValue = SVB.makeIntVal(EnumDeclInitValue);
47 DefinedOrUnknownSVal ElemEqualsValueToCast =
48 SVB.evalEQ(PS, EnumDeclValue, CompareValue);
49
50 return static_cast<bool>(PS->assume(ElemEqualsValueToCast, true));
51 }
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.
60class EnumCastOutOfRangeChecker : public Checker<check::PreStmt<CastExpr>> {
61 mutable std::unique_ptr<BugType> EnumValueCastOutOfRange;
62 void reportWarning(CheckerContext &C, const CastExpr *CE,
63 const EnumDecl *E) const;
64
65public:
66 void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
67};
68
69using EnumValueVector = llvm::SmallVector<llvm::APSInt, 6>;
70
71// Collects all of the values an enum can represent (as SVals).
72EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
73 EnumValueVector DeclValues(
74 std::distance(ED->enumerator_begin(), ED->enumerator_end()));
75 llvm::transform(ED->enumerators(), DeclValues.begin(),
76 [](const EnumConstantDecl *D) { return D->getInitVal(); });
77 return DeclValues;
78}
79} // namespace
80
81void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
82 const CastExpr *CE,
83 const EnumDecl *E) const {
84 assert(E && "valid EnumDecl* is expected");
85 if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
86 if (!EnumValueCastOutOfRange)
87 EnumValueCastOutOfRange.reset(
88 new BugType(this, "Enum cast out of range"));
89
90 llvm::SmallString<128> Msg{"The value provided to the cast expression is "
91 "not in the valid range of values for "};
92 StringRef EnumName{E->getName()};
93 if (EnumName.empty()) {
94 Msg += "the enum";
95 } else {
96 Msg += '\'';
97 Msg += EnumName;
98 Msg += '\'';
99 }
100
101 auto BR = std::make_unique<PathSensitiveBugReport>(*EnumValueCastOutOfRange,
102 Msg, N);
104 BR->addNote("enum declared here",
105 PathDiagnosticLocation::create(E, C.getSourceManager()),
106 {E->getSourceRange()});
107 C.emitReport(std::move(BR));
108 }
109}
110
111void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr *CE,
112 CheckerContext &C) const {
113
114 // Only perform enum range check on casts where such checks are valid. For
115 // all other cast kinds (where enum range checks are unnecessary or invalid),
116 // just return immediately. TODO: The set of casts allowed for enum range
117 // checking may be incomplete. Better to add a missing cast kind to enable a
118 // missing check than to generate false negatives and have to remove those
119 // later.
120 switch (CE->getCastKind()) {
121 case CK_IntegralCast:
122 break;
123
124 default:
125 return;
126 break;
127 }
128
129 // Get the value of the expression to cast.
130 const std::optional<DefinedOrUnknownSVal> ValueToCast =
131 C.getSVal(CE->getSubExpr()).getAs<DefinedOrUnknownSVal>();
132
133 // If the value cannot be reasoned about (not even a DefinedOrUnknownSVal),
134 // don't analyze further.
135 if (!ValueToCast)
136 return;
137
138 const QualType T = CE->getType();
139 // Check whether the cast type is an enum.
140 if (!T->isEnumeralType())
141 return;
142
143 // If the cast is an enum, get its declaration.
144 // If the isEnumeralType() returned true, then the declaration must exist
145 // even if it is a stub declaration. It is up to the getDeclValuesForEnum()
146 // function to handle this.
147 const EnumDecl *ED = T->castAs<EnumType>()->getDecl();
148
149 EnumValueVector DeclValues = getDeclValuesForEnum(ED);
150
151 // If the declarator list is empty, bail out.
152 // Every initialization an enum with a fixed underlying type but without any
153 // enumerators would produce a warning if we were to continue at this point.
154 // The most notable example is std::byte in the C++17 standard library.
155 if (DeclValues.size() == 0)
156 return;
157
158 // Check if any of the enum values possibly match.
159 bool PossibleValueMatch =
160 llvm::any_of(DeclValues, ConstraintBasedEQEvaluator(C, *ValueToCast));
161
162 // If there is no value that can possibly match any of the enum values, then
163 // warn.
164 if (!PossibleValueMatch)
165 reportWarning(C, CE, ED);
166}
167
168void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {
169 mgr.registerChecker<EnumCastOutOfRangeChecker>();
170}
171
172bool ento::shouldRegisterEnumCastOutOfRangeChecker(const CheckerManager &mgr) {
173 return true;
174}
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3517
CastKind getCastKind() const
Definition: Expr.h:3561
Expr * getSubExpr()
Definition: Expr.h:3567
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3253
Represents an enum.
Definition: Decl.h:3816
enumerator_range enumerators() const
Definition: Decl.h:3949
enumerator_iterator enumerator_begin() const
Definition: Decl.h:3953
enumerator_iterator enumerator_end() const
Definition: Decl.h:3960
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4997
QualType getType() const
Definition: Expr.h:142
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:275
A (possibly-)qualified type.
Definition: Type.h:736
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7625
bool isEnumeralType() const
Definition: Type.h:7127
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:278
SVal evalEQ(ProgramStateRef state, SVal lhs, SVal rhs)
bool trackExpressionValue(const ExplodedNode *N, const Expr *E, PathSensitiveBugReport &R, TrackingOptions Opts={})
Attempts to add visitors to track expression value back to its point of origin.