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