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