1 /* 2 * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /** 25 * 26 * @test 27 * @modules java.base/java.io:open 28 * @bug 6524062 29 * @summary Test to ensure that FOS.finalize() invokes the close() method as per 30 * the specification. 31 * @run main/othervm UnreferencedFOSClosesFd 32 */ 33 import java.io.File; 34 import java.io.FileDescriptor; 35 import java.io.FileNotFoundException; 36 import java.io.FileOutputStream; 37 import java.io.IOException; 38 import java.lang.management.ManagementFactory; 39 import java.lang.management.OperatingSystemMXBean; 40 import java.lang.ref.Reference; 41 import java.lang.ref.ReferenceQueue; 42 import java.lang.ref.WeakReference; 43 import java.lang.reflect.Field; 44 import java.util.HashSet; 45 import java.util.concurrent.atomic.AtomicInteger; 46 47 import com.sun.management.UnixOperatingSystemMXBean; 48 49 public class UnreferencedFOSClosesFd { 50 51 enum CleanupType { 52 CLOSE, // Cleanup is handled via calling close 53 CLEANER} // Cleanup is handled via Cleaner 54 55 static final String FILE_NAME = "empty.txt"; 56 57 /** 58 * Subclass w/ no overrides; not finalize or close. 59 * Cleanup should be via the Cleaner (not close). 60 */ 61 public static class StreamOverrides extends FileOutputStream { 62 63 protected final AtomicInteger closeCounter; 64 65 public StreamOverrides(String name) throws FileNotFoundException { 66 super(name); 67 closeCounter = new AtomicInteger(0); 68 } 69 70 final AtomicInteger closeCounter() { 71 return closeCounter; 72 } 73 } 74 75 /** 76 * Subclass overrides close. 77 * Cleanup should be via AltFinalizer calling close(). 78 */ 79 public static class StreamOverridesClose extends StreamOverrides { 80 81 public StreamOverridesClose(String name) throws FileNotFoundException { 82 super(name); 83 } 84 85 public void close() throws IOException { 86 closeCounter.incrementAndGet(); 87 super.close(); 88 } 89 } 90 91 /** 92 * Subclass overrides finalize and close. 93 * Cleanup should be via the Cleaner (not close). 94 */ 95 public static class StreamOverridesFinalize extends StreamOverrides { 96 97 public StreamOverridesFinalize(String name) throws FileNotFoundException { 98 super(name); 99 } 100 101 @SuppressWarnings({"deprecation","removal"}) 102 protected void finalize() throws IOException { 103 super.finalize(); 104 } 105 } 106 107 /** 108 * Subclass overrides finalize and close. 109 * Cleanup should be via AltFinalizer calling close(). 110 */ 111 public static class StreamOverridesFinalizeClose extends StreamOverridesClose { 112 113 public StreamOverridesFinalizeClose(String name) throws FileNotFoundException { 114 super(name); 115 } 116 117 @SuppressWarnings({"deprecation","removal"}) 118 protected void finalize() throws IOException { 119 super.finalize(); 120 } 121 } 122 123 /** 124 * Main runs each test case and reports number of failures. 125 */ 126 public static void main(String argv[]) throws Exception { 127 128 129 130 File inFile = new File(System.getProperty("test.dir", "."), FILE_NAME); 131 inFile.createNewFile(); 132 inFile.deleteOnExit(); 133 134 String name = inFile.getPath(); 135 136 long fdCount0 = getFdCount(); 137 System.out.printf("initial count of open file descriptors: %d%n", fdCount0); 138 139 int failCount = 0; 140 failCount += test(new FileOutputStream(name), CleanupType.CLEANER); 141 142 failCount += test(new StreamOverrides(name), CleanupType.CLEANER); 143 144 failCount += test(new StreamOverridesClose(name), CleanupType.CLOSE); 145 146 failCount += test(new StreamOverridesFinalize(name), CleanupType.CLEANER); 147 148 failCount += test(new StreamOverridesFinalizeClose(name), CleanupType.CLOSE); 149 150 if (failCount > 0) { 151 throw new AssertionError("Failed test count: " + failCount); 152 } 153 154 // Check the final count of open file descriptors 155 long fdCount = getFdCount(); 156 System.out.printf("final count of open file descriptors: %d%n", fdCount); 157 if (fdCount != fdCount0) { 158 throw new AssertionError("raw fd count wrong: expected: " + fdCount0 159 + ", actual: " + fdCount); 160 } 161 } 162 163 // Get the count of open file descriptors, or -1 if not available 164 private static long getFdCount() { 165 OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean(); 166 return (mxBean instanceof UnixOperatingSystemMXBean) 167 ? ((UnixOperatingSystemMXBean) mxBean).getOpenFileDescriptorCount() 168 : -1L; 169 } 170 171 private static int test(FileOutputStream fos, CleanupType cleanType) throws Exception { 172 173 try { 174 System.out.printf("%nTesting %s%n", fos.getClass().getName()); 175 176 // Prepare to wait for FOS to be reclaimed 177 ReferenceQueue<Object> queue = new ReferenceQueue<>(); 178 HashSet<Reference<?>> pending = new HashSet<>(); 179 WeakReference<FileOutputStream> msWeak = new WeakReference<>(fos, queue); 180 pending.add(msWeak); 181 182 FileDescriptor fd = fos.getFD(); 183 WeakReference<FileDescriptor> fdWeak = new WeakReference<>(fd, queue); 184 pending.add(fdWeak); 185 186 Field fdField = FileDescriptor.class.getDeclaredField("fd"); 187 fdField.setAccessible(true); 188 int ffd = fdField.getInt(fd); 189 190 Field altFinalizerField = FileOutputStream.class.getDeclaredField("altFinalizer"); 191 altFinalizerField.setAccessible(true); 192 Object altFinalizer = altFinalizerField.get(fos); 193 if ((altFinalizer != null) ^ (cleanType == CleanupType.CLOSE)) { 194 throw new RuntimeException("Unexpected AltFinalizer: " + altFinalizer 195 + ", for " + cleanType); 196 } 197 198 Field cleanupField = FileDescriptor.class.getDeclaredField("cleanup"); 199 cleanupField.setAccessible(true); 200 Object cleanup = cleanupField.get(fd); 201 System.out.printf(" cleanup: %s, alt: %s, ffd: %d, cf: %s%n", 202 cleanup, altFinalizer, ffd, cleanupField); 203 if ((cleanup != null) ^ (cleanType == CleanupType.CLEANER)) { 204 throw new Exception("unexpected cleanup: " 205 + cleanup + ", for " + cleanType); 206 } 207 if (cleanup != null) { 208 WeakReference<Object> cleanupWeak = new WeakReference<>(cleanup, queue); 209 pending.add(cleanupWeak); 210 System.out.printf(" fdWeak: %s%n msWeak: %s%n cleanupWeak: %s%n", 211 fdWeak, msWeak, cleanupWeak); 212 } 213 if (altFinalizer != null) { 214 WeakReference<Object> altFinalizerWeak = new WeakReference<>(altFinalizer, queue); 215 pending.add(altFinalizerWeak); 216 System.out.printf(" fdWeak: %s%n msWeak: %s%n altFinalizerWeak: %s%n", 217 fdWeak, msWeak, altFinalizerWeak); 218 } 219 220 AtomicInteger closeCounter = fos instanceof StreamOverrides 221 ? ((StreamOverrides) fos).closeCounter() : null; 222 223 Reference<?> r; 224 while (((r = queue.remove(1000L)) != null) 225 || !pending.isEmpty()) { 226 System.out.printf(" r: %s, pending: %d%n", 227 r, pending.size()); 228 if (r != null) { 229 pending.remove(r); 230 } else { 231 fos = null; 232 fd = null; 233 cleanup = null; 234 altFinalizer = null; 235 System.gc(); // attempt to reclaim them 236 } 237 } 238 Reference.reachabilityFence(fd); 239 Reference.reachabilityFence(fos); 240 Reference.reachabilityFence(cleanup); 241 Reference.reachabilityFence(altFinalizer); 242 243 // Confirm the correct number of calls to close depending on the cleanup type 244 switch (cleanType) { 245 case CLEANER: 246 if (closeCounter != null && closeCounter.get() > 0) { 247 throw new RuntimeException("Close should not have been called: count: " 248 + closeCounter); 249 } 250 break; 251 case CLOSE: 252 if (closeCounter == null || closeCounter.get() == 0) { 253 throw new RuntimeException("Close should have been called: count: 0"); 254 } 255 break; 256 } 257 } catch (Exception ex) { 258 ex.printStackTrace(System.out); 259 return 1; 260 } 261 return 0; 262 } 263 }