-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathMistypedExponentiation.ql
More file actions
53 lines (49 loc) · 1.61 KB
/
MistypedExponentiation.ql
File metadata and controls
53 lines (49 loc) · 1.61 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
/**
* @name Bitwise exclusive-or used like exponentiation
* @description Using ^ as exponentiation is a mistake, as it is the bitwise exclusive-or operator.
* @kind problem
* @problem.severity warning
* @id go/mistyped-exponentiation
* @tags quality
* reliability
* correctness
* external/cwe/cwe-480
* @precision high
*/
import go
private Expr getConstantInitialiser(Expr e) {
exists(DeclaredConstant c | e = c.getAReference() | result = c.getInit())
}
/** Holds if `e` is not 0 and is either an octal or hexadecimal literal, or the number one. */
predicate maybeXorBitPattern(Expr e) {
// 0 makes no sense as an xor bit pattern
not e.getNumericValue() = 0 and
// include octal and hex literals
[e, getConstantInitialiser(e)].(IntLit).getText().matches("0%")
or
e.getNumericValue() = 1
}
from XorExpr xe, Expr lhs, Expr rhs
where
lhs = xe.getLeftOperand() and
rhs = xe.getRightOperand() and
exists(lhs.getNumericValue()) and
not maybeXorBitPattern(lhs) and
(
not maybeXorBitPattern(rhs) and
rhs.getIntValue() >= 0
or
exists(Ident id | id = xe.getRightOperand() |
id.getName().regexpMatch("(?i)_*((exp(onent)?)|pow(er)?)")
)
) and
// exclude the right hand side of assignments to variables that have "mask" in their name
not exists(Assignment assign, Ident id | assign.getRhs() = xe.getParent*() |
id.getName().regexpMatch("(?i).*mask.*") and
(
assign.getLhs() = id or
assign.getLhs().(SelectorExpr).getSelector() = id
)
)
select xe,
"This expression uses the bitwise exclusive-or operator when exponentiation was likely meant."