From ad3e32d93517612e438c1d1d857979c6c78c67c4 Mon Sep 17 00:00:00 2001 From: jrm Date: Wed, 13 Apr 2016 16:06:40 -0700 Subject: [PATCH] Fix resource leak false positive with the resource wrapper java.io.DataInputStream Summary:public The code: DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); creates a resource with `FileInputStream()` and wraps it twice as a field of `BufferedInputStream` and then as a field of `DataInputStream`. Then calling: in.close(); needs to go down the wrappers hierachy: `DataInputStream.close()` -> `FilterInputStream.close()` which then calls `BufferedInputStream.close()` -> `FilterInputStream.close()` -> `FileInputStream.close()`. Going down the wrapper was not working before because `FilterInputStream.close()` was only going further when the type of field `in` was `FileInputStream` wheras it should also continue when the type of the field is any subtype of `FilterInputStream`, e.g. `DataInputStream` and `BufferedInputStream` like in the test example. This diff fixes this last aspect. Reviewed By: sblackshear Differential Revision: D3174822 fb-gh-sync-id: 3adbb7e fbshipit-source-id: 3adbb7e --- infer/models/java/src/java/io/FilterInputStream.java | 8 ++++++-- .../java/infer/FilterInputStreamLeaks.java | 12 +++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/infer/models/java/src/java/io/FilterInputStream.java b/infer/models/java/src/java/io/FilterInputStream.java index 5cab86568..e682588f1 100644 --- a/infer/models/java/src/java/io/FilterInputStream.java +++ b/infer/models/java/src/java/io/FilterInputStream.java @@ -28,9 +28,13 @@ public class FilterInputStream extends InputStream { } public void close() throws IOException { - if (in != null) - if (in instanceof FileInputStream) + if (in != null) { + if (in instanceof FileInputStream) { ((FileInputStream) in).close(); + } else { + in.close(); + } + } } public int read() throws IOException { diff --git a/infer/tests/codetoanalyze/java/infer/FilterInputStreamLeaks.java b/infer/tests/codetoanalyze/java/infer/FilterInputStreamLeaks.java index 1b12e0e80..351522c6d 100644 --- a/infer/tests/codetoanalyze/java/infer/FilterInputStreamLeaks.java +++ b/infer/tests/codetoanalyze/java/infer/FilterInputStreamLeaks.java @@ -10,11 +10,7 @@ package codetoanalyze.java.infer; -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.PushbackInputStream; +import java.io.*; import java.security.DigestInputStream; import java.util.zip.CheckedInputStream; import java.util.zip.DeflaterInputStream; @@ -263,4 +259,10 @@ public class FilterInputStreamLeaks { if (pms != null) pms.close(); } } + + public void twoLevelWrapperNoLeak(File file) throws IOException { + DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); + in.close(); + } + }