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