Plug numerous potential resource leaks

This fixes 33 out of 37 Eclipse "Potential resource leak: '...' may
not be closed" warnings.  It also fixes 3 out of 37 Eclipse "Resource
'...' should be managed by try-with-resource" warnings, although that
was not the main focus of this effort.

The remaining 4 warnings about potential resource leaks all involve a
leaked JarFile instance that is passed to a JarFileModule constructor
call.  JarFileModile never attempts to close its underlying JarFile;
this code is written as though JarFile cleanup were the caller's
responsibility.  However, the JarFile often cannot be closed by the
code that creates the JarFileModule either, since the JarFile needs to
remain open while the JarFileModule is in use, and some of these
JarFileModules stay around beyond the lifetime of the code that
created them.  Truly fixing this would essentially require making
JarFileModule implement Closeable, which in turn would probably
require that Module implement Closeable, which in turn would require
changes to lots of code that deals with Module instances to arrange
for them to be properly closed.  That's more invasive than I'm
prepared to take on right now.
This commit is contained in:
Ben Liblit 2017-03-12 00:44:55 -06:00
parent 7a3a23b2b4
commit b1678882b3
28 changed files with 213 additions and 174 deletions

View File

@ -111,9 +111,10 @@ public abstract class JavaSourceAnalysisEngine<I extends InstanceKey> extends Ab
scope = makeSourceAnalysisScope(); scope = makeSourceAnalysisScope();
if (getExclusionsFile() != null) { if (getExclusionsFile() != null) {
InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile()); try (final InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile())) {
scope.setExclusions(new FileOfClasses(is)); scope.setExclusions(new FileOfClasses(is));
} }
}
for (Module M : this.systemEntries) { for (Module M : this.systemEntries) {
scope.addToScope(scope.getPrimordialLoader(), M); scope.addToScope(scope.getPrimordialLoader(), M);

View File

@ -251,16 +251,15 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
private void getScriptFromUrl(String urlAsString, ITag scriptTag) throws IOException, MalformedURLException { private void getScriptFromUrl(String urlAsString, ITag scriptTag) throws IOException, MalformedURLException {
URL scriptSrc = new URL(entrypointUrl, urlAsString); URL scriptSrc = new URL(entrypointUrl, urlAsString);
Reader scriptInputStream; BOMInputStream bs;
try { try {
BOMInputStream bs = new BOMInputStream(scriptSrc.openConnection().getInputStream(), false, bs = new BOMInputStream(scriptSrc.openConnection().getInputStream(), false,
ByteOrderMark.UTF_8, ByteOrderMark.UTF_8,
ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE,
ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE); ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE);
if (bs.hasBOM()) { if (bs.hasBOM()) {
System.err.println("removing BOM " + bs.getBOM()); System.err.println("removing BOM " + bs.getBOM());
} }
scriptInputStream = new InputStreamReader(bs);
} catch (Exception e) { } catch (Exception e) {
//it looks like this happens when we can't resolve the url? //it looks like this happens when we can't resolve the url?
if (DEBUG) { if (DEBUG) {
@ -270,22 +269,17 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
} }
return; return;
} }
try (
BufferedReader scriptReader = null; final Reader scriptInputStream = new InputStreamReader(bs);
try { final BufferedReader scriptReader = new BufferedReader(scriptInputStream);
) {
String line; String line;
scriptReader = new BufferedReader(scriptInputStream);
StringBuffer x = new StringBuffer(); StringBuffer x = new StringBuffer();
while ((line = scriptReader.readLine()) != null) { while ((line = scriptReader.readLine()) != null) {
x.append(line).append("\n"); x.append(line).append("\n");
} }
scriptRegion.println(x.toString(), scriptTag.getElementPosition(), scriptSrc, false); scriptRegion.println(x.toString(), scriptTag.getElementPosition(), scriptSrc, false);
} finally {
if (scriptReader != null) {
scriptReader.close();
}
} }
} }
@ -329,9 +323,11 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
public Set<MappedSourceModule> extractSources(URL entrypointUrl, IHtmlParser htmlParser, IUrlResolver urlResolver) public Set<MappedSourceModule> extractSources(URL entrypointUrl, IHtmlParser htmlParser, IUrlResolver urlResolver)
throws IOException, Error { throws IOException, Error {
Reader inputStreamReader = WebUtil.getStream(entrypointUrl); IGeneratorCallback htmlCallback;
IGeneratorCallback htmlCallback = createHtmlCallback(entrypointUrl, urlResolver); try (Reader inputStreamReader = WebUtil.getStream(entrypointUrl)) {
htmlCallback = createHtmlCallback(entrypointUrl, urlResolver);
htmlParser.parse(entrypointUrl, inputStreamReader, htmlCallback, entrypointUrl.getFile()); htmlParser.parse(entrypointUrl, inputStreamReader, htmlCallback, entrypointUrl.getFile());
}
SourceRegion finalRegion = new SourceRegion(); SourceRegion finalRegion = new SourceRegion();
htmlCallback.writeToFinalRegion(finalRegion); htmlCallback.writeToFinalRegion(finalRegion);
@ -339,7 +335,10 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
// writing the final region into one SourceFileModule. // writing the final region into one SourceFileModule.
File outputFile = createOutputFile(entrypointUrl, DELETE_UPON_EXIT, USE_TEMP_NAME); File outputFile = createOutputFile(entrypointUrl, DELETE_UPON_EXIT, USE_TEMP_NAME);
tempFile = outputFile; tempFile = outputFile;
FileMapping fileMapping = finalRegion.writeToFile(new PrintWriter(new FileWriter(outputFile))); FileMapping fileMapping;
try (final PrintWriter printer = new PrintWriter(new FileWriter(outputFile))) {
fileMapping = finalRegion.writeToFile(printer);
}
if (fileMapping == null) { if (fileMapping == null) {
fileMapping = new EmptyFileMapping(); fileMapping = new EmptyFileMapping();
} }

View File

@ -28,17 +28,17 @@ public class CAstPrinter {
} }
@Override @Override
public void write(char[] cbuf, int off, int len) throws IOException { public void write(char[] cbuf, int off, int len) {
sb.append(new String(cbuf, off, len)); sb.append(new String(cbuf, off, len));
} }
@Override @Override
public void flush() throws IOException { public void flush() {
// do nothing // do nothing
} }
@Override @Override
public void close() throws IOException { public void close() {
// do nothing // do nothing
} }
} }
@ -146,15 +146,17 @@ public class CAstPrinter {
public String doPrint(CAstNode top, CAstSourcePositionMap pos) { public String doPrint(CAstNode top, CAstSourcePositionMap pos) {
final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
Writer writer = new StringWriter(sb); try (final StringWriter writer = new StringWriter(sb)) {
printTo(top, pos, writer); printTo(top, pos, writer);
}
return sb.toString(); return sb.toString();
} }
public String doPrint(CAstEntity ce) { public String doPrint(CAstEntity ce) {
final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
StringWriter writer = new StringWriter(sb); try (final StringWriter writer = new StringWriter(sb)) {
printTo(ce, writer); printTo(ce, writer);
}
return sb.toString(); return sb.toString();
} }

View File

@ -58,8 +58,10 @@ public class CFGSanitizerTest extends WalaTestCase {
ClassHierarchy cha = ClassHierarchyFactory.make(scope); ClassHierarchy cha = ClassHierarchyFactory.make(scope);
ClassLoader cl = CFGSanitizerTest.class.getClassLoader(); ClassLoader cl = CFGSanitizerTest.class.getClassLoader();
InputStream s = cl.getResourceAsStream("natives.xml"); XMLMethodSummaryReader summary;
XMLMethodSummaryReader summary = new XMLMethodSummaryReader(s, scope); try (final InputStream s = cl.getResourceAsStream("natives.xml")) {
summary = new XMLMethodSummaryReader(s, scope);
}
AnalysisOptions options = new AnalysisOptions(scope, null); AnalysisOptions options = new AnalysisOptions(scope, null);
Map<MethodReference, MethodSummary> summaries = summary.getSummaries(); Map<MethodReference, MethodSummary> summaries = summary.getSummaries();
for (MethodReference mr : summaries.keySet()) { for (MethodReference mr : summaries.keySet()) {

View File

@ -931,9 +931,10 @@ public class SlicerTest {
public static void dumpSliceToFile(Collection<Statement> slice, String fileName) throws FileNotFoundException { public static void dumpSliceToFile(Collection<Statement> slice, String fileName) throws FileNotFoundException {
File f = new File(fileName); File f = new File(fileName);
FileOutputStream fo = new FileOutputStream(f); FileOutputStream fo = new FileOutputStream(f);
PrintWriter w = new PrintWriter(fo); try (final PrintWriter w = new PrintWriter(fo)) {
dumpSlice(slice, w); dumpSlice(slice, w);
} }
}
public static CGNode findMainMethod(CallGraph cg) { public static CGNode findMainMethod(CallGraph cg) {
Descriptor d = Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V"); Descriptor d = Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V");

View File

@ -105,7 +105,9 @@ public class SimpleThreadEscapeAnalysis extends AbstractAnalysisEngine {
collectJars(files[i], result); collectJars(files[i], result);
} }
} else if (f.getAbsolutePath().endsWith(".jar")) { } else if (f.getAbsolutePath().endsWith(".jar")) {
result.add(new JarFile(f, false)); try (final JarFile jar = new JarFile(f, false)) {
result.add(jar);
}
} }
} }

View File

@ -93,7 +93,10 @@ public class DalvikCallGraphTestBase extends DynamicCallGraphTestBase {
public void dynamicCG(File javaJarPath, String mainClass, String... args) throws FileNotFoundException, IOException, ClassNotFoundException, InvalidClassFileException, FailureException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException { public void dynamicCG(File javaJarPath, String mainClass, String... args) throws FileNotFoundException, IOException, ClassNotFoundException, InvalidClassFileException, FailureException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException {
File F = TemporaryFile.streamToFile(new File("test_jar.jar"), new FileInputStream(javaJarPath)); File F;
try (final FileInputStream in = new FileInputStream(javaJarPath)) {
F = TemporaryFile.streamToFile(new File("test_jar.jar"), in);
}
F.deleteOnExit(); F.deleteOnExit();
instrument(F.getAbsolutePath()); instrument(F.getAbsolutePath());
run(mainClass.substring(1).replace('/', '.'), "LibraryExclusions.txt", args); run(mainClass.substring(1).replace('/', '.'), "LibraryExclusions.txt", args);

View File

@ -73,7 +73,9 @@ public class DexFileModule implements Module {
public static DexFileModule make(File f) throws IllegalArgumentException, IOException { public static DexFileModule make(File f) throws IllegalArgumentException, IOException {
if (f.getName().endsWith("jar")) { if (f.getName().endsWith("jar")) {
return new DexFileModule(new JarFile(f)); try (final JarFile jar = new JarFile(f)) {
return new DexFileModule(jar);
}
} else { } else {
return new DexFileModule(f); return new DexFileModule(f);
} }

View File

@ -39,8 +39,9 @@ public class AndroidAnalysisScope {
scope = AnalysisScope.createJavaAnalysisScope(); scope = AnalysisScope.createJavaAnalysisScope();
File exclusionsFile = new File(exclusions); File exclusionsFile = new File(exclusions);
InputStream fs = exclusionsFile.exists()? new FileInputStream(exclusionsFile): FileProvider.class.getClassLoader().getResourceAsStream(exclusionsFile.getName()); try (final InputStream fs = exclusionsFile.exists()? new FileInputStream(exclusionsFile): FileProvider.class.getClassLoader().getResourceAsStream(exclusionsFile.getName())) {
scope.setExclusions(new FileOfClasses(fs)); scope.setExclusions(new FileOfClasses(fs));
}
scope.setLoaderImpl(ClassLoaderReference.Primordial, scope.setLoaderImpl(ClassLoaderReference.Primordial,
"com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl"); "com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl");
@ -50,7 +51,9 @@ public class AndroidAnalysisScope {
scope.addToScope(ClassLoaderReference.Primordial, DexFileModule.make(new File(al))); scope.addToScope(ClassLoaderReference.Primordial, DexFileModule.make(new File(al)));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
scope.addToScope(ClassLoaderReference.Primordial, new JarFileModule(new JarFile(new File(al)))); try (final JarFile jar = new JarFile(new File(al))) {
scope.addToScope(ClassLoaderReference.Primordial, new JarFileModule(jar));
}
} }
} }

View File

@ -101,8 +101,8 @@ public class AndroidManifestXMLReader {
if (xmlFile == null) { if (xmlFile == null) {
throw new IllegalArgumentException("xmlFile may not be null"); throw new IllegalArgumentException("xmlFile may not be null");
} }
try { try (final FileInputStream in = new FileInputStream(xmlFile)) {
readXML(new FileInputStream(xmlFile)); readXML(in);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new IllegalStateException("Exception was thrown"); throw new IllegalStateException("Exception was thrown");

View File

@ -37,6 +37,7 @@
*/ */
package com.ibm.wala.cast.java.test; package com.ibm.wala.cast.java.test;
import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -50,8 +51,14 @@ public class JDTJavaIRTests extends JavaIRTests {
public static final String PROJECT_ZIP = "test_project.zip"; public static final String PROJECT_ZIP = "test_project.zip";
public static final ZippedProjectData PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP); public static final ZippedProjectData PROJECT;
static {
try {
PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final ZippedProjectData project; private final ZippedProjectData project;
public JDTJavaIRTests() { public JDTJavaIRTests() {

View File

@ -10,6 +10,8 @@
*******************************************************************************/ *******************************************************************************/
package com.ibm.wala.ide.jsdt.tests; package com.ibm.wala.ide.jsdt.tests;
import java.io.IOException;
import com.ibm.wala.ide.tests.util.EclipseTestUtil.ZippedProjectData; import com.ibm.wala.ide.tests.util.EclipseTestUtil.ZippedProjectData;
public class JSProjectScopeTest extends AbstractJSProjectScopeTest { public class JSProjectScopeTest extends AbstractJSProjectScopeTest {
@ -18,7 +20,14 @@ public class JSProjectScopeTest extends AbstractJSProjectScopeTest {
public static final String PROJECT_ZIP = "test_js_project.zip"; public static final String PROJECT_ZIP = "test_js_project.zip";
public static final ZippedProjectData PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP); public static final ZippedProjectData PROJECT;
static {
try {
PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public JSProjectScopeTest() { public JSProjectScopeTest() {
super(PROJECT); super(PROJECT);

View File

@ -41,14 +41,14 @@ public class EclipseTestUtil {
public final String projectName; public final String projectName;
public final String zipFileName; public final String zipFileName;
public ZippedProjectData(Plugin sourcePlugin, String projectName, String zipFileName) { public ZippedProjectData(Plugin sourcePlugin, String projectName, String zipFileName) throws IOException {
this.sourcePlugin = sourcePlugin; this.sourcePlugin = sourcePlugin;
this.projectName = projectName; this.projectName = projectName;
this.zipFileName = zipFileName; this.zipFileName = zipFileName;
open(); open();
} }
private void open() { private void open() throws IOException {
importZippedProject(sourcePlugin, projectName, zipFileName, new NullProgressMonitor()); importZippedProject(sourcePlugin, projectName, zipFileName, new NullProgressMonitor());
} }
@ -57,11 +57,12 @@ public class EclipseTestUtil {
} }
} }
public static void importZippedProject(Plugin plugin, String projectName, String zipFileName, IProgressMonitor monitor) { public static void importZippedProject(Plugin plugin, String projectName, String zipFileName, IProgressMonitor monitor) throws IOException {
ZipFile zipFile = getZipFile(plugin, zipFileName); try (final ZipFile zipFile = getZipFile(plugin, zipFileName)) {
createOpenProject(projectName); createOpenProject(projectName);
importZipfile(projectName, zipFile, monitor); importZipfile(projectName, zipFile, monitor);
} }
}
public static void createOpenProject(String projectName) { public static void createOpenProject(String projectName) {
IWorkspaceRoot root = getWorkspace(); IWorkspaceRoot root = getWorkspace();

View File

@ -60,9 +60,10 @@ abstract public class EclipseProjectAnalysisEngine<P, I extends InstanceKey> ext
ePath = createProjectPath(project); ePath = createProjectPath(project);
super.scope = ePath.toAnalysisScope(makeAnalysisScope()); super.scope = ePath.toAnalysisScope(makeAnalysisScope());
if (getExclusionsFile() != null) { if (getExclusionsFile() != null) {
InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile()); try (final InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile())) {
scope.setExclusions(new FileOfClasses(is)); scope.setExclusions(new FileOfClasses(is));
} }
}
} catch (CoreException e) { } catch (CoreException e) {
assert false : e.getMessage(); assert false : e.getMessage();
} }

View File

@ -75,7 +75,9 @@ public class EclipseFileProvider extends FileProvider {
IPath path = new Path(fileName); IPath path = new Path(fileName);
if (workspaceRoot_getFile.invoke(workspaceRoot, path) != null) { if (workspaceRoot_getFile.invoke(workspaceRoot, path) != null) {
return new JarFileModule(new JarFile(fileName, false)); try (final JarFile jar = new JarFile(fileName, false)) {
return new JarFileModule(jar);
}
} }
} catch (Exception e) { } catch (Exception e) {
} }
@ -105,7 +107,10 @@ public class EclipseFileProvider extends FileProvider {
*/ */
private JarFileModule getFromPlugin(Plugin p, String fileName) throws IOException { private JarFileModule getFromPlugin(Plugin p, String fileName) throws IOException {
URL url = getFileURLFromPlugin(p, fileName); URL url = getFileURLFromPlugin(p, fileName);
return (url == null) ? null : new JarFileModule(new JarFile(filePathFromURL(url))); if (url == null) return null;
try (final JarFile jar = new JarFile(filePathFromURL(url))) {
return new JarFileModule(jar);
}
} }
/** /**

View File

@ -312,26 +312,15 @@ public class AndroidAnalysisContext {
private static XMLMethodSummaryReader loadMethodSummaries( private static XMLMethodSummaryReader loadMethodSummaries(
AnalysisScope scope, InputStream xmlIStream) AnalysisScope scope, InputStream xmlIStream)
throws FileNotFoundException { throws FileNotFoundException {
InputStream s = xmlIStream; try (InputStream s = xmlIStream != null ? xmlIStream :
XMLMethodSummaryReader summary = null; AndroidAnalysisContext.class.getClassLoader()
try {
if (null == s) {
s = AndroidAnalysisContext.class.getClassLoader()
.getResourceAsStream( .getResourceAsStream(
pathToSpec + File.separator + methodSpec); pathToSpec + File.separator + methodSpec)) {
} return new XMLMethodSummaryReader(s, scope);
summary = new XMLMethodSummaryReader(s, scope);
} finally {
try {
if (null != s) {
s.close();
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} return null;
return summary;
} }
/** /**

View File

@ -150,7 +150,9 @@ public class CGAnalysisContext<E extends ISSABasicBlock> {
SSAPropagationCallGraphBuilder cgb; SSAPropagationCallGraphBuilder cgb;
if (null != options.getSummariesURI()) { if (null != options.getSummariesURI()) {
extraSummaries.add(new FileInputStream(new File(options.getSummariesURI()))); try (final FileInputStream in = new FileInputStream(new File(options.getSummariesURI()))) {
extraSummaries.add(in);
}
} }
cgb = AndroidAnalysisContext.makeZeroCFABuilder(analysisOptions, cache, cha, scope, cgb = AndroidAnalysisContext.makeZeroCFABuilder(analysisOptions, cache, cha, scope,

View File

@ -44,8 +44,7 @@ public class AddBytecodeDebug {
for (int i = 0; i < 1; i++) { for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter(true); instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", false)); try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args); args = instrumenter.parseStandardArgs(args);
instrumenter.setPassUnmodifiedClasses(true); instrumenter.setPassUnmodifiedClasses(true);
instrumenter.beginTraversal(); instrumenter.beginTraversal();
@ -56,6 +55,7 @@ public class AddBytecodeDebug {
instrumenter.close(); instrumenter.close();
} }
} }
}
private static void doClass(final ClassInstrumenter ci, Writer w) throws Exception { private static void doClass(final ClassInstrumenter ci, Writer w) throws Exception {
final String className = ci.getReader().getName(); final String className = ci.getReader().getName();

View File

@ -62,7 +62,7 @@ public class Bench {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) { for (int i = 0; i < 1; i++) {
Writer w = new BufferedWriter(new FileWriter("report", false)); try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args); args = instrumenter.parseStandardArgs(args);
if (args.length > 0) { if (args.length > 0) {
@ -80,6 +80,7 @@ public class Bench {
while ((ci = instrumenter.nextClass()) != null) { while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w); doClass(ci, w);
} }
}
instrumenter.close(); instrumenter.close();
} }
} }

View File

@ -59,7 +59,7 @@ public class Mangler {
for (int i = 0; i < 1; i++) { for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter(true); instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", false)); try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args); args = instrumenter.parseStandardArgs(args);
int seed; int seed;
@ -67,7 +67,6 @@ public class Mangler {
seed = Integer.parseInt(args[0]); seed = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
System.err.println("Invalid number: " + args[0]); System.err.println("Invalid number: " + args[0]);
w.close();
return; return;
} }
@ -79,6 +78,7 @@ public class Mangler {
while ((ci = instrumenter.nextClass()) != null) { while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w, r); doClass(ci, w, r);
} }
}
instrumenter.close(); instrumenter.close();
} }
} }

View File

@ -73,7 +73,7 @@ public class OfflineDynamicCallGraph {
public static void main(String[] args) throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException { public static void main(String[] args) throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException {
OfflineInstrumenter instrumenter; OfflineInstrumenter instrumenter;
ClassInstrumenter ci; ClassInstrumenter ci;
Writer w = new BufferedWriter(new FileWriter("report", false)); try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
for(int i = 0; i < args.length - 1; i++) { for(int i = 0; i < args.length - 1; i++) {
if ("--runtime".equals(args[i])) { if ("--runtime".equals(args[i])) {
@ -113,6 +113,7 @@ public class OfflineDynamicCallGraph {
instrumenter.outputModifiedClass(ci, cw); instrumenter.outputModifiedClass(ci, cw);
} }
} }
}
instrumenter.close(); instrumenter.close();
} }

View File

@ -67,8 +67,8 @@ public class Runtime {
}; };
private Runtime(String fileName, String filterFileName, String policyClassName) { private Runtime(String fileName, String filterFileName, String policyClassName) {
try { try (final FileInputStream in = new FileInputStream(filterFileName)) {
filter = new FileOfClasses(new FileInputStream(filterFileName)); filter = new FileOfClasses(in);
} catch (Exception e) { } catch (Exception e) {
filter = null; filter = null;
} }

View File

@ -191,8 +191,8 @@ public class AddSerialVersion {
if (args[i] == null) { if (args[i] == null) {
throw new IllegalArgumentException("args[" + i + "] is null"); throw new IllegalArgumentException("args[" + i + "] is null");
} }
try { try (final FileInputStream in = new FileInputStream(args[i])) {
byte[] data = Util.readFully(new FileInputStream(args[i])); byte[] data = Util.readFully(in);
ClassReader r = new ClassReader(data); ClassReader r = new ClassReader(data);
System.out.println(Util.makeClass(r.getName()) + ": serialVersionUID = " + computeSerialVersionUID(r)); System.out.println(Util.makeClass(r.getName()) + ": serialVersionUID = " + computeSerialVersionUID(r));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {

View File

@ -57,7 +57,7 @@ public class BatchVerifier {
} }
} }
PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter("report", false))); try (final PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter("report", false)))) {
oi.beginTraversal(); oi.beginTraversal();
ClassInstrumenter ci; ClassInstrumenter ci;
@ -70,6 +70,7 @@ public class BatchVerifier {
while ((ci = oi.nextClass()) != null) { while ((ci = oi.nextClass()) != null) {
doClass(ci.getReader(), w); doClass(ci.getReader(), w);
} }
}
oi.close(); oi.close();

View File

@ -55,8 +55,7 @@ public class BootstrapDumper {
assert f.exists(); assert f.exists();
urls[i-1] = f.toURI().toURL(); urls[i-1] = f.toURI().toURL();
} }
URLClassLoader image = URLClassLoader.newInstance(urls, BootstrapDumper.class.getClassLoader().getParent()); try (final URLClassLoader image = URLClassLoader.newInstance(urls, BootstrapDumper.class.getClassLoader().getParent())) {
System.err.println(image); System.err.println(image);
ClassInstrumenter ci; ClassInstrumenter ci;
@ -68,6 +67,7 @@ public class BootstrapDumper {
w.flush(); w.flush();
} }
} }
}
oi.close(); oi.close();
} }

View File

@ -53,7 +53,7 @@ public class MethodTracer {
for (int i = 0; i < 1; i++) { for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter(true); instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", false)); try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
instrumenter.parseStandardArgs(args); instrumenter.parseStandardArgs(args);
instrumenter.setPassUnmodifiedClasses(false); instrumenter.setPassUnmodifiedClasses(false);
@ -62,6 +62,7 @@ public class MethodTracer {
while ((ci = instrumenter.nextClass()) != null) { while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w); doClass(ci, w);
} }
}
instrumenter.close(); instrumenter.close();
} }
} }

View File

@ -127,6 +127,7 @@ public abstract class OfflineInstrumenterBase {
} }
@Override @Override
@SuppressWarnings("resource")
public InputStream open() throws IOException { public InputStream open() throws IOException {
JarFile cachedJar = openCachedJar(file); JarFile cachedJar = openCachedJar(file);
return cachedJar.getInputStream(cachedJar.getEntry(name)); return cachedJar.getInputStream(cachedJar.getEntry(name));
@ -150,6 +151,7 @@ public abstract class OfflineInstrumenterBase {
/** /**
* Get the underlying ZipEntry corresponding to this resource. * Get the underlying ZipEntry corresponding to this resource.
*/ */
@SuppressWarnings("resource")
public ZipEntry getEntry() throws IOException { public ZipEntry getEntry() throws IOException {
JarFile cachedJar = openCachedJar(file); JarFile cachedJar = openCachedJar(file);
return cachedJar.getEntry(name); return cachedJar.getEntry(name);
@ -454,7 +456,9 @@ public abstract class OfflineInstrumenterBase {
throw new IllegalStateException("Output file was not set"); throw new IllegalStateException("Output file was not set");
} }
outputJar = new JarOutputStream(new FileOutputStream(outputFile)); @SuppressWarnings("resource")
final FileOutputStream out = new FileOutputStream(outputFile);
outputJar = new JarOutputStream(out);
} }
} }

View File

@ -83,7 +83,9 @@ public class StringTable extends Table<String> implements Cloneable {
if (f == null) { if (f == null) {
throw new IllegalArgumentException("null f"); throw new IllegalArgumentException("null f");
} }
return readFromStream(new FileInputStream(f), comment); try (final FileInputStream in = new FileInputStream(f)) {
return readFromStream(in, comment);
}
} }
/** /**