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