-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathIntMultToLong.ql
More file actions
55 lines (52 loc) · 2.1 KB
/
IntMultToLong.ql
File metadata and controls
55 lines (52 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @name Result of multiplication cast to wider type
* @description Casting the result of a multiplication to a wider type instead of casting
* before the multiplication may cause overflow.
* @kind problem
* @problem.severity warning
* @precision very-high
* @id java/integer-multiplication-cast-to-long
* @tags reliability
* security
* correctness
* types
* external/cwe/cwe-190
* external/cwe/cwe-192
* external/cwe/cwe-197
* external/cwe/cwe-681
*/
import java
import semmle.code.java.dataflow.RangeUtils
import semmle.code.java.Conversions
/** An multiplication that does not overflow. */
predicate small(MulExpr e) {
exists(NumType t, float lhs, float rhs, float res | t = e.getType() |
lhs = e.getLeftOperand().getProperExpr().(ConstantIntegerExpr).getIntValue() and
rhs = e.getRightOperand().getProperExpr().(ConstantIntegerExpr).getIntValue() and
lhs * rhs = res and
t.getOrdPrimitiveType().getMinValue() <= res and res <= t.getOrdPrimitiveType().getMaxValue()
)
}
/**
* A parent of e, but only one that roughly preserves the value - in particular, not calls.
*/
Expr getRestrictedParent(Expr e) {
result = e.getParent() and
(result instanceof ArithExpr or result instanceof ConditionalExpr or result instanceof ParExpr)
}
from ConversionSite c, MulExpr e, NumType sourceType, NumType destType
where
// e is nested inside c, with only parents that roughly "preserve" the value
getRestrictedParent*(e) = c and
// the destination type is wider than the type of the multiplication
e.getType() = sourceType and
c.getConversionTarget() = destType and
destType.widerThan(sourceType) and
// not a trivial conversion
not c.isTrivial() and
// not an explicit conversion, which is probably intended by a user
c.isImplicit() and
// not obviously small and ok
not small(e) and
e.getEnclosingCallable().fromSource()
select c, "Potential overflow in $@ before it is converted to "+ destType.getName() +" by use in " + ("a " + c.kind()).regexpReplaceAll("^a ([aeiou])", "an $1") + ".", e, sourceType.getName() + " multiplication"