|
| 1 | +/** |
| 2 | + * Provides a configurable module DoNotCastToAnOutOfRangeEnumerationValueShared with a `problems` predicate |
| 3 | + * for the following issue: |
| 4 | + * Casting to an out-of-range enumeration value leads to unspecified or undefined |
| 5 | + * behavior. |
| 6 | + */ |
| 7 | + |
| 8 | +import cpp |
| 9 | +import codingstandards.cpp.Customizations |
| 10 | +import codingstandards.cpp.Exclusions |
| 11 | +import codingstandards.cpp.Enums |
| 12 | +import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis |
| 13 | +import codingstandards.cpp.SimpleRangeAnalysisCustomizations |
| 14 | + |
| 15 | +signature module DoNotCastToAnOutOfRangeEnumerationValueSharedConfigSig { |
| 16 | + Query getQuery(); |
| 17 | +} |
| 18 | + |
| 19 | +module DoNotCastToAnOutOfRangeEnumerationValueShared< |
| 20 | + DoNotCastToAnOutOfRangeEnumerationValueSharedConfigSig Config> |
| 21 | +{ |
| 22 | + query predicate problems(Cast c, string description, Enum e, string enumName) { |
| 23 | + not isExcluded(c, Config::getQuery()) and |
| 24 | + // Conversion from an integral type to an enum type |
| 25 | + c.getExpr().getType().getUnspecifiedType() instanceof IntegralType and |
| 26 | + c.getType().getUnspecifiedType() = e and |
| 27 | + not ( |
| 28 | + // The deduced bound for the expression is within the type range for the explicit type |
| 29 | + upperBound(c.getExpr()) <= Enums::getValueRangeUpperBound(e) and |
| 30 | + lowerBound(c.getExpr()) >= Enums::getValueRangeLowerBound(e) |
| 31 | + ) and |
| 32 | + // Not a compile time constant with the same value as an existing enum constant |
| 33 | + not exists(float enumConstantValue | |
| 34 | + enumConstantValue = Enums::getEnumConstantValue(e.getAnEnumConstant()) |
| 35 | + | |
| 36 | + // Expression is a constant |
| 37 | + c.getExpr().getValue().toFloat() = enumConstantValue |
| 38 | + or |
| 39 | + // Range analysis has precise bounds |
| 40 | + enumConstantValue = upperBound(c.getExpr()) and |
| 41 | + enumConstantValue = lowerBound(c.getExpr()) |
| 42 | + ) and |
| 43 | + enumName = e.getName() and |
| 44 | + ( |
| 45 | + if exists(upperBound(c.getExpr())) |
| 46 | + then |
| 47 | + description = |
| 48 | + "Cast to enum $@ with value range " + Enums::getValueRangeLowerBound(e) + "..." + |
| 49 | + Enums::getValueRangeUpperBound(e) + " from expression with wider value range " + |
| 50 | + lowerBound(c.getExpr()) + "..." + upperBound(c.getExpr()) + " in function " + |
| 51 | + c.getEnclosingFunction().getName() + "." |
| 52 | + else |
| 53 | + description = |
| 54 | + "Cast to enum $@ with value range " + Enums::getValueRangeLowerBound(e) + "..." + |
| 55 | + Enums::getValueRangeUpperBound(e) + |
| 56 | + " from expression with a potentially wider value range." |
| 57 | + ) |
| 58 | + } |
| 59 | +} |
0 commit comments