CodeQL 文档

不正确的“非”运算符使用

ID: cpp/incorrect-not-operator-usage
Kind: problem
Security severity: 7.5
Severity: warning
Precision: medium
Tags:
   - security
   - external/cwe/cwe-480
Query suites:
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

此规则查找在按位运算中用作运算符的逻辑非运算符使用。

由于逻辑运算结果值的性质,只有最低位可能被设置,并且在按位运算中不太可能是故意的。违规行为通常表明输入错误,使用逻辑非(!)运算符而不是按位非(~)运算符。

此规则仅限于分析按位与(&)和按位或(|)运算,以提供更好的精度。

此规则忽略显式使用双重否定(!!)作为按位运算符的实例,因为这是一种将整数值规范化为 1 或 0 的常用机制。

注意:不建议在内核代码或较旧的 C 代码中使用此规则,因为它可能会发现许多误报实例。

建议

仔细检查标记的表达式。考虑代码逻辑中的意图,并确定是否需要更改非运算符。

示例

以下是一个此问题示例,以及如何修复它

#define FLAGS   0x4004

void f_warning(int i)
{
    // BAD: the usage of the logical not operator in this case is unlikely to be correct
    // as the output is being used as an operator for a bit-wise and operation
    if (i & !FLAGS)
    {
        // code
    }
}

void f_fixed(int i)
{
    if (i & ~FLAGS) // GOOD: Changing the logical not operator for the bit-wise not operator would fix this logic
    {
        // code
    }
}

在其他情况下,特别是当表达式具有 bool 类型时,修复可能采用以下形式 a && !b

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私