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