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