Create rule S7438 Incompatible bit masks should not be used in comparisons (#4781)

* Create rule S7438

* Update rule.adoc

* Update metadata.json

* Update metadata.json

* Update metadata.json

* Update rule.adoc

* Update metadata.json

* Update rule.adoc

---------

Co-authored-by: sallaigy <sallaigy@users.noreply.github.com>
Co-authored-by: Gyula Sallai <gyula.sallai@sonarsource.com>
This commit is contained in:
github-actions[bot] 2025-03-19 14:10:14 +00:00 committed by GitHub
parent 00d540f5ed
commit 29af6f4517
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,24 @@
{
"title": "Incompatible bit masks should not be used in comparisons",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Blocker",
"ruleSpecification": "RSPEC-7438",
"sqKey": "S7438",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "HIGH"
},
"attribute": "LOGICAL"
}
}

View File

@ -0,0 +1,42 @@
== Why is this an issue?
If the bits that the comparison cares about are always set to zero or one by the bit mask, the comparison is constant true or false (depending on mask, compared value, and operators). This results in dead code, potential security vulnerabilities, confusion for developers, and wasted processing time on redundant checks.
== How to fix it
Ensuring valid bitwise operations in comparisons requires:
* For `&` (AND) operations:
** `x & mask == value` is valid if all bits set in `value` are also set in `mask`
** `x & mask < value` is valid if `mask < value`
** `x & mask > value` is valid if `mask > value`
* For `|` (OR) operations:
** `x | mask == value` is valid if all bits set in `mask` are also set in `value`
Correct the bit mask or comparison value to create a valid logical expression that can be both true and false depending on input. This ensures the bitwise operations in the comparisons result in meaningful code execution.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
let x = 1;
if (x & 1 == 2) {
// This code will never execute
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
let x = 1;
if (x & 2 == 2) {
// This code will execute when the second bit of x is set
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#bad_bit_mask