1 /*
  2  * Copyright (c) 1994, 2021, 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.nio.channels.FileChannel;
 29 import java.util.Arrays;
 30 import jdk.internal.misc.Blocker;
 31 import jdk.internal.util.ArraysSupport;
 32 import sun.nio.ch.FileChannelImpl;
 33 
 34 /**
 35  * A {@code FileInputStream} obtains input bytes
 36  * from a file in a file system. What files
 37  * are  available depends on the host environment.
 38  *
 39  * <p>{@code FileInputStream} is meant for reading streams of raw bytes
 40  * such as image data. For reading streams of characters, consider using
 41  * {@code FileReader}.
 42  *
 43  * @apiNote
 44  * To release resources used by this stream {@link #close} should be called
 45  * directly or by try-with-resources. Subclasses are responsible for the cleanup
 46  * of resources acquired by the subclass.
 47  * Subclasses that override {@link #finalize} in order to perform cleanup
 48  * should be modified to use alternative cleanup mechanisms such as
 49  * {@link java.lang.ref.Cleaner} and remove the overriding {@code finalize} method.
 50  *
 51  * @implSpec
 52  * If this FileInputStream has been subclassed and the {@link #close}
 53  * method has been overridden, the {@link #close} method will be
 54  * called when the FileInputStream is unreachable.
 55  * Otherwise, it is implementation specific how the resource cleanup described in
 56  * {@link #close} is performed.
 57  *
 58  * @author  Arthur van Hoff
 59  * @see     java.io.File
 60  * @see     java.io.FileDescriptor
 61  * @see     java.io.FileOutputStream
 62  * @see     java.nio.file.Files#newInputStream
 63  * @since   1.0
 64  */
 65 public class FileInputStream extends InputStream
 66 {
 67     private static final int DEFAULT_BUFFER_SIZE = 8192;
 68 
 69     /* File Descriptor - handle to the open file */
 70     private final FileDescriptor fd;
 71 
 72     /**
 73      * The path of the referenced file
 74      * (null if the stream is created with a file descriptor)
 75      */
 76     private final String path;
 77 
 78     private volatile FileChannel channel;
 79 
 80     private final Object closeLock = new Object();
 81 
 82     private volatile boolean closed;
 83 
 84     /**
 85      * Creates a {@code FileInputStream} by
 86      * opening a connection to an actual file,
 87      * the file named by the path name {@code name}
 88      * in the file system.  A new {@code FileDescriptor}
 89      * object is created to represent this file
 90      * connection.
 91      * <p>
 92      * First, if there is a security
 93      * manager, its {@code checkRead} method
 94      * is called with the {@code name} argument
 95      * as its argument.
 96      * <p>
 97      * If the named file does not exist, is a directory rather than a regular
 98      * file, or for some other reason cannot be opened for reading then a
 99      * {@code FileNotFoundException} is thrown.
100      *
101      * @param      name   the system-dependent file name.
102      * @throws     FileNotFoundException  if the file does not exist,
103      *             is a directory rather than a regular file,
104      *             or for some other reason cannot be opened for
105      *             reading.
106      * @throws     SecurityException      if a security manager exists and its
107      *             {@code checkRead} method denies read access
108      *             to the file.
109      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
110      */
111     public FileInputStream(String name) throws FileNotFoundException {
112         this(name != null ? new File(name) : null);
113     }
114 
115     /**
116      * Creates a {@code FileInputStream} by
117      * opening a connection to an actual file,
118      * the file named by the {@code File}
119      * object {@code file} in the file system.
120      * A new {@code FileDescriptor} object
121      * is created to represent this file connection.
122      * <p>
123      * First, if there is a security manager,
124      * its {@code checkRead} method  is called
125      * with the path represented by the {@code file}
126      * argument as its argument.
127      * <p>
128      * If the named file does not exist, is a directory rather than a regular
129      * file, or for some other reason cannot be opened for reading then a
130      * {@code FileNotFoundException} is thrown.
131      *
132      * @param      file   the file to be opened for reading.
133      * @throws     FileNotFoundException  if the file does not exist,
134      *             is a directory rather than a regular file,
135      *             or for some other reason cannot be opened for
136      *             reading.
137      * @throws     SecurityException      if a security manager exists and its
138      *             {@code checkRead} method denies read access to the file.
139      * @see        java.io.File#getPath()
140      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
141      */
142     public FileInputStream(File file) throws FileNotFoundException {
143         String name = (file != null ? file.getPath() : null);
144         @SuppressWarnings("removal")
145         SecurityManager security = System.getSecurityManager();
146         if (security != null) {
147             security.checkRead(name);
148         }
149         if (name == null) {
150             throw new NullPointerException();
151         }
152         if (file.isInvalid()) {
153             throw new FileNotFoundException("Invalid file path");
154         }
155         fd = new FileDescriptor();
156         fd.attach(this);
157         path = name;
158         open(name);
159         FileCleanable.register(fd);       // open set the fd, register the cleanup
160     }
161 
162     /**
163      * Creates a {@code FileInputStream} by using the file descriptor
164      * {@code fdObj}, which represents an existing connection to an
165      * actual file in the file system.
166      * <p>
167      * If there is a security manager, its {@code checkRead} method is
168      * called with the file descriptor {@code fdObj} as its argument to
169      * see if it's ok to read the file descriptor. If read access is denied
170      * to the file descriptor a {@code SecurityException} is thrown.
171      * <p>
172      * If {@code fdObj} is null then a {@code NullPointerException}
173      * is thrown.
174      * <p>
175      * This constructor does not throw an exception if {@code fdObj}
176      * is {@link java.io.FileDescriptor#valid() invalid}.
177      * However, if the methods are invoked on the resulting stream to attempt
178      * I/O on the stream, an {@code IOException} is thrown.
179      *
180      * @param      fdObj   the file descriptor to be opened for reading.
181      * @throws     SecurityException      if a security manager exists and its
182      *             {@code checkRead} method denies read access to the
183      *             file descriptor.
184      * @see        SecurityManager#checkRead(java.io.FileDescriptor)
185      */
186     public FileInputStream(FileDescriptor fdObj) {
187         @SuppressWarnings("removal")
188         SecurityManager security = System.getSecurityManager();
189         if (fdObj == null) {
190             throw new NullPointerException();
191         }
192         if (security != null) {
193             security.checkRead(fdObj);
194         }
195         fd = fdObj;
196         path = null;
197 
198         /*
199          * FileDescriptor is being shared by streams.
200          * Register this stream with FileDescriptor tracker.
201          */
202         fd.attach(this);
203     }
204 
205     /**
206      * Opens the specified file for reading.
207      * @param name the name of the file
208      */
209     private native void open0(String name) throws FileNotFoundException;
210 
211     // wrap native call to allow instrumentation
212     /**
213      * Opens the specified file for reading.
214      * @param name the name of the file
215      */
216     private void open(String name) throws FileNotFoundException {
217         if (Thread.currentThread().isVirtual()) {
218             Blocker.managedBlock(() -> open0(name));
219         } else {
220             open0(name);
221         }
222     }
223 
224     /**
225      * Reads a byte of data from this input stream. This method blocks
226      * if no input is yet available.
227      *
228      * @return     the next byte of data, or {@code -1} if the end of the
229      *             file is reached.
230      * @throws     IOException  if an I/O error occurs.
231      */
232     public int read() throws IOException {
233         if (Thread.currentThread().isVirtual()) {
234             return Blocker.managedBlock(() -> read0());
235         } else {
236             return read0();
237         }
238     }
239 
240     private native int read0() throws IOException;
241 
242     /**
243      * Reads a subarray as a sequence of bytes.
244      * @param     b the data to be written
245      * @param     off the start offset in the data
246      * @param     len the number of bytes that are written
247      * @throws    IOException If an I/O error has occurred.
248      */
249     private native int readBytes(byte[] b, int off, int len) throws IOException;
250 
251     /**
252      * Reads up to {@code b.length} bytes of data from this input
253      * stream into an array of bytes. This method blocks until some input
254      * is available.
255      *
256      * @param      b   the buffer into which the data is read.
257      * @return     the total number of bytes read into the buffer, or
258      *             {@code -1} if there is no more data because the end of
259      *             the file has been reached.
260      * @throws     IOException  if an I/O error occurs.
261      */
262     public int read(byte[] b) throws IOException {
263         if (Thread.currentThread().isVirtual()) {
264             return Blocker.managedBlock(() -> readBytes(b, 0, b.length));
265         } else {
266             return readBytes(b, 0, b.length);
267         }
268     }
269 
270     /**
271      * Reads up to {@code len} bytes of data from this input stream
272      * into an array of bytes. If {@code len} is not zero, the method
273      * blocks until some input is available; otherwise, no
274      * bytes are read and {@code 0} is returned.
275      *
276      * @param      b     the buffer into which the data is read.
277      * @param      off   the start offset in the destination array {@code b}
278      * @param      len   the maximum number of bytes read.
279      * @return     the total number of bytes read into the buffer, or
280      *             {@code -1} if there is no more data because the end of
281      *             the file has been reached.
282      * @throws     NullPointerException If {@code b} is {@code null}.
283      * @throws     IndexOutOfBoundsException If {@code off} is negative,
284      *             {@code len} is negative, or {@code len} is greater than
285      *             {@code b.length - off}
286      * @throws     IOException  if an I/O error occurs.
287      */
288     public int read(byte[] b, int off, int len) throws IOException {
289         if (Thread.currentThread().isVirtual()) {
290             return Blocker.managedBlock(() -> readBytes(b, off, len));
291         } else {
292             return readBytes(b, off, len);
293         }
294     }
295 
296     public byte[] readAllBytes() throws IOException {
297         long length = length();
298         long position = position();
299         long size = length - position;
300 
301         if (length <= 0 || size <= 0)
302             return super.readAllBytes();
303 
304         if (size > (long) Integer.MAX_VALUE) {
305             String msg =
306                 String.format("Required array size too large for %s: %d = %d - %d",
307                     path, size, length, position);
308             throw new OutOfMemoryError(msg);
309         }
310 
311         int capacity = (int)size;
312         byte[] buf = new byte[capacity];
313 
314         int nread = 0;
315         int n;
316         for (;;) {
317             // read to EOF which may read more or less than initial size, e.g.,
318             // file is truncated while we are reading
319             while ((n = read(buf, nread, capacity - nread)) > 0)
320                 nread += n;
321 
322             // if last call to read() returned -1, we are done; otherwise,
323             // try to read one more byte and if that fails we're done too
324             if (n < 0 || (n = read()) < 0)
325                 break;
326 
327             // one more byte was read; need to allocate a larger buffer
328             capacity = Math.max(ArraysSupport.newLength(capacity,
329                                                         1,         // min growth
330                                                         capacity), // pref growth
331                                 DEFAULT_BUFFER_SIZE);
332             buf = Arrays.copyOf(buf, capacity);
333             buf[nread++] = (byte)n;
334         }
335         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
336     }
337 
338     public byte[] readNBytes(int len) throws IOException {
339         if (len < 0)
340             throw new IllegalArgumentException("len < 0");
341         if (len == 0)
342             return new byte[0];
343 
344         long length = length();
345         long position = position();
346         long size = length - position;
347 
348         if (length <= 0 || size <= 0)
349             return super.readNBytes(len);
350 
351         int capacity = (int)Math.min(len, size);
352         byte[] buf = new byte[capacity];
353 
354         int remaining = capacity;
355         int nread = 0;
356         int n;
357         do {
358             n = read(buf, nread, remaining);
359             if (n > 0) {
360                 nread += n;
361                 remaining -= n;
362             } else if (n == 0) {
363                 // Block until a byte is read or EOF is detected
364                 byte b = (byte)read();
365                 if (b == -1 )
366                     break;
367                 buf[nread++] = b;
368                 remaining--;
369             }
370         } while (n >= 0 && remaining > 0);
371         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
372     }
373 
374     /**
375      * {@inheritDoc}
376      */
377     public long transferTo(OutputStream out) throws IOException {
378         long transferred = 0L;
379         if (out instanceof FileOutputStream fos) {
380             FileChannel fc = getChannel();
381             long pos = fc.position();
382             transferred = fc.transferTo(pos, Long.MAX_VALUE, fos.getChannel());
383             long newPos = pos + transferred;
384             fc.position(newPos);
385             if (newPos >= fc.size()) {
386                 return transferred;
387             }
388         }
389         return transferred + super.transferTo(out);
390     }
391 
392     private long length() throws IOException {
393         if (Thread.currentThread().isVirtual()) {
394             return Blocker.managedBlock(() -> length0());
395         } else {
396             return length0();
397         }
398     }
399     private native long length0() throws IOException;
400 
401     private long position() throws IOException {
402         if (Thread.currentThread().isVirtual()) {
403             return Blocker.managedBlock(() -> position0());
404         } else {
405             return position0();
406         }
407     }
408     private native long position0() throws IOException;
409 
410     /**
411      * Skips over and discards {@code n} bytes of data from the
412      * input stream.
413      *
414      * <p>The {@code skip} method may, for a variety of
415      * reasons, end up skipping over some smaller number of bytes,
416      * possibly {@code 0}. If {@code n} is negative, the method
417      * will try to skip backwards. In case the backing file does not support
418      * backward skip at its current position, an {@code IOException} is
419      * thrown. The actual number of bytes skipped is returned. If it skips
420      * forwards, it returns a positive value. If it skips backwards, it
421      * returns a negative value.
422      *
423      * <p>This method may skip more bytes than what are remaining in the
424      * backing file. This produces no exception and the number of bytes skipped
425      * may include some number of bytes that were beyond the EOF of the
426      * backing file. Attempting to read from the stream after skipping past
427      * the end will result in -1 indicating the end of the file.
428      *
429      * @param      n   the number of bytes to be skipped.
430      * @return     the actual number of bytes skipped.
431      * @throws     IOException  if n is negative, if the stream does not
432      *             support seek, or if an I/O error occurs.
433      */
434     public long skip(long n) throws IOException {
435         if (Thread.currentThread().isVirtual()) {
436             return Blocker.managedBlock(() -> skip0(n));
437         } else {
438             return skip0(n);
439         }
440     }
441 
442     private native long skip0(long n) throws IOException;
443 
444     /**
445      * Returns an estimate of the number of remaining bytes that can be read (or
446      * skipped over) from this input stream without blocking by the next
447      * invocation of a method for this input stream. Returns 0 when the file
448      * position is beyond EOF. The next invocation might be the same thread
449      * or another thread. A single read or skip of this many bytes will not
450      * block, but may read or skip fewer bytes.
451      *
452      * <p> In some cases, a non-blocking read (or skip) may appear to be
453      * blocked when it is merely slow, for example when reading large
454      * files over slow networks.
455      *
456      * @return     an estimate of the number of remaining bytes that can be read
457      *             (or skipped over) from this input stream without blocking.
458      * @throws     IOException  if this file input stream has been closed by calling
459      *             {@code close} or an I/O error occurs.
460      */
461     public int available() throws IOException {
462         if (Thread.currentThread().isVirtual()) {
463             return Blocker.managedBlock(() -> available0());
464         } else {
465             return available0();
466         }
467     }
468 
469     private native int available0() throws IOException;
470 
471     /**
472      * Closes this file input stream and releases any system resources
473      * associated with the stream.
474      *
475      * <p> If this stream has an associated channel then the channel is closed
476      * as well.
477      *
478      * @apiNote
479      * Overriding {@link #close} to perform cleanup actions is reliable
480      * only when called directly or when called by try-with-resources.
481      * Do not depend on finalization to invoke {@code close};
482      * finalization is not reliable and is deprecated.
483      * If cleanup of native resources is needed, other mechanisms such as
484      * {@linkplain java.lang.ref.Cleaner} should be used.
485      *
486      * @throws     IOException  if an I/O error occurs.
487      *
488      * @revised 1.4
489      */
490     public void close() throws IOException {
491         if (closed) {
492             return;
493         }
494         synchronized (closeLock) {
495             if (closed) {
496                 return;
497             }
498             closed = true;
499         }
500 
501         FileChannel fc = channel;
502         if (fc != null) {
503             // possible race with getChannel(), benign since
504             // FileChannel.close is final and idempotent
505             fc.close();
506         }
507 
508         fd.closeAll(new Closeable() {
509             public void close() throws IOException {
510                fd.close();
511            }
512         });
513     }
514 
515     /**
516      * Returns the {@code FileDescriptor}
517      * object  that represents the connection to
518      * the actual file in the file system being
519      * used by this {@code FileInputStream}.
520      *
521      * @return     the file descriptor object associated with this stream.
522      * @throws     IOException  if an I/O error occurs.
523      * @see        java.io.FileDescriptor
524      */
525     public final FileDescriptor getFD() throws IOException {
526         if (fd != null) {
527             return fd;
528         }
529         throw new IOException();
530     }
531 
532     /**
533      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
534      * object associated with this file input stream.
535      *
536      * <p> The initial {@link java.nio.channels.FileChannel#position()
537      * position} of the returned channel will be equal to the
538      * number of bytes read from the file so far.  Reading bytes from this
539      * stream will increment the channel's position.  Changing the channel's
540      * position, either explicitly or by reading, will change this stream's
541      * file position.
542      *
543      * @return  the file channel associated with this file input stream
544      *
545      * @since 1.4
546      */
547     public FileChannel getChannel() {
548         FileChannel fc = this.channel;
549         if (fc == null) {
550             synchronized (this) {
551                 fc = this.channel;
552                 if (fc == null) {
553                     this.channel = fc = FileChannelImpl.open(fd, path, true,
554                         false, false, this);
555                     if (closed) {
556                         try {
557                             // possible race with close(), benign since
558                             // FileChannel.close is final and idempotent
559                             fc.close();
560                         } catch (IOException ioe) {
561                             throw new InternalError(ioe); // should not happen
562                         }
563                     }
564                 }
565             }
566         }
567         return fc;
568     }
569 
570     private static native void initIDs();
571 
572     static {
573         initIDs();
574     }
575 }
--- EOF ---