Skip to content

Commit

Permalink
Add CodeQL check for bitshift precedence
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Yao <richard.yao@alumni.stonybrook.edu>
ryao committed Jan 25, 2024
1 parent e010c1e commit 55d3522
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions .github/codeql-cpp.yml
Original file line number Diff line number Diff line change
@@ -2,3 +2,4 @@ name: "Custom CodeQL Analysis"

queries:
- uses: ./.github/codeql/custom-queries/cpp/deprecatedFunctionUsage.ql
- uses: ./.github/codeql/custom-queries/cpp/bitshiftPrecedence.ql
51 changes: 51 additions & 0 deletions .github/codeql/custom-queries/cpp/bitshiftPrecedence.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* @name Bit shift precedence issue
* @description Detects bit shift operations where an arithmetic operation could be misinterpreted due to lack of parentheses, specifically when the left child is an arithmetic expression other than multiplication, or the right child is an arithmetic expression.
* @kind problem
* @severity warning
* @id cpp/bitshift-precedence-issue
*/

import cpp

class NonParenthesizedArithmeticExpr extends Expr {
NonParenthesizedArithmeticExpr() {
(
this instanceof AddExpr or
this instanceof SubExpr or
this instanceof MulExpr or
this instanceof DivExpr or
this instanceof RemExpr
) and
not exists(ParenthesisExpr pe | pe.getExpr() = this)
}
}

from Expr bitShiftExpr, NonParenthesizedArithmeticExpr arithExpr
where
(
bitShiftExpr instanceof LShiftExpr or
bitShiftExpr instanceof RShiftExpr
) and
(
(
// Check if the left operand is a non-parenthesized arithmetic expression excluding multiplication
arithExpr = bitShiftExpr.(LShiftExpr).getLeftOperand() and
not arithExpr instanceof MulExpr
) or
(
// Check if the right operand is a non-parenthesized arithmetic expression
arithExpr = bitShiftExpr.(LShiftExpr).getRightOperand()
) or
(
// Check if the left operand is a non-parenthesized arithmetic expression excluding multiplication
arithExpr= bitShiftExpr.(RShiftExpr).getLeftOperand() and
not arithExpr instanceof MulExpr
) or
(
// Check if the right operand is a non-parenthesized arithmetic expression
arithExpr = bitShiftExpr.(RShiftExpr).getRightOperand()
)
)
select bitShiftExpr,
"This bit shift operation's operand is an arithmetic operation without parentheses and may not be evaluated as intended due to operator precedence."

0 comments on commit 55d3522

Please sign in to comment.