Skip to content

Commit eef9e44

Browse files
committed
Add not-using-ByteArrayOutputStream-writeTo.ql
1 parent a844987 commit eef9e44

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Finds usage of `ByteArrayOutputStream` where the written data is obtained
3+
* using `toByteArray()` and then later written to another `OutputStream`.
4+
* In these cases `ByteArrayOutputStream.writeTo` should be preferred because
5+
* unlike `toByteArray()` it avoids creating a copy of the internal buffer.
6+
*
7+
* @kind problem
8+
*/
9+
10+
import java
11+
import semmle.code.java.dataflow.DataFlow
12+
13+
class ToByteArrayMethod extends Method {
14+
ToByteArrayMethod() {
15+
getDeclaringType().hasQualifiedName("java.io", "ByteArrayOutputStream") and
16+
hasStringSignature("toByteArray()")
17+
}
18+
}
19+
20+
class OutputStreamWriteMethod extends Method {
21+
OutputStreamWriteMethod() {
22+
getDeclaringType().getASourceSupertype*().hasQualifiedName("java.io", "OutputStream") and
23+
hasStringSignature("write(byte[])")
24+
}
25+
}
26+
27+
from MethodAccess toByteArrayCall, MethodAccess writeCall
28+
where
29+
toByteArrayCall.getMethod() instanceof ToByteArrayMethod and
30+
writeCall.getMethod() instanceof OutputStreamWriteMethod and
31+
// TODO: Using dataflow causes some false positives when array is additionally used in other ways
32+
DataFlow::localExprFlow(toByteArrayCall, writeCall.getArgument(0))
33+
select toByteArrayCall,
34+
"Could use `ByteArrayOutputStream.writeTo` instead of manually writing to `OutputStream` $@",
35+
writeCall, "here"

0 commit comments

Comments
 (0)