File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
codeql-custom-queries-java/queries/performance Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 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"
You can’t perform that action at this time.
0 commit comments