1 /*
   2  * Copyright (c) 2003, 2011, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;
  27 
  28 import java.util.ArrayList;
  29 import java.util.List;
  30 
  31 /**
  32  * Instances of the file descriptor class serve as an opaque handle
  33  * to the underlying machine-specific structure representing an
  34  * open file, an open socket, or another source or sink of bytes.
  35  * The main practical use for a file descriptor is to create a
  36  * {@link FileInputStream} or {@link FileOutputStream} to contain it.
  37  *
  38  * <p>Applications should not create their own file descriptors.
  39  *
  40  * @author  Pavani Diwanji
  41  * @since   JDK1.0
  42  */
  43 public final class FileDescriptor {
  44 
  45     private int fd;
  46 
  47     private long handle;
  48 
  49     private Closeable parent;
  50     private List<Closeable> otherParents;
  51     private boolean closed;
  52 
  53     /**
  54      * Constructs an (invalid) FileDescriptor
  55      * object.
  56      */
  57     public /**/ FileDescriptor() {
  58         fd = -1;
  59         handle = -1;
  60     }
  61 
  62     static {
  63         initIDs();
  64     }
  65 
  66     // Set up JavaIOFileDescriptorAccess in SharedSecrets
  67     static {
  68         sun.misc.SharedSecrets.setJavaIOFileDescriptorAccess(
  69             new sun.misc.JavaIOFileDescriptorAccess() {
  70                 public void set(FileDescriptor obj, int fd) {
  71                     obj.fd = fd;
  72                 }
  73 
  74                 public int get(FileDescriptor obj) {
  75                     return obj.fd;
  76                 }
  77 
  78                 public void setHandle(FileDescriptor obj, long handle) {
  79                     obj.handle = handle;
  80                 }
  81 
  82                 public long getHandle(FileDescriptor obj) {
  83                     return obj.handle;
  84                 }
  85             }
  86         );
  87     }
  88 
  89     /**
  90      * A handle to the standard input stream. Usually, this file
  91      * descriptor is not used directly, but rather via the input stream
  92      * known as {@code System.in}.
  93      *
  94      * @see     java.lang.System#in
  95      */
  96     public static final FileDescriptor in = standardStream(0);
  97 
  98     /**
  99      * A handle to the standard output stream. Usually, this file
 100      * descriptor is not used directly, but rather via the output stream
 101      * known as {@code System.out}.
 102      * @see     java.lang.System#out
 103      */
 104     public static final FileDescriptor out = standardStream(1);
 105 
 106     /**
 107      * A handle to the standard error stream. Usually, this file
 108      * descriptor is not used directly, but rather via the output stream
 109      * known as {@code System.err}.
 110      *
 111      * @see     java.lang.System#err
 112      */
 113     public static final FileDescriptor err = standardStream(2);
 114 
 115     /**
 116      * Tests if this file descriptor object is valid.
 117      *
 118      * @return  {@code true} if the file descriptor object represents a
 119      *          valid, open file, socket, or other active I/O connection;
 120      *          {@code false} otherwise.
 121      */
 122     public boolean valid() {
 123         return ((handle != -1) || (fd != -1));
 124     }
 125 
 126     /**
 127      * Force all system buffers to synchronize with the underlying
 128      * device.  This method returns after all modified data and
 129      * attributes of this FileDescriptor have been written to the
 130      * relevant device(s).  In particular, if this FileDescriptor
 131      * refers to a physical storage medium, such as a file in a file
 132      * system, sync will not return until all in-memory modified copies
 133      * of buffers associated with this FileDesecriptor have been
 134      * written to the physical medium.
 135      *
 136      * sync is meant to be used by code that requires physical
 137      * storage (such as a file) to be in a known state  For
 138      * example, a class that provided a simple transaction facility
 139      * might use sync to ensure that all changes to a file caused
 140      * by a given transaction were recorded on a storage medium.
 141      *
 142      * sync only affects buffers downstream of this FileDescriptor.  If
 143      * any in-memory buffering is being done by the application (for
 144      * example, by a BufferedOutputStream object), those buffers must
 145      * be flushed into the FileDescriptor (for example, by invoking
 146      * OutputStream.flush) before that data will be affected by sync.
 147      *
 148      * @exception SyncFailedException
 149      *        Thrown when the buffers cannot be flushed,
 150      *        or because the system cannot guarantee that all the
 151      *        buffers have been synchronized with physical media.
 152      * @since     JDK1.1
 153      */
 154     public native void sync() throws SyncFailedException;
 155 
 156     /* This routine initializes JNI field offsets for the class */
 157     private static native void initIDs();
 158 
 159     private static native long set(int d);
 160 
 161     private static FileDescriptor standardStream(int fd) {
 162         FileDescriptor desc = new FileDescriptor();
 163         desc.handle = set(fd);
 164         return desc;
 165     }
 166 
 167     /*
 168      * Package private methods to track referents.
 169      * If multiple streams point to the same FileDescriptor, we cycle
 170      * through the list of all referents and call close()
 171      */
 172 
 173     /**
 174      * Attach a Closeable to this FD for tracking.
 175      * parent reference is added to otherParents when
 176      * needed to make closeAll simpler.
 177      */
 178     synchronized void attach(Closeable c) {
 179         if (parent == null) {
 180             // first caller gets to do this
 181             parent = c;
 182         } else if (otherParents == null) {
 183             otherParents = new ArrayList<>();
 184             otherParents.add(parent);
 185             otherParents.add(c);
 186         } else {
 187             otherParents.add(c);
 188         }
 189     }
 190 
 191     /**
 192      * Cycle through all Closeables sharing this FD and call
 193      * close() on each one.
 194      *
 195      * The caller closeable gets to call close0().
 196      */
 197     @SuppressWarnings("try")
 198     synchronized void closeAll(Closeable releaser) throws IOException {
 199         if (!closed) {
 200             closed = true;
 201             IOException ioe = null;
 202             try (Closeable c = releaser) {
 203                 if (otherParents != null) {
 204                     for (Closeable referent : otherParents) {
 205                         try {
 206                             referent.close();
 207                         } catch(IOException x) {
 208                             if (ioe == null) {
 209                                 ioe = x;
 210                             } else {
 211                                 ioe.addSuppressed(x);
 212                             }
 213                         }
 214                     }
 215                 }
 216             } catch(IOException ex) {
 217                 /*
 218                  * If releaser close() throws IOException
 219                  * add other exceptions as suppressed.
 220                  */
 221                 if (ioe != null)
 222                     ex.addSuppressed(ioe);
 223                 ioe = ex;
 224             } finally {
 225                 if (ioe != null)
 226                     throw ioe;
 227             }
 228         }
 229     }
 230 }