Skip to content
Draft
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
6 changes: 6 additions & 0 deletions its/ruling/src/test/resources/diff_S9130.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"ruleKey": "S9130",
"hasTruePositives": true,
"falseNegatives": 0,
"falsePositives": 0
}
19 changes: 19 additions & 0 deletions its/ruling/src/test/resources/eclipse-jetty/java-S9130.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"org.eclipse.jetty:jetty-project:jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java": [
84
],
"org.eclipse.jetty:jetty-project:jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java": [
1379,
1386,
1407,
1414,
1423
],
"org.eclipse.jetty:jetty-project:jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java": [
303
],
"org.eclipse.jetty:jetty-project:jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java": [
466,
467
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package checks;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

class StreamReadResultCastCheckSample {

void byteCastInWhileLoop(FileInputStream fis) throws IOException {
byte b;
while ((b = (byte) fis.read()) != -1) { // Noncompliant {{Store the return value of "read()" in an "int" variable and check for -1 before casting.}}
process(b);
}
}

void byteCastAssignment(InputStream is) throws IOException {
byte value = (byte) is.read(); // Noncompliant
}

void charCastFromInputStream(InputStream is) throws IOException {
char c;
while ((c = (char) is.read()) != -1) { // Noncompliant
process(c);
}
}

void byteCastInDoWhile(FileInputStream fis) throws IOException {
byte b;
do {
b = (byte) fis.read(); // Noncompliant
} while (b != -1);
}

void charCastFromReader(FileReader reader) throws IOException {
char c;
while ((c = (char) reader.read()) != -1) { // Noncompliant
process(c);
}
}

void charCastAssignmentFromReader(Reader reader) throws IOException {
char c = (char) reader.read(); // Noncompliant
}

void byteCastWithParentheses(InputStream is) throws IOException {
byte b = (byte) (is.read()); // Noncompliant
}

void byteCastFromSubtype(BufferedInputStream bis) throws IOException {
byte b = (byte) bis.read(); // Noncompliant
}

// Compliant cases

void correctPatternWithIntVariable(FileInputStream fis) throws IOException {
int data;
while ((data = fis.read()) != -1) {
byte b = (byte) data;
process(b);
}
}

void multiArgReadByteArray(InputStream is) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead = is.read(buffer);
}

void multiArgReadByteArrayWithOffset(InputStream is) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead = is.read(buffer, 0, 1024);
}

void noCastAtAll(InputStream is) throws IOException {
int value = is.read();
}

void multiArgReadCharArray(Reader reader) throws IOException {
char[] buffer = new char[1024];
int charsRead = reader.read(buffer);
}

void correctPatternWithReader(Reader reader) throws IOException {
int data;
while ((data = reader.read()) != -1) {
char c = (char) data;
process(c);
}
}

void wideningCast(InputStream is) throws IOException {
long value = (long) is.read();
}

void customReadMethod() {
CustomReader custom = new CustomReader();
byte b = (byte) custom.read();
}

private void process(byte b) {}
private void process(char c) {}

static class CustomReader {
int read() {
return 0;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* 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.Collections;
import java.util.List;
import org.sonar.check.Rule;
import org.sonar.java.model.ExpressionUtils;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.semantic.MethodMatchers;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.TypeCastTree;

@Rule(key = "S9130")
public class StreamReadResultCastCheck extends IssuableSubscriptionVisitor {

private static final MethodMatchers READ_MATCHERS = MethodMatchers.or(
MethodMatchers.create()
.ofSubTypes("java.io.InputStream")
.names("read")
.addWithoutParametersMatcher()
.build(),
MethodMatchers.create()
.ofSubTypes("java.io.Reader")
.names("read")
.addWithoutParametersMatcher()
.build());

@Override
public List<Tree.Kind> nodesToVisit() {
return Collections.singletonList(Tree.Kind.TYPE_CAST);
}

@Override
public void visitNode(Tree tree) {
TypeCastTree castTree = (TypeCastTree) tree;
var castToType = castTree.type().symbolType();
if (castToType.is("byte") || castToType.is("char")) {
ExpressionTree expression = ExpressionUtils.skipParentheses(castTree.expression());
if (expression.is(Tree.Kind.METHOD_INVOCATION) && READ_MATCHERS.matches((MethodInvocationTree) expression)) {
reportIssue(castTree, "Store the return value of \"read()\" in an \"int\" variable and check for -1 before casting.");
}
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* 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 StreamReadResultCastCheckTest {

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

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<h2>Why is this an issue?</h2>
<p>Stream reading methods like <code>InputStream.read()</code> and <code>Reader.read()</code> return an <code>int</code> that can represent all
possible data values (0-255 for byte-oriented streams) plus a special sentinel value (<code>-1</code>) to indicate end-of-stream.</p>
<p>When the return value is cast to a narrower type (<code>byte</code> or <code>char</code>) before checking for <code>-1</code>, the maximum
unsigned value (such as 255 or 0xFF) wraps around to <code>-1</code> due to signed integer representation. This makes it impossible to distinguish
between a legitimate data value and end-of-stream, leading to premature termination or data corruption.</p>
<h3>Noncompliant code example</h3>
<pre data-diff-id="1" data-diff-type="noncompliant">
FileInputStream fis = new FileInputStream("data.bin");
byte b;
while ((b = (byte) fis.read()) != -1) { // Noncompliant
process(b);
}
</pre>
<h3>Compliant solution</h3>
<pre data-diff-id="1" data-diff-type="compliant">
FileInputStream fis = new FileInputStream("data.bin");
int data;
while ((data = fis.read()) != -1) {
byte b = (byte) data;
process(b);
}
</pre>
<h2>Resources</h2>
<ul>
<li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/InputStream.html#read()">InputStream.read() (Java SE 17 &amp; JDK 17)</a></li>
<li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/Reader.html#read()">Reader.read() (Java SE 17 &amp; JDK 17)</a></li>
</ul>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"title": "Stream read results should be checked for -1 before casting",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5 min"
},
"tags": [],
"defaultSeverity": "Critical",
"ruleSpecification": "RSPEC-9130",
"sqKey": "S9130",
"scope": "All",
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "HIGH"
},
"attribute": "LOGICAL"
}
}
Empty file.
Empty file.
Loading