Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package checks;

class BitwiseAndWithZeroCheckSample {

private static final int READ_PERMISSION = 0x04;

int getFlags() {
return 42;
}

void noncompliantPatterns() {
int flags = getFlags();
int result;

// Basic cases
result = flags & 0; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
result = 0 & flags; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}

// Hex zero
result = flags & 0x0; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
result = flags & 0x00; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
result = flags & 0X0; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}

// Long zero
result = (int) (flags & 0L); // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
result = (int) (flags & 0x00L); // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}

// Binary zero
result = flags & 0b0; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
result = flags & 0B0; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}

// Octal zero (leading zero)
result = flags & 00; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}

// Compound assignment
flags &= 0; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
flags &= 0x0; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
flags &= 0L; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}

// Parenthesized zero
result = flags & (0); // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
result = (0) & flags; // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
flags &= (0); // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}

// Nested in comparison (issue on the & expression)
if ((flags & 0) == 0) { } // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
if ((flags & 0) != 0) { } // Noncompliant {{Remove this bitwise AND with zero; the result is always zero.}}
}

void compliantPatterns() {
int flags = getFlags();
int mask = 0xFF;
int result;

// Non-zero bitmask
result = flags & 0x01;
result = flags & 0xFF;
result = flags & 1;

// Variable operands
result = flags & mask;
result = flags & READ_PERMISSION;

// Two variables
int a = 1, b = 2;
result = a & b;

// Non-zero compound assignment
flags &= 0x0F;

// Different operators (covered by S2437)
result = flags | 0;
result = flags ^ 0;

// Parenthesized non-zero
result = flags & (0x0F);

// Long non-zero bitmask
long longResult = flags & 0xFFL;
longResult = flags & 0x0FL;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import java.util.Arrays;
import java.util.List;
import org.sonar.check.Rule;
import org.sonar.java.model.ExpressionUtils;
import org.sonar.java.model.LiteralUtils;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.AssignmentExpressionTree;
import org.sonar.plugins.java.api.tree.BinaryExpressionTree;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.Tree.Kind;

@Rule(key = "S9344")
public class BitwiseAndWithZeroCheck extends IssuableSubscriptionVisitor {

private static final String MESSAGE = "Remove this bitwise AND with zero; the result is always zero.";

@Override
public List<Kind> nodesToVisit() {
return Arrays.asList(Kind.AND, Kind.AND_ASSIGNMENT);
}

@Override
public void visitNode(Tree tree) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issue location is inconsistent between the two branches: the & case reports the whole binary expression (reportIssue(tree, MESSAGE)), while the &= case reports only the operator token (reportIssue(assignment.operatorToken(), MESSAGE), line 47). The sibling rule S2437 (UnnecessaryBitOperationCheck) uses operatorToken() uniformly for both binary and assignment forms — worth aligning here too.

if (tree.is(Kind.AND)) {
BinaryExpressionTree binary = (BinaryExpressionTree) tree;
if (isZero(binary.leftOperand()) || isZero(binary.rightOperand())) {
reportIssue(binary.operatorToken(), MESSAGE);
}
} else {
AssignmentExpressionTree assignment = (AssignmentExpressionTree) tree;
if (isZero(assignment.expression())) {
reportIssue(assignment.operatorToken(), MESSAGE);
}
}
}

private static boolean isZero(ExpressionTree expression) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isZero() fails to detect a parenthesized zero literal, so flags & (0) is not flagged (false negative). LiteralUtils.longLiteralValue() only unwraps UNARY_MINUS/UNARY_PLUS before checking for INT_LITERAL/LONG_LITERAL — it never unwraps PARENTHESIZED_EXPRESSION. The codebase already has ExpressionUtils.skipParentheses used by other checks (e.g. StringConcatToTextBlockCheck, MathOnFloatCheck, UselessMathematicalComparisonCheck) for exactly this purpose. Also not covered by the test sample.

Long value = LiteralUtils.longLiteralValue(ExpressionUtils.skipParentheses(expression));
return value != null && value == 0L;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;

class BitwiseAndWithZeroCheckTest {

@Test
void test() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/BitwiseAndWithZeroCheckSample.java"))
.withCheck(new BitwiseAndWithZeroCheck())
.verifyIssues();
}

@Test
void test_without_semantic() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/BitwiseAndWithZeroCheckSample.java"))
.withCheck(new BitwiseAndWithZeroCheck())
.withoutSemantic()
.verifyIssues();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<h2>Why is this an issue?</h2>
<p>A bitwise AND operation combines two values bit by bit. When one of the operands is <code>0</code>, every bit in the result will be <code>0</code>
because <code>0 AND anything</code> is always <code>0</code>. This makes the operation meaningless and any subsequent comparison trivial.</p>
<p>This pattern almost always indicates a programming error, such as using the wrong constant, the wrong operator, or a copy-paste mistake.</p>
<h2>How to fix it</h2>
<p>Replace the <code>0</code> with the intended bitmask constant.</p>
<h3>Noncompliant code example</h3>
<pre>
int flags = getFlags();
if ((flags &amp; 0) == 0) { // Noncompliant - always true
doSomething();
}
</pre>
<h3>Compliant solution</h3>
<pre>
int flags = getFlags();
if ((flags &amp; 0x01) == 0) { // Compliant - checks if the least significant bit is not set
doSomething();
}
</pre>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"title": "Bitwise AND operations with zero should be corrected",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"suspicious"
],
"defaultSeverity": "Critical",
"ruleSpecification": "RSPEC-9344",
"sqKey": "S9344",
"scope": "All",
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "HIGH"
},
"attribute": "LOGICAL"
}
}
Empty file.
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ void profile_is_registered_as_expected() {
BuiltInQualityProfilesDefinition.BuiltInQualityProfile actualProfile = profilesPerLanguages.get("java").get("Sonar agentic AI");
assertThat(actualProfile.isDefault()).isFalse();
assertThat(actualProfile.rules())
.hasSize(465)
.hasSize(466)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's added by the rule-api tool. We will be doing a re-run of rule-api for all rules before the release anyway.

.extracting(BuiltInQualityProfilesDefinition.BuiltInActiveRule::ruleKey)
.doesNotContainAnyElementsOf(List.of(
"S101",
Expand Down
Loading