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