1 /*
  2  * Copyright (c) 1994, 2020, 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 jdk.internal.misc.InternalLock;
 29 import jdk.internal.misc.Unsafe;
 30 import jdk.internal.util.ArraysSupport;
 31 
 32 /**
 33  * A {@code BufferedInputStream} adds
 34  * functionality to another input stream-namely,
 35  * the ability to buffer the input and to
 36  * support the {@code mark} and {@code reset}
 37  * methods. When  the {@code BufferedInputStream}
 38  * is created, an internal buffer array is
 39  * created. As bytes  from the stream are read
 40  * or skipped, the internal buffer is refilled
 41  * as necessary  from the contained input stream,
 42  * many bytes at a time. The {@code mark}
 43  * operation  remembers a point in the input
 44  * stream and the {@code reset} operation
 45  * causes all the  bytes read since the most
 46  * recent {@code mark} operation to be
 47  * reread before new bytes are  taken from
 48  * the contained input stream.
 49  *
 50  * @author  Arthur van Hoff
 51  * @since   1.0
 52  */
 53 public class BufferedInputStream extends FilterInputStream {
 54 
 55     private static int DEFAULT_BUFFER_SIZE = 8192;
 56 
 57     /**
 58      * As this class is used early during bootstrap, it's motivated to use
 59      * Unsafe.compareAndSetObject instead of AtomicReferenceFieldUpdater
 60      * (or VarHandles) to reduce dependencies and improve startup time.
 61      */
 62     private static final Unsafe U = Unsafe.getUnsafe();
 63 
 64     private static final long BUF_OFFSET
 65             = U.objectFieldOffset(BufferedInputStream.class, "buf");
 66 
 67     // initialized to null when BufferedInputStream is sub-classed
 68     private final InternalLock lock;
 69 
 70     /**
 71      * The internal buffer array where the data is stored. When necessary,
 72      * it may be replaced by another array of
 73      * a different size.
 74      */
 75     /*
 76      * We null this out with a CAS on close(), which is necessary since
 77      * closes can be asynchronous. We use nullness of buf[] as primary
 78      * indicator that this stream is closed. (The "in" field is also
 79      * nulled out on close.)
 80      */
 81     protected volatile byte[] buf;
 82 
 83     /**
 84      * The index one greater than the index of the last valid byte in
 85      * the buffer.
 86      * This value is always
 87      * in the range {@code 0} through {@code buf.length};
 88      * elements {@code buf[0]} through {@code buf[count-1]}
 89      * contain buffered input data obtained
 90      * from the underlying  input stream.
 91      */
 92     protected int count;
 93 
 94     /**
 95      * The current position in the buffer. This is the index of the next
 96      * character to be read from the {@code buf} array.
 97      * <p>
 98      * This value is always in the range {@code 0}
 99      * through {@code count}. If it is less
100      * than {@code count}, then  {@code buf[pos]}
101      * is the next byte to be supplied as input;
102      * if it is equal to {@code count}, then
103      * the  next {@code read} or {@code skip}
104      * operation will require more bytes to be
105      * read from the contained  input stream.
106      *
107      * @see     java.io.BufferedInputStream#buf
108      */
109     protected int pos;
110 
111     /**
112      * The value of the {@code pos} field at the time the last
113      * {@code mark} method was called.
114      * <p>
115      * This value is always
116      * in the range {@code -1} through {@code pos}.
117      * If there is no marked position in  the input
118      * stream, this field is {@code -1}. If
119      * there is a marked position in the input
120      * stream,  then {@code buf[markpos]}
121      * is the first byte to be supplied as input
122      * after a {@code reset} operation. If
123      * {@code markpos} is not {@code -1},
124      * then all bytes from positions {@code buf[markpos]}
125      * through  {@code buf[pos-1]} must remain
126      * in the buffer array (though they may be
127      * moved to  another place in the buffer array,
128      * with suitable adjustments to the values
129      * of {@code count},  {@code pos},
130      * and {@code markpos}); they may not
131      * be discarded unless and until the difference
132      * between {@code pos} and {@code markpos}
133      * exceeds {@code marklimit}.
134      *
135      * @see     java.io.BufferedInputStream#mark(int)
136      * @see     java.io.BufferedInputStream#pos
137      */
138     protected int markpos = -1;
139 
140     /**
141      * The maximum read ahead allowed after a call to the
142      * {@code mark} method before subsequent calls to the
143      * {@code reset} method fail.
144      * Whenever the difference between {@code pos}
145      * and {@code markpos} exceeds {@code marklimit},
146      * then the  mark may be dropped by setting
147      * {@code markpos} to {@code -1}.
148      *
149      * @see     java.io.BufferedInputStream#mark(int)
150      * @see     java.io.BufferedInputStream#reset()
151      */
152     protected int marklimit;
153 
154     /**
155      * Check to make sure that underlying input stream has not been
156      * nulled out due to close; if not return it;
157      */
158     private InputStream getInIfOpen() throws IOException {
159         InputStream input = in;
160         if (input == null)
161             throw new IOException("Stream closed");
162         return input;
163     }
164 
165     /**
166      * Check to make sure that buffer has not been nulled out due to
167      * close; if not return it;
168      */
169     private byte[] getBufIfOpen() throws IOException {
170         byte[] buffer = buf;
171         if (buffer == null)
172             throw new IOException("Stream closed");
173         return buffer;
174     }
175 
176     /**
177      * Creates a {@code BufferedInputStream}
178      * and saves its  argument, the input stream
179      * {@code in}, for later use. An internal
180      * buffer array is created and  stored in {@code buf}.
181      *
182      * @param   in   the underlying input stream.
183      */
184     public BufferedInputStream(InputStream in) {
185         this(in, DEFAULT_BUFFER_SIZE);
186     }
187 
188     /**
189      * Creates a {@code BufferedInputStream}
190      * with the specified buffer size,
191      * and saves its  argument, the input stream
192      * {@code in}, for later use.  An internal
193      * buffer array of length  {@code size}
194      * is created and stored in {@code buf}.
195      *
196      * @param   in     the underlying input stream.
197      * @param   size   the buffer size.
198      * @throws  IllegalArgumentException if {@code size <= 0}.
199      */
200     public BufferedInputStream(InputStream in, int size) {
201         super(in);
202         if (size <= 0) {
203             throw new IllegalArgumentException("Buffer size <= 0");
204         }
205         buf = new byte[size];
206 
207         // use monitors when BufferedInputStream is sub-classed
208         if (getClass() == BufferedInputStream.class) {
209             lock = new InternalLock();
210         } else {
211             lock = null;
212         }
213     }
214 
215     /**
216      * Fills the buffer with more data, taking into account
217      * shuffling and other tricks for dealing with marks.
218      * Assumes that it is being called by a locked method.
219      * This method also assumes that all data has already been read in,
220      * hence pos > count.
221      */
222     private void fill() throws IOException {
223         byte[] buffer = getBufIfOpen();
224         if (markpos < 0)
225             pos = 0;            /* no mark: throw away the buffer */
226         else if (pos >= buffer.length) { /* no room left in buffer */
227             if (markpos > 0) {  /* can throw away early part of the buffer */
228                 int sz = pos - markpos;
229                 System.arraycopy(buffer, markpos, buffer, 0, sz);
230                 pos = sz;
231                 markpos = 0;
232             } else if (buffer.length >= marklimit) {
233                 markpos = -1;   /* buffer got too big, invalidate mark */
234                 pos = 0;        /* drop buffer contents */
235             } else {            /* grow buffer */
236                 int nsz = ArraysSupport.newLength(pos,
237                         1,  /* minimum growth */
238                         pos /* preferred growth */);
239                 if (nsz > marklimit)
240                     nsz = marklimit;
241                 byte[] nbuf = new byte[nsz];
242                 System.arraycopy(buffer, 0, nbuf, 0, pos);
243                 if (!U.compareAndSetReference(this, BUF_OFFSET, buffer, nbuf)) {
244                     // Can't replace buf if there was an async close.
245                     // Note: This would need to be changed if fill()
246                     // is ever made accessible to multiple threads.
247                     // But for now, the only way CAS can fail is via close.
248                     // assert buf == null;
249                     throw new IOException("Stream closed");
250                 }
251                 buffer = nbuf;
252             }
253         }
254         count = pos;
255         int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
256         if (n > 0)
257             count = n + pos;
258     }
259 
260     /**
261      * See
262      * the general contract of the {@code read}
263      * method of {@code InputStream}.
264      *
265      * @return     the next byte of data, or {@code -1} if the end of the
266      *             stream is reached.
267      * @throws     IOException  if this input stream has been closed by
268      *                          invoking its {@link #close()} method,
269      *                          or an I/O error occurs.
270      * @see        java.io.FilterInputStream#in
271      */
272     public int read() throws IOException {
273         if (lock != null) {
274             lock.lock();
275             try {
276                 return lockedRead();
277             } finally {
278                 lock.unlock();
279             }
280         } else {
281             synchronized (this) {
282                 return lockedRead();
283             }
284         }
285     }
286 
287     private int lockedRead() throws IOException {
288         if (pos >= count) {
289             fill();
290             if (pos >= count)
291                 return -1;
292         }
293         return getBufIfOpen()[pos++] & 0xff;
294     }
295 
296     /**
297      * Read characters into a portion of an array, reading from the underlying
298      * stream at most once if necessary.
299      */
300     private int read1(byte[] b, int off, int len) throws IOException {
301         int avail = count - pos;
302         if (avail <= 0) {
303             /* If the requested length is at least as large as the buffer, and
304                if there is no mark/reset activity, do not bother to copy the
305                bytes into the local buffer.  In this way buffered streams will
306                cascade harmlessly. */
307             if (len >= getBufIfOpen().length && markpos < 0) {
308                 return getInIfOpen().read(b, off, len);
309             }
310             fill();
311             avail = count - pos;
312             if (avail <= 0) return -1;
313         }
314         int cnt = (avail < len) ? avail : len;
315         System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
316         pos += cnt;
317         return cnt;
318     }
319 
320     /**
321      * Reads bytes from this byte-input stream into the specified byte array,
322      * starting at the given offset.
323      *
324      * <p> This method implements the general contract of the corresponding
325      * {@link InputStream#read(byte[], int, int) read} method of
326      * the {@link InputStream} class.  As an additional
327      * convenience, it attempts to read as many bytes as possible by repeatedly
328      * invoking the {@code read} method of the underlying stream.  This
329      * iterated {@code read} continues until one of the following
330      * conditions becomes true: <ul>
331      *
332      *   <li> The specified number of bytes have been read,
333      *
334      *   <li> The {@code read} method of the underlying stream returns
335      *   {@code -1}, indicating end-of-file, or
336      *
337      *   <li> The {@code available} method of the underlying stream
338      *   returns zero, indicating that further input requests would block.
339      *
340      * </ul> If the first {@code read} on the underlying stream returns
341      * {@code -1} to indicate end-of-file then this method returns
342      * {@code -1}.  Otherwise this method returns the number of bytes
343      * actually read.
344      *
345      * <p> Subclasses of this class are encouraged, but not required, to
346      * attempt to read as many bytes as possible in the same fashion.
347      *
348      * @param      b     destination buffer.
349      * @param      off   offset at which to start storing bytes.
350      * @param      len   maximum number of bytes to read.
351      * @return     the number of bytes read, or {@code -1} if the end of
352      *             the stream has been reached.
353      * @throws     IOException  if this input stream has been closed by
354      *                          invoking its {@link #close()} method,
355      *                          or an I/O error occurs.
356      */
357     public int read(byte[] b, int off, int len) throws IOException {
358         if (lock != null) {
359             lock.lock();
360             try {
361                 return lockedRead(b, off, len);
362             } finally {
363                 lock.unlock();
364             }
365         } else {
366             synchronized (this) {
367                 return lockedRead(b, off, len);
368             }
369         }
370     }
371 
372     private int lockedRead(byte[] b, int off, int len) throws IOException {
373         getBufIfOpen(); // Check for closed stream
374         if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
375             throw new IndexOutOfBoundsException();
376         } else if (len == 0) {
377             return 0;
378         }
379 
380         int n = 0;
381         for (;;) {
382             int nread = read1(b, off + n, len - n);
383             if (nread <= 0)
384                 return (n == 0) ? nread : n;
385             n += nread;
386             if (n >= len)
387                 return n;
388             // if not closed but no bytes available, return
389             InputStream input = in;
390             if (input != null && input.available() <= 0)
391                 return n;
392         }
393     }
394 
395     /**
396      * See the general contract of the {@code skip}
397      * method of {@code InputStream}.
398      *
399      * @throws IOException  if this input stream has been closed by
400      *                      invoking its {@link #close()} method,
401      *                      {@code in.skip(n)} throws an IOException,
402      *                      or an I/O error occurs.
403      */
404     public long skip(long n) throws IOException {
405         if (lock != null) {
406             lock.lock();
407             try {
408                 return lockedSkip(n);
409             } finally {
410                 lock.unlock();
411             }
412         } else {
413             synchronized (this) {
414                 return lockedSkip(n);
415             }
416         }
417     }
418 
419     private long lockedSkip(long n) throws IOException {
420         getBufIfOpen(); // Check for closed stream
421         if (n <= 0) {
422             return 0;
423         }
424         long avail = count - pos;
425 
426         if (avail <= 0) {
427             // If no mark position set then don't keep in buffer
428             if (markpos <0)
429                 return getInIfOpen().skip(n);
430 
431             // Fill in buffer to save bytes for reset
432             fill();
433             avail = count - pos;
434             if (avail <= 0)
435                 return 0;
436         }
437 
438         long skipped = (avail < n) ? avail : n;
439         pos += skipped;
440         return skipped;
441     }
442 
443     /**
444      * Returns an estimate of the number of bytes that can be read (or
445      * skipped over) from this input stream without blocking by the next
446      * invocation of a method for this input stream. The next invocation might be
447      * the same thread or another thread.  A single read or skip of this
448      * many bytes will not block, but may read or skip fewer bytes.
449      * <p>
450      * This method returns the sum of the number of bytes remaining to be read in
451      * the buffer ({@code count - pos}) and the result of calling the
452      * {@link java.io.FilterInputStream#in in}{@code .available()}.
453      *
454      * @return     an estimate of the number of bytes that can be read (or skipped
455      *             over) from this input stream without blocking.
456      * @throws     IOException  if this input stream has been closed by
457      *                          invoking its {@link #close()} method,
458      *                          or an I/O error occurs.
459      */
460     public int available() throws IOException {
461         if (lock != null) {
462             lock.lock();
463             try {
464                 return lockAvailable();
465             } finally {
466                 lock.unlock();
467             }
468         } else {
469             synchronized (this) {
470                 return lockAvailable();
471             }
472         }
473     }
474 
475     private int lockAvailable() throws IOException {
476         int n = count - pos;
477         int avail = getInIfOpen().available();
478         return n > (Integer.MAX_VALUE - avail)
479                     ? Integer.MAX_VALUE
480                     : n + avail;
481     }
482 
483     /**
484      * See the general contract of the {@code mark}
485      * method of {@code InputStream}.
486      *
487      * @param   readlimit   the maximum limit of bytes that can be read before
488      *                      the mark position becomes invalid.
489      * @see     java.io.BufferedInputStream#reset()
490      */
491     public void mark(int readlimit) {
492         if (lock != null) {
493             lock.lock();
494             try {
495                 lockedMark(readlimit);
496             } finally {
497                 lock.unlock();
498             }
499         } else {
500             synchronized (this) {
501                 lockedMark(readlimit);
502             }
503         }
504     }
505 
506     private void lockedMark(int readlimit) {
507         marklimit = readlimit;
508         markpos = pos;
509     }
510 
511     /**
512      * See the general contract of the {@code reset}
513      * method of {@code InputStream}.
514      * <p>
515      * If {@code markpos} is {@code -1}
516      * (no mark has been set or the mark has been
517      * invalidated), an {@code IOException}
518      * is thrown. Otherwise, {@code pos} is
519      * set equal to {@code markpos}.
520      *
521      * @throws     IOException  if this stream has not been marked or,
522      *                  if the mark has been invalidated, or the stream
523      *                  has been closed by invoking its {@link #close()}
524      *                  method, or an I/O error occurs.
525      * @see        java.io.BufferedInputStream#mark(int)
526      */
527     public void reset() throws IOException {
528         if (lock != null) {
529             lock.lock();
530             try {
531                 lockedReset();
532             } finally {
533                 lock.unlock();
534             }
535         } else {
536             synchronized (this) {
537                 lockedReset();
538             }
539         }
540     }
541 
542     private void lockedReset() throws IOException {
543         getBufIfOpen(); // Cause exception if closed
544         if (markpos < 0)
545             throw new IOException("Resetting to invalid mark");
546         pos = markpos;
547     }
548 
549     /**
550      * Tests if this input stream supports the {@code mark}
551      * and {@code reset} methods. The {@code markSupported}
552      * method of {@code BufferedInputStream} returns
553      * {@code true}.
554      *
555      * @return  a {@code boolean} indicating if this stream type supports
556      *          the {@code mark} and {@code reset} methods.
557      * @see     java.io.InputStream#mark(int)
558      * @see     java.io.InputStream#reset()
559      */
560     public boolean markSupported() {
561         return true;
562     }
563 
564     /**
565      * Closes this input stream and releases any system resources
566      * associated with the stream.
567      * Once the stream has been closed, further read(), available(), reset(),
568      * or skip() invocations will throw an IOException.
569      * Closing a previously closed stream has no effect.
570      *
571      * @throws     IOException  if an I/O error occurs.
572      */
573     public void close() throws IOException {
574         byte[] buffer;
575         while ( (buffer = buf) != null) {
576             if (U.compareAndSetReference(this, BUF_OFFSET, buffer, null)) {
577                 InputStream input = in;
578                 in = null;
579                 if (input != null)
580                     input.close();
581                 return;
582             }
583             // Else retry in case a new buf was CASed in fill()
584         }
585     }
586 }