From 55d35221f7a92f1f7f9d9182722ccbfa79051748 Mon Sep 17 00:00:00 2001 From: Richard Yao Date: Wed, 24 Jan 2024 22:28:56 -0500 Subject: [PATCH] Add CodeQL check for bitshift precedence Signed-off-by: Richard Yao --- .github/codeql-cpp.yml | 1 + .../custom-queries/cpp/bitshiftPrecedence.ql | 51 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 .github/codeql/custom-queries/cpp/bitshiftPrecedence.ql diff --git a/.github/codeql-cpp.yml b/.github/codeql-cpp.yml index 88b8c6086025..862a682b5850 100644 --- a/.github/codeql-cpp.yml +++ b/.github/codeql-cpp.yml @@ -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 diff --git a/.github/codeql/custom-queries/cpp/bitshiftPrecedence.ql b/.github/codeql/custom-queries/cpp/bitshiftPrecedence.ql new file mode 100644 index 000000000000..2797cc670fc2 --- /dev/null +++ b/.github/codeql/custom-queries/cpp/bitshiftPrecedence.ql @@ -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."