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