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  * @library /test/lib
  29  * @build jdk.test.lib.util.FileUtils UnreferencedFOSClosesFd
  30  * @bug 6524062
  31  * @summary Test to ensure that FOS.finalize() invokes the close() method as per
  32  * the specification.
  33  * @run main/othervm UnreferencedFOSClosesFd
  34  */
  35 import java.io.File;
  36 import java.io.FileDescriptor;
  37 import java.io.FileNotFoundException;
  38 import java.io.FileOutputStream;
  39 import java.io.IOException;
  40 import java.lang.management.ManagementFactory;
  41 import java.lang.management.OperatingSystemMXBean;
  42 import java.lang.ref.Reference;
  43 import java.lang.ref.ReferenceQueue;
  44 import java.lang.ref.WeakReference;
  45 import java.lang.reflect.Field;
  46 import java.nio.file.Path;
  47 import java.util.ArrayDeque;
  48 import java.util.HashSet;
  49 import java.util.concurrent.atomic.AtomicInteger;
  50 
  51 import com.sun.management.UnixOperatingSystemMXBean;
  52 
  53 import jdk.test.lib.util.FileUtils;
  54 
  55 public class UnreferencedFOSClosesFd {
  56 
  57     enum CleanupType {
  58         CLOSE,      // Cleanup is handled via calling close
  59         CLEANER}    // Cleanup is handled via Cleaner
  60 
  61     static final String FILE_NAME = "empty.txt";
  62 
  63     /**
  64      * Subclass w/ no overrides; not finalize or close.
  65      * Cleanup should be via the Cleaner (not close).
  66      */
  67     public static class StreamOverrides extends FileOutputStream {
  68 
  69         protected final AtomicInteger closeCounter;
  70 
  71         public StreamOverrides(String name) throws FileNotFoundException {
  72             super(name);
  73             closeCounter = new AtomicInteger(0);
  74         }
  75 
  76         final AtomicInteger closeCounter() {
  77             return closeCounter;
  78         }
  79     }
  80 
  81     /**
  82      * Subclass overrides close.
  83      * Cleanup should be via AltFinalizer calling close().
  84      */
  85     public static class StreamOverridesClose extends StreamOverrides {
  86 
  87         public StreamOverridesClose(String name) throws FileNotFoundException {
  88             super(name);
  89         }
  90 
  91         public void close() throws IOException {
  92             closeCounter.incrementAndGet();
  93             super.close();
  94         }
  95     }
  96 
  97     /**
  98      * Subclass overrides finalize and close.
  99      * Cleanup should be via the Cleaner (not close).
 100      */
 101     public static class StreamOverridesFinalize extends StreamOverrides {
 102 
 103         public StreamOverridesFinalize(String name) throws FileNotFoundException {
 104             super(name);
 105         }
 106 
 107         @SuppressWarnings({"deprecation","removal"})
 108         protected void finalize() throws IOException {
 109             super.finalize();
 110         }
 111     }
 112 
 113     /**
 114      * Subclass overrides finalize and close.
 115      * Cleanup should be via AltFinalizer calling close().
 116      */
 117     public static class StreamOverridesFinalizeClose extends StreamOverridesClose {
 118 
 119         public StreamOverridesFinalizeClose(String name) throws FileNotFoundException {
 120             super(name);
 121         }
 122 
 123         @SuppressWarnings({"deprecation","removal"})
 124         protected void finalize() throws IOException {
 125             super.finalize();
 126         }
 127     }
 128 
 129     /**
 130      * Main runs each test case and reports number of failures.
 131      */
 132     public static void main(String argv[]) throws Exception {
 133 
 134 
 135 
 136         File inFile = new File(System.getProperty("test.dir", "."), FILE_NAME);
 137         inFile.createNewFile();
 138         inFile.deleteOnExit();
 139 
 140         String name = inFile.getPath();
 141 
 142         FileUtils.listFileDescriptors(System.out);
 143         long fdCount0 = getFdCount();
 144 
 145         int failCount = 0;
 146         failCount += test(new FileOutputStream(name), CleanupType.CLEANER);
 147 
 148         failCount += test(new StreamOverrides(name), CleanupType.CLEANER);
 149 
 150         failCount += test(new StreamOverridesClose(name), CleanupType.CLOSE);
 151 
 152         failCount += test(new StreamOverridesFinalize(name), CleanupType.CLEANER);
 153 
 154         failCount += test(new StreamOverridesFinalizeClose(name), CleanupType.CLOSE);
 155 
 156         if (failCount > 0) {
 157             throw new AssertionError("Failed test count: " + failCount);
 158         }
 159 
 160         // Check the final count of open file descriptors
 161         long fdCount = getFdCount();
 162         if (fdCount != fdCount0) {
 163             System.out.printf("initial count of open file descriptors: %d%n", fdCount0);
 164             System.out.printf("final count of open file descriptors: %d%n", fdCount);
 165             FileUtils.listFileDescriptors(System.out);
 166         }
 167     }
 168 
 169     // Get the count of open file descriptors, or -1 if not available
 170     private static long getFdCount() {
 171         OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
 172         return  (mxBean instanceof UnixOperatingSystemMXBean)
 173                 ? ((UnixOperatingSystemMXBean) mxBean).getOpenFileDescriptorCount()
 174                 : -1L;
 175     }
 176 
 177     private static int test(FileOutputStream fos, CleanupType cleanType) throws Exception {
 178 
 179         try {
 180             System.out.printf("%nTesting %s%n", fos.getClass().getName());
 181 
 182             // Prepare to wait for FOS to be reclaimed
 183             ReferenceQueue<Object> queue = new ReferenceQueue<>();
 184             HashSet<Reference<?>> pending = new HashSet<>();
 185             WeakReference<FileOutputStream> msWeak = new WeakReference<>(fos, queue);
 186             pending.add(msWeak);
 187 
 188             FileDescriptor fd = fos.getFD();
 189             WeakReference<FileDescriptor> fdWeak = new WeakReference<>(fd, queue);
 190             pending.add(fdWeak);
 191 
 192             Field fdField = FileDescriptor.class.getDeclaredField("fd");
 193             fdField.setAccessible(true);
 194             int ffd = fdField.getInt(fd);
 195 
 196             Field altFinalizerField = FileOutputStream.class.getDeclaredField("altFinalizer");
 197             altFinalizerField.setAccessible(true);
 198             Object altFinalizer = altFinalizerField.get(fos);
 199             if ((altFinalizer != null) ^ (cleanType == CleanupType.CLOSE)) {
 200                 throw new RuntimeException("Unexpected AltFinalizer: " + altFinalizer
 201                         + ", for " + cleanType);
 202             }
 203 
 204             Field cleanupField = FileDescriptor.class.getDeclaredField("cleanup");
 205             cleanupField.setAccessible(true);
 206             Object cleanup = cleanupField.get(fd);
 207             System.out.printf("  cleanup: %s, alt: %s, ffd: %d, cf: %s%n",
 208                     cleanup, altFinalizer, ffd, cleanupField);
 209             if ((cleanup != null) ^ (cleanType == CleanupType.CLEANER)) {
 210                 throw new Exception("unexpected cleanup: "
 211                         + cleanup + ", for " + cleanType);
 212             }
 213             if (cleanup != null) {
 214                 WeakReference<Object> cleanupWeak = new WeakReference<>(cleanup, queue);
 215                 pending.add(cleanupWeak);
 216                 System.out.printf("    fdWeak: %s%n    msWeak: %s%n    cleanupWeak: %s%n",
 217                         fdWeak, msWeak, cleanupWeak);
 218             }
 219             if (altFinalizer != null) {
 220                 WeakReference<Object> altFinalizerWeak = new WeakReference<>(altFinalizer, queue);
 221                 pending.add(altFinalizerWeak);
 222                 System.out.printf("    fdWeak: %s%n    msWeak: %s%n    altFinalizerWeak: %s%n",
 223                         fdWeak, msWeak, altFinalizerWeak);
 224             }
 225 
 226             AtomicInteger closeCounter = fos instanceof StreamOverrides
 227                     ? ((StreamOverrides) fos).closeCounter() : null;
 228 
 229             Reference<?> r;
 230             while (((r = queue.remove(1000L)) != null)
 231                     || !pending.isEmpty()) {
 232                 System.out.printf("    r: %s, pending: %d%n",
 233                         r, pending.size());
 234                 if (r != null) {
 235                     pending.remove(r);
 236                 } else {
 237                     fos = null;
 238                     fd = null;
 239                     cleanup = null;
 240                     altFinalizer = null;
 241                     System.gc();  // attempt to reclaim them
 242                 }
 243             }
 244             Reference.reachabilityFence(fd);
 245             Reference.reachabilityFence(fos);
 246             Reference.reachabilityFence(cleanup);
 247             Reference.reachabilityFence(altFinalizer);
 248 
 249             // Confirm the correct number of calls to close depending on the cleanup type
 250             switch (cleanType) {
 251                 case CLEANER:
 252                     if (closeCounter != null && closeCounter.get() > 0) {
 253                         throw new RuntimeException("Close should not have been called: count: "
 254                                 + closeCounter);
 255                     }
 256                     break;
 257                 case CLOSE:
 258                     if (closeCounter == null || closeCounter.get() == 0) {
 259                         throw new RuntimeException("Close should have been called: count: 0");
 260                     }
 261                     break;
 262             }
 263         } catch (Exception ex) {
 264             ex.printStackTrace(System.out);
 265             return 1;
 266         }
 267         return 0;
 268     }
 269 }