1 //===- EnumCastOutOfRangeChecker.cpp ---------------------------*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The EnumCastOutOfRangeChecker is responsible for checking integer to
11 // enumeration casts that could result in undefined values. This could happen
12 // if the value that we cast from is out of the value range of the enumeration.
14 // [ISO/IEC 14882-2014] ISO/IEC 14882-2014.
15 // Programming Languages — C++, Fourth Edition. 2014.
16 // C++ Standard, [dcl.enum], in paragraph 8, which defines the range of an enum
17 // C++ Standard, [expr.static.cast], paragraph 10, which defines the behaviour
18 // of casting an integer value that is out of range
19 // SEI CERT C++ Coding Standard, INT50-CPP. Do not cast to an out-of-range
21 //===----------------------------------------------------------------------===//
23 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
24 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
27 using namespace clang;
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;
41 ConstraintBasedEQEvaluator(CheckerContext &C,
42 const DefinedOrUnknownSVal CompareValue)
43 : CompareValue(CompareValue), PS(C.getState()), SVB(C.getSValBuilder()) {}
45 bool operator()(const llvm::APSInt &EnumDeclInitValue) {
46 DefinedOrUnknownSVal EnumDeclValue = SVB.makeIntVal(EnumDeclInitValue);
47 DefinedOrUnknownSVal ElemEqualsValueToCast =
48 SVB.evalEQ(PS, EnumDeclValue, CompareValue);
50 return static_cast<bool>(PS->assume(ElemEqualsValueToCast, true));
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<BuiltinBug> EnumValueCastOutOfRange;
62 void reportWarning(CheckerContext &C) const;
65 void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
68 using EnumValueVector = llvm::SmallVector<llvm::APSInt, 6>;
70 // Collects all of the values an enum can represent (as SVals).
71 EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
72 EnumValueVector DeclValues(
73 std::distance(ED->enumerator_begin(), ED->enumerator_end()));
74 llvm::transform(ED->enumerators(), DeclValues.begin(),
75 [](const EnumConstantDecl *D) { return D->getInitVal(); });
80 void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C) const {
81 if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
82 if (!EnumValueCastOutOfRange)
83 EnumValueCastOutOfRange.reset(
84 new BuiltinBug(this, "Enum cast out of range",
85 "The value provided to the cast expression is not in "
86 "the valid range of values for the enum"));
87 C.emitReport(llvm::make_unique<BugReport>(
88 *EnumValueCastOutOfRange, EnumValueCastOutOfRange->getDescription(),
93 void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr *CE,
94 CheckerContext &C) const {
95 // Get the value of the expression to cast.
96 const llvm::Optional<DefinedOrUnknownSVal> ValueToCast =
97 C.getSVal(CE->getSubExpr()).getAs<DefinedOrUnknownSVal>();
99 // If the value cannot be reasoned about (not even a DefinedOrUnknownSVal),
100 // don't analyze further.
104 const QualType T = CE->getType();
105 // Check whether the cast type is an enum.
106 if (!T->isEnumeralType())
109 // If the cast is an enum, get its declaration.
110 // If the isEnumeralType() returned true, then the declaration must exist
111 // even if it is a stub declaration. It is up to the getDeclValuesForEnum()
112 // function to handle this.
113 const EnumDecl *ED = T->castAs<EnumType>()->getDecl();
115 EnumValueVector DeclValues = getDeclValuesForEnum(ED);
116 // Check if any of the enum values possibly match.
117 bool PossibleValueMatch = llvm::any_of(
118 DeclValues, ConstraintBasedEQEvaluator(C, *ValueToCast));
120 // If there is no value that can possibly match any of the enum values, then
122 if (!PossibleValueMatch)
126 void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {
127 mgr.registerChecker<EnumCastOutOfRangeChecker>();