1 /*
  2  * Copyright (c) 2003, 2023, 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 import java.util.Objects;
 31 
 32 import jdk.internal.access.JavaIOFileDescriptorAccess;
 33 import jdk.internal.access.SharedSecrets;
 34 import jdk.internal.misc.Blocker;
 35 import jdk.internal.ref.PhantomCleanable;
 36 
 37 /**
 38  * Instances of the file descriptor class serve as an opaque handle
 39  * to the underlying machine-specific structure representing an open
 40  * file, an open socket, or another source or sink of bytes.
 41  * The main practical use for a file descriptor is to create a
 42  * {@link FileInputStream} or {@link FileOutputStream} to contain it.
 43  * <p>
 44  * Applications should not create their own file descriptors.
 45  *
 46  * @author  Pavani Diwanji
 47  * @since   1.0
 48  */
 49 public final class FileDescriptor {
 50 
 51     private int fd;
 52 
 53     private long handle;
 54 
 55     private Closeable parent;
 56     private List<Closeable> otherParents;
 57     private boolean closed;
 58 
 59     /**
 60      * true, if file is opened for appending.
 61      */
 62     private boolean append;
 63 
 64     static {
 65         initIDs();
 66     }
 67 
 68     // Set up JavaIOFileDescriptorAccess in SharedSecrets
 69     static {
 70         SharedSecrets.setJavaIOFileDescriptorAccess(
 71                 new JavaIOFileDescriptorAccess() {
 72                     public void set(FileDescriptor fdo, int fd) {
 73                         fdo.set(fd);
 74                     }
 75 
 76                     public int get(FileDescriptor fdo) {
 77                         return fdo.fd;
 78                     }
 79 
 80                     public void setAppend(FileDescriptor fdo, boolean append) {
 81                         fdo.append = append;
 82                     }
 83 
 84                     public boolean getAppend(FileDescriptor fdo) {
 85                         return fdo.append;
 86                     }
 87 
 88                     public void close(FileDescriptor fdo) throws IOException {
 89                         fdo.close();
 90                     }
 91 
 92                     /* Register for a normal FileCleanable fd/handle cleanup. */
 93                     public void registerCleanup(FileDescriptor fdo) {
 94                         FileCleanable.register(fdo);
 95                     }
 96 
 97                     /* Register a custom PhantomCleanup. */
 98                     public void registerCleanup(FileDescriptor fdo,
 99                                                 PhantomCleanable<FileDescriptor> cleanup) {
100                         fdo.registerCleanup(cleanup);
101                     }
102 
103                     public void unregisterCleanup(FileDescriptor fdo) {
104                         fdo.unregisterCleanup();
105                     }
106 
107                     public void setHandle(FileDescriptor fdo, long handle) {
108                         fdo.setHandle(handle);
109                     }
110 
111                     public long getHandle(FileDescriptor fdo) {
112                         return fdo.handle;
113                     }
114                 }
115         );
116     }
117 
118     /**
119      * Cleanup in case FileDescriptor is not explicitly closed.
120      */
121     private PhantomCleanable<FileDescriptor> cleanup;
122 
123     /**
124      * Constructs an (invalid) FileDescriptor object.
125      * The fd or handle is set later.
126      */
127     public FileDescriptor() {
128         fd = -1;
129         handle = -1;
130     }
131 
132     /**
133      * Used for standard input, output, and error only.
134      * For Windows the corresponding handle is initialized.
135      * For Unix the append mode is cached.
136      * @param fd the raw fd number (0, 1, 2)
137      */
138     private FileDescriptor(int fd) {
139         this.fd = fd;
140         this.handle = getHandle(fd);
141         this.append = getAppend(fd);
142     }
143 
144     /**
145      * A handle to the standard input stream. Usually, this file
146      * descriptor is not used directly, but rather via the input stream
147      * known as {@code System.in}.
148      *
149      * @see     java.lang.System#in
150      */
151     public static final FileDescriptor in = new FileDescriptor(0);
152 
153     /**
154      * A handle to the standard output stream. Usually, this file
155      * descriptor is not used directly, but rather via the output stream
156      * known as {@code System.out}.
157      * @see     java.lang.System#out
158      */
159     public static final FileDescriptor out = new FileDescriptor(1);
160 
161     /**
162      * A handle to the standard error stream. Usually, this file
163      * descriptor is not used directly, but rather via the output stream
164      * known as {@code System.err}.
165      *
166      * @see     java.lang.System#err
167      */
168     public static final FileDescriptor err = new FileDescriptor(2);
169 
170     /**
171      * Tests if this file descriptor object is valid.
172      *
173      * @return  {@code true} if the file descriptor object represents a
174      *          valid, open file, socket, or other active I/O connection;
175      *          {@code false} otherwise.
176      */
177     public boolean valid() {
178         return (handle != -1) || (fd != -1);
179     }
180 
181     /**
182      * Force all system buffers to synchronize with the underlying
183      * device.  This method returns after all modified data and
184      * attributes of this FileDescriptor have been written to the
185      * relevant device(s).  In particular, if this FileDescriptor
186      * refers to a physical storage medium, such as a file in a file
187      * system, sync will not return until all in-memory modified copies
188      * of buffers associated with this FileDescriptor have been
189      * written to the physical medium.
190      *
191      * sync is meant to be used by code that requires physical
192      * storage (such as a file) to be in a known state  For
193      * example, a class that provided a simple transaction facility
194      * might use sync to ensure that all changes to a file caused
195      * by a given transaction were recorded on a storage medium.
196      *
197      * sync only affects buffers downstream of this FileDescriptor.  If
198      * any in-memory buffering is being done by the application (for
199      * example, by a BufferedOutputStream object), those buffers must
200      * be flushed into the FileDescriptor (for example, by invoking
201      * OutputStream.flush) before that data will be affected by sync.
202      *
203      * @throws    SyncFailedException
204      *        Thrown when the buffers cannot be flushed,
205      *        or because the system cannot guarantee that all the
206      *        buffers have been synchronized with physical media.
207      * @since     1.1
208      */
209     public void sync() throws SyncFailedException {
210         long comp = Blocker.begin();
211         try {
212             sync0();
213         } finally {
214             Blocker.end(comp);
215         }
216     }
217 
218     /* fsync/equivalent this file descriptor */
219     private native void sync0() throws SyncFailedException;
220 
221     /* This routine initializes JNI field offsets for the class */
222     private static native void initIDs();
223 
224     /*
225      * On Windows return the handle for the standard streams.
226      */
227     private static native long getHandle(int d);
228 
229     /**
230      * Returns true, if the file was opened for appending.
231      */
232     private static native boolean getAppend(int fd);
233 
234     /**
235      * Set the fd.
236      * Used on Unix and for sockets on Windows and Unix.
237      * If setting to -1, clear the cleaner.
238      * The {@link #registerCleanup} method should be called for new fds.
239      * @param fd the raw fd or -1 to indicate closed
240      */
241     synchronized void set(int fd) {
242         if (fd == -1 && cleanup != null) {
243             cleanup.clear();
244             cleanup = null;
245         }
246         this.fd = fd;
247     }
248 
249     /**
250      * Set the handle.
251      * Used on Windows for regular files.
252      * If setting to -1, clear the cleaner.
253      * The {@link #registerCleanup} method should be called for new handles.
254      * @param handle the handle or -1 to indicate closed
255      */
256     void setHandle(long handle) {
257         if (handle == -1 && cleanup != null) {
258             cleanup.clear();
259             cleanup = null;
260         }
261         this.handle = handle;
262     }
263 
264     /**
265      * Register a cleanup for the current handle.
266      * Used directly in java.io and indirectly via fdAccess.
267      * The cleanup should be registered after the handle is set in the FileDescriptor.
268      * @param cleanable a PhantomCleanable to register
269      */
270     synchronized void registerCleanup(PhantomCleanable<FileDescriptor> cleanable) {
271         Objects.requireNonNull(cleanable, "cleanable");
272         if (cleanup != null) {
273             cleanup.clear();
274         }
275         cleanup = cleanable;
276     }
277 
278     /**
279      * Unregister a cleanup for the current raw fd or handle.
280      * Used directly in java.io and indirectly via fdAccess.
281      * Normally {@link #close()} should be used except in cases where
282      * it is certain the caller will close the raw fd and the cleanup
283      * must not close the raw fd.  {@link #unregisterCleanup()} must be
284      * called before the raw fd is closed to prevent a race that makes
285      * it possible for the fd to be reallocated to another use and later
286      * the cleanup might be invoked.
287      */
288     synchronized void unregisterCleanup() {
289         if (cleanup != null) {
290             cleanup.clear();
291         }
292         cleanup = null;
293     }
294 
295     /**
296      * Close the raw file descriptor or handle, if it has not already been closed.
297      * The native code sets the fd and handle to -1.
298      * Clear the cleaner so the close does not happen twice.
299      * Package private to allow it to be used in java.io.
300      * @throws IOException if close fails
301      */
302     synchronized void close() throws IOException {
303         unregisterCleanup();
304         close0();
305     }
306 
307     /*
308      * Close the raw file descriptor or handle, if it has not already been closed
309      * and set the fd and handle to -1.
310      */
311     private native void close0() throws IOException;
312 
313     /*
314      * Package private methods to track referents.
315      * If multiple streams point to the same FileDescriptor, we cycle
316      * through the list of all referents and call close()
317      */
318 
319     /**
320      * Attach a Closeable to this FD for tracking.
321      * parent reference is added to otherParents when
322      * needed to make closeAll simpler.
323      */
324     synchronized void attach(Closeable c) {
325         if (parent == null) {
326             // first caller gets to do this
327             parent = c;
328         } else if (otherParents == null) {
329             otherParents = new ArrayList<>();
330             otherParents.add(parent);
331             otherParents.add(c);
332         } else {
333             otherParents.add(c);
334         }
335     }
336 
337     /**
338      * Cycle through all Closeables sharing this FD and call
339      * close() on each one.
340      *
341      * The caller closeable gets to call close0().
342      */
343     @SuppressWarnings("try")
344     synchronized void closeAll(Closeable releaser) throws IOException {
345         if (!closed) {
346             closed = true;
347             IOException ioe = null;
348             try (releaser) {
349                 if (otherParents != null) {
350                     for (Closeable referent : otherParents) {
351                         try {
352                             referent.close();
353                         } catch(IOException x) {
354                             if (ioe == null) {
355                                 ioe = x;
356                             } else {
357                                 ioe.addSuppressed(x);
358                             }
359                         }
360                     }
361                 }
362             } catch(IOException ex) {
363                 /*
364                  * If releaser close() throws IOException
365                  * add other exceptions as suppressed.
366                  */
367                 if (ioe != null)
368                     ex.addSuppressed(ioe);
369                 ioe = ex;
370             } finally {
371                 if (ioe != null)
372                     throw ioe;
373             }
374         }
375     }
376 }