1 /*
   2  * Copyright (c) 1996, 2017, 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.io.ObjectStreamClass.WeakClassKey;
  29 import java.lang.System.Logger;
  30 import java.lang.ref.ReferenceQueue;
  31 import java.lang.reflect.Array;
  32 import java.lang.reflect.Modifier;
  33 import java.lang.reflect.Proxy;
  34 import java.security.AccessControlContext;
  35 import java.security.AccessController;
  36 import java.security.PrivilegedAction;
  37 import java.security.PrivilegedActionException;
  38 import java.security.PrivilegedExceptionAction;
  39 import java.util.Arrays;
  40 import java.util.Map;
  41 import java.util.Objects;
  42 import java.util.concurrent.ConcurrentHashMap;
  43 import java.util.concurrent.ConcurrentMap;
  44 
  45 import static java.io.ObjectStreamClass.processQueue;
  46 
  47 import jdk.internal.misc.SharedSecrets;
  48 import jdk.internal.misc.Unsafe;
  49 import sun.reflect.misc.ReflectUtil;
  50 
  51 /**
  52  * An ObjectInputStream deserializes primitive data and objects previously
  53  * written using an ObjectOutputStream.
  54  *
  55  * <p><strong>Warning: Deserialization of untrusted data is inherently dangerous
  56  * and should be avoided. Untrusted data should be carefully validated according to the
  57  * "Serialization and Deserialization" section of the
  58  * {@extLink secure_coding_guidelines_javase Secure Coding Guidelines for Java SE}.
  59  * {@extLink serialization_filter_guide Serialization Filtering} describes best
  60  * practices for defensive use of serial filters.
  61  * </strong></p>
  62  *
  63  * <p>ObjectOutputStream and ObjectInputStream can provide an application with
  64  * persistent storage for graphs of objects when used with a FileOutputStream
  65  * and FileInputStream respectively.  ObjectInputStream is used to recover
  66  * those objects previously serialized. Other uses include passing objects
  67  * between hosts using a socket stream or for marshaling and unmarshaling
  68  * arguments and parameters in a remote communication system.
  69  *
  70  * <p>ObjectInputStream ensures that the types of all objects in the graph
  71  * created from the stream match the classes present in the Java Virtual
  72  * Machine.  Classes are loaded as required using the standard mechanisms.
  73  *
  74  * <p>Only objects that support the java.io.Serializable or
  75  * java.io.Externalizable interface can be read from streams.
  76  *
  77  * <p>The method <code>readObject</code> is used to read an object from the
  78  * stream.  Java's safe casting should be used to get the desired type.  In
  79  * Java, strings and arrays are objects and are treated as objects during
  80  * serialization. When read they need to be cast to the expected type.
  81  *
  82  * <p>Primitive data types can be read from the stream using the appropriate
  83  * method on DataInput.
  84  *
  85  * <p>The default deserialization mechanism for objects restores the contents
  86  * of each field to the value and type it had when it was written.  Fields
  87  * declared as transient or static are ignored by the deserialization process.
  88  * References to other objects cause those objects to be read from the stream
  89  * as necessary.  Graphs of objects are restored correctly using a reference
  90  * sharing mechanism.  New objects are always allocated when deserializing,
  91  * which prevents existing objects from being overwritten.
  92  *
  93  * <p>Reading an object is analogous to running the constructors of a new
  94  * object.  Memory is allocated for the object and initialized to zero (NULL).
  95  * No-arg constructors are invoked for the non-serializable classes and then
  96  * the fields of the serializable classes are restored from the stream starting
  97  * with the serializable class closest to java.lang.object and finishing with
  98  * the object's most specific class.
  99  *
 100  * <p>For example to read from a stream as written by the example in
 101  * ObjectOutputStream:
 102  * <br>
 103  * <pre>
 104  *      FileInputStream fis = new FileInputStream("t.tmp");
 105  *      ObjectInputStream ois = new ObjectInputStream(fis);
 106  *
 107  *      int i = ois.readInt();
 108  *      String today = (String) ois.readObject();
 109  *      Date date = (Date) ois.readObject();
 110  *
 111  *      ois.close();
 112  * </pre>
 113  *
 114  * <p>Classes control how they are serialized by implementing either the
 115  * java.io.Serializable or java.io.Externalizable interfaces.
 116  *
 117  * <p>Implementing the Serializable interface allows object serialization to
 118  * save and restore the entire state of the object and it allows classes to
 119  * evolve between the time the stream is written and the time it is read.  It
 120  * automatically traverses references between objects, saving and restoring
 121  * entire graphs.
 122  *
 123  * <p>Serializable classes that require special handling during the
 124  * serialization and deserialization process should implement the following
 125  * methods:
 126  *
 127  * <pre>
 128  * private void writeObject(java.io.ObjectOutputStream stream)
 129  *     throws IOException;
 130  * private void readObject(java.io.ObjectInputStream stream)
 131  *     throws IOException, ClassNotFoundException;
 132  * private void readObjectNoData()
 133  *     throws ObjectStreamException;
 134  * </pre>
 135  *
 136  * <p>The readObject method is responsible for reading and restoring the state
 137  * of the object for its particular class using data written to the stream by
 138  * the corresponding writeObject method.  The method does not need to concern
 139  * itself with the state belonging to its superclasses or subclasses.  State is
 140  * restored by reading data from the ObjectInputStream for the individual
 141  * fields and making assignments to the appropriate fields of the object.
 142  * Reading primitive data types is supported by DataInput.
 143  *
 144  * <p>Any attempt to read object data which exceeds the boundaries of the
 145  * custom data written by the corresponding writeObject method will cause an
 146  * OptionalDataException to be thrown with an eof field value of true.
 147  * Non-object reads which exceed the end of the allotted data will reflect the
 148  * end of data in the same way that they would indicate the end of the stream:
 149  * bytewise reads will return -1 as the byte read or number of bytes read, and
 150  * primitive reads will throw EOFExceptions.  If there is no corresponding
 151  * writeObject method, then the end of default serialized data marks the end of
 152  * the allotted data.
 153  *
 154  * <p>Primitive and object read calls issued from within a readExternal method
 155  * behave in the same manner--if the stream is already positioned at the end of
 156  * data written by the corresponding writeExternal method, object reads will
 157  * throw OptionalDataExceptions with eof set to true, bytewise reads will
 158  * return -1, and primitive reads will throw EOFExceptions.  Note that this
 159  * behavior does not hold for streams written with the old
 160  * <code>ObjectStreamConstants.PROTOCOL_VERSION_1</code> protocol, in which the
 161  * end of data written by writeExternal methods is not demarcated, and hence
 162  * cannot be detected.
 163  *
 164  * <p>The readObjectNoData method is responsible for initializing the state of
 165  * the object for its particular class in the event that the serialization
 166  * stream does not list the given class as a superclass of the object being
 167  * deserialized.  This may occur in cases where the receiving party uses a
 168  * different version of the deserialized instance's class than the sending
 169  * party, and the receiver's version extends classes that are not extended by
 170  * the sender's version.  This may also occur if the serialization stream has
 171  * been tampered; hence, readObjectNoData is useful for initializing
 172  * deserialized objects properly despite a "hostile" or incomplete source
 173  * stream.
 174  *
 175  * <p>Serialization does not read or assign values to the fields of any object
 176  * that does not implement the java.io.Serializable interface.  Subclasses of
 177  * Objects that are not serializable can be serializable. In this case the
 178  * non-serializable class must have a no-arg constructor to allow its fields to
 179  * be initialized.  In this case it is the responsibility of the subclass to
 180  * save and restore the state of the non-serializable class. It is frequently
 181  * the case that the fields of that class are accessible (public, package, or
 182  * protected) or that there are get and set methods that can be used to restore
 183  * the state.
 184  *
 185  * <p>The contents of the stream can be filtered during deserialization.
 186  * If a {@linkplain #setObjectInputFilter(ObjectInputFilter) filter is set}
 187  * on an ObjectInputStream, the {@link ObjectInputFilter} can check that
 188  * the classes, array lengths, number of references in the stream, depth, and
 189  * number of bytes consumed from the input stream are allowed and
 190  * if not, can terminate deserialization.
 191  * A {@linkplain ObjectInputFilter.Config#setSerialFilter(ObjectInputFilter) process-wide filter}
 192  * can be configured that is applied to each {@code ObjectInputStream} unless replaced
 193  * using {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter}.
 194  *
 195  * <p>Any exception that occurs while deserializing an object will be caught by
 196  * the ObjectInputStream and abort the reading process.
 197  *
 198  * <p>Implementing the Externalizable interface allows the object to assume
 199  * complete control over the contents and format of the object's serialized
 200  * form.  The methods of the Externalizable interface, writeExternal and
 201  * readExternal, are called to save and restore the objects state.  When
 202  * implemented by a class they can write and read their own state using all of
 203  * the methods of ObjectOutput and ObjectInput.  It is the responsibility of
 204  * the objects to handle any versioning that occurs.
 205  *
 206  * <p>Enum constants are deserialized differently than ordinary serializable or
 207  * externalizable objects.  The serialized form of an enum constant consists
 208  * solely of its name; field values of the constant are not transmitted.  To
 209  * deserialize an enum constant, ObjectInputStream reads the constant name from
 210  * the stream; the deserialized constant is then obtained by calling the static
 211  * method <code>Enum.valueOf(Class, String)</code> with the enum constant's
 212  * base type and the received constant name as arguments.  Like other
 213  * serializable or externalizable objects, enum constants can function as the
 214  * targets of back references appearing subsequently in the serialization
 215  * stream.  The process by which enum constants are deserialized cannot be
 216  * customized: any class-specific readObject, readObjectNoData, and readResolve
 217  * methods defined by enum types are ignored during deserialization.
 218  * Similarly, any serialPersistentFields or serialVersionUID field declarations
 219  * are also ignored--all enum types have a fixed serialVersionUID of 0L.
 220  *
 221  * @author      Mike Warres
 222  * @author      Roger Riggs
 223  * @see java.io.DataInput
 224  * @see java.io.ObjectOutputStream
 225  * @see java.io.Serializable
 226  * @see <a href="{@docRoot}/../specs/serialization/input.html">
 227  *     Object Serialization Specification, Section 3, Object Input Classes</a>
 228  * @since   1.1
 229  */
 230 public class ObjectInputStream
 231     extends InputStream implements ObjectInput, ObjectStreamConstants
 232 {
 233     /** handle value representing null */
 234     private static final int NULL_HANDLE = -1;
 235 
 236     /** marker for unshared objects in internal handle table */
 237     private static final Object unsharedMarker = new Object();
 238 
 239     /**
 240      * immutable table mapping primitive type names to corresponding
 241      * class objects
 242      */
 243     private static final Map<String, Class<?>> primClasses =
 244         Map.of("boolean", boolean.class,
 245                "byte", byte.class,
 246                "char", char.class,
 247                "short", short.class,
 248                "int", int.class,
 249                "long", long.class,
 250                "float", float.class,
 251                "double", double.class,
 252                "void", void.class);
 253 
 254     private static class Caches {
 255         /** cache of subclass security audit results */
 256         static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
 257             new ConcurrentHashMap<>();
 258 
 259         /** queue for WeakReferences to audited subclasses */
 260         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
 261             new ReferenceQueue<>();
 262     }
 263 
 264     /*
 265      * Separate class to defer initialization of logging until needed.
 266      */
 267     private static class Logging {
 268         /*
 269          * Logger for ObjectInputFilter results.
 270          * Setup the filter logger if it is set to DEBUG or TRACE.
 271          * (Assuming it will not change).
 272          */
 273         static final System.Logger filterLogger;
 274 
 275         static {
 276             Logger filterLog = System.getLogger("java.io.serialization");
 277             filterLogger = (filterLog.isLoggable(Logger.Level.DEBUG)
 278                     || filterLog.isLoggable(Logger.Level.TRACE)) ? filterLog : null;
 279         }
 280     }
 281 
 282     /** filter stream for handling block data conversion */
 283     private final BlockDataInputStream bin;
 284     /** validation callback list */
 285     private final ValidationList vlist;
 286     /** recursion depth */
 287     private long depth;
 288     /** Total number of references to any type of object, class, enum, proxy, etc. */
 289     private long totalObjectRefs;
 290     /** whether stream is closed */
 291     private boolean closed;
 292 
 293     /** wire handle -> obj/exception map */
 294     private final HandleTable handles;
 295     /** scratch field for passing handle values up/down call stack */
 296     private int passHandle = NULL_HANDLE;
 297     /** flag set when at end of field value block with no TC_ENDBLOCKDATA */
 298     private boolean defaultDataEnd = false;
 299 
 300     /** if true, invoke readObjectOverride() instead of readObject() */
 301     private final boolean enableOverride;
 302     /** if true, invoke resolveObject() */
 303     private boolean enableResolve;
 304 
 305     /**
 306      * Context during upcalls to class-defined readObject methods; holds
 307      * object currently being deserialized and descriptor for current class.
 308      * Null when not during readObject upcall.
 309      */
 310     private SerialCallbackContext curContext;
 311 
 312     /**
 313      * Filter of class descriptors and classes read from the stream;
 314      * may be null.
 315      */
 316     private ObjectInputFilter serialFilter;
 317 
 318     /**
 319      * Creates an ObjectInputStream that reads from the specified InputStream.
 320      * A serialization stream header is read from the stream and verified.
 321      * This constructor will block until the corresponding ObjectOutputStream
 322      * has written and flushed the header.
 323      *
 324      * <p>The serialization filter is initialized to the value of
 325      * {@linkplain ObjectInputFilter.Config#getSerialFilter() the process-wide filter}.
 326      *
 327      * <p>If a security manager is installed, this constructor will check for
 328      * the "enableSubclassImplementation" SerializablePermission when invoked
 329      * directly or indirectly by the constructor of a subclass which overrides
 330      * the ObjectInputStream.readFields or ObjectInputStream.readUnshared
 331      * methods.
 332      *
 333      * @param   in input stream to read from
 334      * @throws  StreamCorruptedException if the stream header is incorrect
 335      * @throws  IOException if an I/O error occurs while reading stream header
 336      * @throws  SecurityException if untrusted subclass illegally overrides
 337      *          security-sensitive methods
 338      * @throws  NullPointerException if <code>in</code> is <code>null</code>
 339      * @see     ObjectInputStream#ObjectInputStream()
 340      * @see     ObjectInputStream#readFields()
 341      * @see     ObjectOutputStream#ObjectOutputStream(OutputStream)
 342      */
 343     public ObjectInputStream(InputStream in) throws IOException {
 344         verifySubclass();
 345         bin = new BlockDataInputStream(in);
 346         handles = new HandleTable(10);
 347         vlist = new ValidationList();
 348         serialFilter = ObjectInputFilter.Config.getSerialFilter();
 349         enableOverride = false;
 350         readStreamHeader();
 351         bin.setBlockDataMode(true);
 352     }
 353 
 354     /**
 355      * Provide a way for subclasses that are completely reimplementing
 356      * ObjectInputStream to not have to allocate private data just used by this
 357      * implementation of ObjectInputStream.
 358      *
 359      * <p>The serialization filter is initialized to the value of
 360      * {@linkplain ObjectInputFilter.Config#getSerialFilter() the process-wide filter}.
 361      *
 362      * <p>If there is a security manager installed, this method first calls the
 363      * security manager's <code>checkPermission</code> method with the
 364      * <code>SerializablePermission("enableSubclassImplementation")</code>
 365      * permission to ensure it's ok to enable subclassing.
 366      *
 367      * @throws  SecurityException if a security manager exists and its
 368      *          <code>checkPermission</code> method denies enabling
 369      *          subclassing.
 370      * @throws  IOException if an I/O error occurs while creating this stream
 371      * @see SecurityManager#checkPermission
 372      * @see java.io.SerializablePermission
 373      */
 374     protected ObjectInputStream() throws IOException, SecurityException {
 375         SecurityManager sm = System.getSecurityManager();
 376         if (sm != null) {
 377             sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
 378         }
 379         bin = null;
 380         handles = null;
 381         vlist = null;
 382         serialFilter = ObjectInputFilter.Config.getSerialFilter();
 383         enableOverride = true;
 384     }
 385 
 386     /**
 387      * Read an object from the ObjectInputStream.  The class of the object, the
 388      * signature of the class, and the values of the non-transient and
 389      * non-static fields of the class and all of its supertypes are read.
 390      * Default deserializing for a class can be overridden using the writeObject
 391      * and readObject methods.  Objects referenced by this object are read
 392      * transitively so that a complete equivalent graph of objects is
 393      * reconstructed by readObject.
 394      *
 395      * <p>The root object is completely restored when all of its fields and the
 396      * objects it references are completely restored.  At this point the object
 397      * validation callbacks are executed in order based on their registered
 398      * priorities. The callbacks are registered by objects (in the readObject
 399      * special methods) as they are individually restored.
 400      *
 401      * <p>The serialization filter, when not {@code null}, is invoked for
 402      * each object (regular or class) read to reconstruct the root object.
 403      * See {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter} for details.
 404      *
 405      * <p>Exceptions are thrown for problems with the InputStream and for
 406      * classes that should not be deserialized.  All exceptions are fatal to
 407      * the InputStream and leave it in an indeterminate state; it is up to the
 408      * caller to ignore or recover the stream state.
 409      *
 410      * @throws  ClassNotFoundException Class of a serialized object cannot be
 411      *          found.
 412      * @throws  InvalidClassException Something is wrong with a class used by
 413      *          serialization.
 414      * @throws  StreamCorruptedException Control information in the
 415      *          stream is inconsistent.
 416      * @throws  OptionalDataException Primitive data was found in the
 417      *          stream instead of objects.
 418      * @throws  IOException Any of the usual Input/Output related exceptions.
 419      */
 420     public final Object readObject()
 421         throws IOException, ClassNotFoundException
 422     {
 423         if (enableOverride) {
 424             return readObjectOverride();
 425         }
 426 
 427         // if nested read, passHandle contains handle of enclosing object
 428         int outerHandle = passHandle;
 429         try {
 430             Object obj = readObject0(false);
 431             handles.markDependency(outerHandle, passHandle);
 432             ClassNotFoundException ex = handles.lookupException(passHandle);
 433             if (ex != null) {
 434                 throw ex;
 435             }
 436             if (depth == 0) {
 437                 vlist.doCallbacks();
 438                 freeze();
 439             }
 440             return obj;
 441         } finally {
 442             passHandle = outerHandle;
 443             if (closed && depth == 0) {
 444                 clear();
 445             }
 446         }
 447     }
 448 
 449     /**
 450      * This method is called by trusted subclasses of ObjectOutputStream that
 451      * constructed ObjectOutputStream using the protected no-arg constructor.
 452      * The subclass is expected to provide an override method with the modifier
 453      * "final".
 454      *
 455      * @return  the Object read from the stream.
 456      * @throws  ClassNotFoundException Class definition of a serialized object
 457      *          cannot be found.
 458      * @throws  OptionalDataException Primitive data was found in the stream
 459      *          instead of objects.
 460      * @throws  IOException if I/O errors occurred while reading from the
 461      *          underlying stream
 462      * @see #ObjectInputStream()
 463      * @see #readObject()
 464      * @since 1.2
 465      */
 466     protected Object readObjectOverride()
 467         throws IOException, ClassNotFoundException
 468     {
 469         return null;
 470     }
 471 
 472     /**
 473      * Reads an "unshared" object from the ObjectInputStream.  This method is
 474      * identical to readObject, except that it prevents subsequent calls to
 475      * readObject and readUnshared from returning additional references to the
 476      * deserialized instance obtained via this call.  Specifically:
 477      * <ul>
 478      *   <li>If readUnshared is called to deserialize a back-reference (the
 479      *       stream representation of an object which has been written
 480      *       previously to the stream), an ObjectStreamException will be
 481      *       thrown.
 482      *
 483      *   <li>If readUnshared returns successfully, then any subsequent attempts
 484      *       to deserialize back-references to the stream handle deserialized
 485      *       by readUnshared will cause an ObjectStreamException to be thrown.
 486      * </ul>
 487      * Deserializing an object via readUnshared invalidates the stream handle
 488      * associated with the returned object.  Note that this in itself does not
 489      * always guarantee that the reference returned by readUnshared is unique;
 490      * the deserialized object may define a readResolve method which returns an
 491      * object visible to other parties, or readUnshared may return a Class
 492      * object or enum constant obtainable elsewhere in the stream or through
 493      * external means. If the deserialized object defines a readResolve method
 494      * and the invocation of that method returns an array, then readUnshared
 495      * returns a shallow clone of that array; this guarantees that the returned
 496      * array object is unique and cannot be obtained a second time from an
 497      * invocation of readObject or readUnshared on the ObjectInputStream,
 498      * even if the underlying data stream has been manipulated.
 499      *
 500      * <p>The serialization filter, when not {@code null}, is invoked for
 501      * each object (regular or class) read to reconstruct the root object.
 502      * See {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter} for details.
 503      *
 504      * <p>ObjectInputStream subclasses which override this method can only be
 505      * constructed in security contexts possessing the
 506      * "enableSubclassImplementation" SerializablePermission; any attempt to
 507      * instantiate such a subclass without this permission will cause a
 508      * SecurityException to be thrown.
 509      *
 510      * @return  reference to deserialized object
 511      * @throws  ClassNotFoundException if class of an object to deserialize
 512      *          cannot be found
 513      * @throws  StreamCorruptedException if control information in the stream
 514      *          is inconsistent
 515      * @throws  ObjectStreamException if object to deserialize has already
 516      *          appeared in stream
 517      * @throws  OptionalDataException if primitive data is next in stream
 518      * @throws  IOException if an I/O error occurs during deserialization
 519      * @since   1.4
 520      */
 521     public Object readUnshared() throws IOException, ClassNotFoundException {
 522         // if nested read, passHandle contains handle of enclosing object
 523         int outerHandle = passHandle;
 524         try {
 525             Object obj = readObject0(true);
 526             handles.markDependency(outerHandle, passHandle);
 527             ClassNotFoundException ex = handles.lookupException(passHandle);
 528             if (ex != null) {
 529                 throw ex;
 530             }
 531             if (depth == 0) {
 532                 vlist.doCallbacks();
 533                 freeze();
 534             }
 535             return obj;
 536         } finally {
 537             passHandle = outerHandle;
 538             if (closed && depth == 0) {
 539                 clear();
 540             }
 541         }
 542     }
 543 
 544     /**
 545      * Read the non-static and non-transient fields of the current class from
 546      * this stream.  This may only be called from the readObject method of the
 547      * class being deserialized. It will throw the NotActiveException if it is
 548      * called otherwise.
 549      *
 550      * @throws  ClassNotFoundException if the class of a serialized object
 551      *          could not be found.
 552      * @throws  IOException if an I/O error occurs.
 553      * @throws  NotActiveException if the stream is not currently reading
 554      *          objects.
 555      */
 556     public void defaultReadObject()
 557         throws IOException, ClassNotFoundException
 558     {
 559         SerialCallbackContext ctx = curContext;
 560         if (ctx == null) {
 561             throw new NotActiveException("not in call to readObject");
 562         }
 563         Object curObj = ctx.getObj();
 564         ObjectStreamClass curDesc = ctx.getDesc();
 565         bin.setBlockDataMode(false);
 566         FieldValues vals = defaultReadFields(curObj, curDesc);
 567         if (curObj != null) {
 568             defaultCheckFieldValues(curObj, curDesc, vals);
 569             defaultSetFieldValues(curObj, curDesc, vals);
 570         }
 571         bin.setBlockDataMode(true);
 572         if (!curDesc.hasWriteObjectData()) {
 573             /*
 574              * Fix for 4360508: since stream does not contain terminating
 575              * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
 576              * knows to simulate end-of-custom-data behavior.
 577              */
 578             defaultDataEnd = true;
 579         }
 580         ClassNotFoundException ex = handles.lookupException(passHandle);
 581         if (ex != null) {
 582             throw ex;
 583         }
 584     }
 585 
 586     /**
 587      * Reads the persistent fields from the stream and makes them available by
 588      * name.
 589      *
 590      * @return  the <code>GetField</code> object representing the persistent
 591      *          fields of the object being deserialized
 592      * @throws  ClassNotFoundException if the class of a serialized object
 593      *          could not be found.
 594      * @throws  IOException if an I/O error occurs.
 595      * @throws  NotActiveException if the stream is not currently reading
 596      *          objects.
 597      * @since 1.2
 598      */
 599     public ObjectInputStream.GetField readFields()
 600         throws IOException, ClassNotFoundException
 601     {
 602         SerialCallbackContext ctx = curContext;
 603         if (ctx == null) {
 604             throw new NotActiveException("not in call to readObject");
 605         }
 606         ctx.checkAndSetUsed();
 607         ObjectStreamClass curDesc = ctx.getDesc();
 608         bin.setBlockDataMode(false);
 609         GetFieldImpl getField = new GetFieldImpl(curDesc);
 610         getField.readFields();
 611         bin.setBlockDataMode(true);
 612         if (!curDesc.hasWriteObjectData()) {
 613             /*
 614              * Fix for 4360508: since stream does not contain terminating
 615              * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
 616              * knows to simulate end-of-custom-data behavior.
 617              */
 618             defaultDataEnd = true;
 619         }
 620 
 621         return getField;
 622     }
 623 
 624     /**
 625      * Register an object to be validated before the graph is returned.  While
 626      * similar to resolveObject these validations are called after the entire
 627      * graph has been reconstituted.  Typically, a readObject method will
 628      * register the object with the stream so that when all of the objects are
 629      * restored a final set of validations can be performed.
 630      *
 631      * @param   obj the object to receive the validation callback.
 632      * @param   prio controls the order of callbacks;zero is a good default.
 633      *          Use higher numbers to be called back earlier, lower numbers for
 634      *          later callbacks. Within a priority, callbacks are processed in
 635      *          no particular order.
 636      * @throws  NotActiveException The stream is not currently reading objects
 637      *          so it is invalid to register a callback.
 638      * @throws  InvalidObjectException The validation object is null.
 639      */
 640     public void registerValidation(ObjectInputValidation obj, int prio)
 641         throws NotActiveException, InvalidObjectException
 642     {
 643         if (depth == 0) {
 644             throw new NotActiveException("stream inactive");
 645         }
 646         vlist.register(obj, prio);
 647     }
 648 
 649     /**
 650      * Load the local class equivalent of the specified stream class
 651      * description.  Subclasses may implement this method to allow classes to
 652      * be fetched from an alternate source.
 653      *
 654      * <p>The corresponding method in <code>ObjectOutputStream</code> is
 655      * <code>annotateClass</code>.  This method will be invoked only once for
 656      * each unique class in the stream.  This method can be implemented by
 657      * subclasses to use an alternate loading mechanism but must return a
 658      * <code>Class</code> object. Once returned, if the class is not an array
 659      * class, its serialVersionUID is compared to the serialVersionUID of the
 660      * serialized class, and if there is a mismatch, the deserialization fails
 661      * and an {@link InvalidClassException} is thrown.
 662      *
 663      * <p>The default implementation of this method in
 664      * <code>ObjectInputStream</code> returns the result of calling
 665      * <pre>
 666      *     Class.forName(desc.getName(), false, loader)
 667      * </pre>
 668      * where <code>loader</code> is the first class loader on the current
 669      * thread's stack (starting from the currently executing method) that is
 670      * neither the {@linkplain ClassLoader#getPlatformClassLoader() platform
 671      * class loader} nor its ancestor; otherwise, <code>loader</code> is the
 672      * <em>platform class loader</em>. If this call results in a
 673      * <code>ClassNotFoundException</code> and the name of the passed
 674      * <code>ObjectStreamClass</code> instance is the Java language keyword
 675      * for a primitive type or void, then the <code>Class</code> object
 676      * representing that primitive type or void will be returned
 677      * (e.g., an <code>ObjectStreamClass</code> with the name
 678      * <code>"int"</code> will be resolved to <code>Integer.TYPE</code>).
 679      * Otherwise, the <code>ClassNotFoundException</code> will be thrown to
 680      * the caller of this method.
 681      *
 682      * @param   desc an instance of class <code>ObjectStreamClass</code>
 683      * @return  a <code>Class</code> object corresponding to <code>desc</code>
 684      * @throws  IOException any of the usual Input/Output exceptions.
 685      * @throws  ClassNotFoundException if class of a serialized object cannot
 686      *          be found.
 687      */
 688     protected Class<?> resolveClass(ObjectStreamClass desc)
 689         throws IOException, ClassNotFoundException
 690     {
 691         String name = desc.getName();
 692         try {
 693             return Class.forName(name, false, latestUserDefinedLoader());
 694         } catch (ClassNotFoundException ex) {
 695             Class<?> cl = primClasses.get(name);
 696             if (cl != null) {
 697                 return cl;
 698             } else {
 699                 throw ex;
 700             }
 701         }
 702     }
 703 
 704     /**
 705      * Returns a proxy class that implements the interfaces named in a proxy
 706      * class descriptor; subclasses may implement this method to read custom
 707      * data from the stream along with the descriptors for dynamic proxy
 708      * classes, allowing them to use an alternate loading mechanism for the
 709      * interfaces and the proxy class.
 710      *
 711      * <p>This method is called exactly once for each unique proxy class
 712      * descriptor in the stream.
 713      *
 714      * <p>The corresponding method in <code>ObjectOutputStream</code> is
 715      * <code>annotateProxyClass</code>.  For a given subclass of
 716      * <code>ObjectInputStream</code> that overrides this method, the
 717      * <code>annotateProxyClass</code> method in the corresponding subclass of
 718      * <code>ObjectOutputStream</code> must write any data or objects read by
 719      * this method.
 720      *
 721      * <p>The default implementation of this method in
 722      * <code>ObjectInputStream</code> returns the result of calling
 723      * <code>Proxy.getProxyClass</code> with the list of <code>Class</code>
 724      * objects for the interfaces that are named in the <code>interfaces</code>
 725      * parameter.  The <code>Class</code> object for each interface name
 726      * <code>i</code> is the value returned by calling
 727      * <pre>
 728      *     Class.forName(i, false, loader)
 729      * </pre>
 730      * where <code>loader</code> is the first class loader on the current
 731      * thread's stack (starting from the currently executing method) that is
 732      * neither the {@linkplain ClassLoader#getPlatformClassLoader() platform
 733      * class loader} nor its ancestor; otherwise, <code>loader</code> is the
 734      * <em>platform class loader</em>.
 735      * Unless any of the resolved interfaces are non-public, this same value
 736      * of <code>loader</code> is also the class loader passed to
 737      * <code>Proxy.getProxyClass</code>; if non-public interfaces are present,
 738      * their class loader is passed instead (if more than one non-public
 739      * interface class loader is encountered, an
 740      * <code>IllegalAccessError</code> is thrown).
 741      * If <code>Proxy.getProxyClass</code> throws an
 742      * <code>IllegalArgumentException</code>, <code>resolveProxyClass</code>
 743      * will throw a <code>ClassNotFoundException</code> containing the
 744      * <code>IllegalArgumentException</code>.
 745      *
 746      * @param interfaces the list of interface names that were
 747      *                deserialized in the proxy class descriptor
 748      * @return  a proxy class for the specified interfaces
 749      * @throws        IOException any exception thrown by the underlying
 750      *                <code>InputStream</code>
 751      * @throws        ClassNotFoundException if the proxy class or any of the
 752      *                named interfaces could not be found
 753      * @see ObjectOutputStream#annotateProxyClass(Class)
 754      * @since 1.3
 755      */
 756     protected Class<?> resolveProxyClass(String[] interfaces)
 757         throws IOException, ClassNotFoundException
 758     {
 759         ClassLoader latestLoader = latestUserDefinedLoader();
 760         ClassLoader nonPublicLoader = null;
 761         boolean hasNonPublicInterface = false;
 762 
 763         // define proxy in class loader of non-public interface(s), if any
 764         Class<?>[] classObjs = new Class<?>[interfaces.length];
 765         for (int i = 0; i < interfaces.length; i++) {
 766             Class<?> cl = Class.forName(interfaces[i], false, latestLoader);
 767             if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
 768                 if (hasNonPublicInterface) {
 769                     if (nonPublicLoader != cl.getClassLoader()) {
 770                         throw new IllegalAccessError(
 771                             "conflicting non-public interface class loaders");
 772                     }
 773                 } else {
 774                     nonPublicLoader = cl.getClassLoader();
 775                     hasNonPublicInterface = true;
 776                 }
 777             }
 778             classObjs[i] = cl;
 779         }
 780         try {
 781             @SuppressWarnings("deprecation")
 782             Class<?> proxyClass = Proxy.getProxyClass(
 783                 hasNonPublicInterface ? nonPublicLoader : latestLoader,
 784                 classObjs);
 785             return proxyClass;
 786         } catch (IllegalArgumentException e) {
 787             throw new ClassNotFoundException(null, e);
 788         }
 789     }
 790 
 791     /**
 792      * This method will allow trusted subclasses of ObjectInputStream to
 793      * substitute one object for another during deserialization. Replacing
 794      * objects is disabled until enableResolveObject is called. The
 795      * enableResolveObject method checks that the stream requesting to resolve
 796      * object can be trusted. Every reference to serializable objects is passed
 797      * to resolveObject.  To insure that the private state of objects is not
 798      * unintentionally exposed only trusted streams may use resolveObject.
 799      *
 800      * <p>This method is called after an object has been read but before it is
 801      * returned from readObject.  The default resolveObject method just returns
 802      * the same object.
 803      *
 804      * <p>When a subclass is replacing objects it must insure that the
 805      * substituted object is compatible with every field where the reference
 806      * will be stored.  Objects whose type is not a subclass of the type of the
 807      * field or array element abort the serialization by raising an exception
 808      * and the object is not be stored.
 809      *
 810      * <p>This method is called only once when each object is first
 811      * encountered.  All subsequent references to the object will be redirected
 812      * to the new object.
 813      *
 814      * @param   obj object to be substituted
 815      * @return  the substituted object
 816      * @throws  IOException Any of the usual Input/Output exceptions.
 817      */
 818     protected Object resolveObject(Object obj) throws IOException {
 819         return obj;
 820     }
 821 
 822     /**
 823      * Enables the stream to do replacement of objects read from the stream. When
 824      * enabled, the {@link #resolveObject} method is called for every object being
 825      * deserialized.
 826      *
 827      * <p>If object replacement is currently not enabled, and
 828      * {@code enable} is true, and there is a security manager installed,
 829      * this method first calls the security manager's
 830      * {@code checkPermission} method with the
 831      * {@code SerializablePermission("enableSubstitution")} permission to
 832      * ensure that the caller is permitted to enable the stream to do replacement
 833      * of objects read from the stream.
 834      *
 835      * @param   enable true for enabling use of {@code resolveObject} for
 836      *          every object being deserialized
 837      * @return  the previous setting before this method was invoked
 838      * @throws  SecurityException if a security manager exists and its
 839      *          {@code checkPermission} method denies enabling the stream
 840      *          to do replacement of objects read from the stream.
 841      * @see SecurityManager#checkPermission
 842      * @see java.io.SerializablePermission
 843      */
 844     protected boolean enableResolveObject(boolean enable)
 845         throws SecurityException
 846     {
 847         if (enable == enableResolve) {
 848             return enable;
 849         }
 850         if (enable) {
 851             SecurityManager sm = System.getSecurityManager();
 852             if (sm != null) {
 853                 sm.checkPermission(SUBSTITUTION_PERMISSION);
 854             }
 855         }
 856         enableResolve = enable;
 857         return !enableResolve;
 858     }
 859 
 860     /**
 861      * The readStreamHeader method is provided to allow subclasses to read and
 862      * verify their own stream headers. It reads and verifies the magic number
 863      * and version number.
 864      *
 865      * @throws  IOException if there are I/O errors while reading from the
 866      *          underlying <code>InputStream</code>
 867      * @throws  StreamCorruptedException if control information in the stream
 868      *          is inconsistent
 869      */
 870     protected void readStreamHeader()
 871         throws IOException, StreamCorruptedException
 872     {
 873         short s0 = bin.readShort();
 874         short s1 = bin.readShort();
 875         if (s0 != STREAM_MAGIC || s1 != STREAM_VERSION) {
 876             throw new StreamCorruptedException(
 877                 String.format("invalid stream header: %04X%04X", s0, s1));
 878         }
 879     }
 880 
 881     /**
 882      * Read a class descriptor from the serialization stream.  This method is
 883      * called when the ObjectInputStream expects a class descriptor as the next
 884      * item in the serialization stream.  Subclasses of ObjectInputStream may
 885      * override this method to read in class descriptors that have been written
 886      * in non-standard formats (by subclasses of ObjectOutputStream which have
 887      * overridden the <code>writeClassDescriptor</code> method).  By default,
 888      * this method reads class descriptors according to the format defined in
 889      * the Object Serialization specification.
 890      *
 891      * @return  the class descriptor read
 892      * @throws  IOException If an I/O error has occurred.
 893      * @throws  ClassNotFoundException If the Class of a serialized object used
 894      *          in the class descriptor representation cannot be found
 895      * @see java.io.ObjectOutputStream#writeClassDescriptor(java.io.ObjectStreamClass)
 896      * @since 1.3
 897      */
 898     protected ObjectStreamClass readClassDescriptor()
 899         throws IOException, ClassNotFoundException
 900     {
 901         ObjectStreamClass desc = new ObjectStreamClass();
 902         desc.readNonProxy(this);
 903         return desc;
 904     }
 905 
 906     /**
 907      * Reads a byte of data. This method will block if no input is available.
 908      *
 909      * @return  the byte read, or -1 if the end of the stream is reached.
 910      * @throws  IOException If an I/O error has occurred.
 911      */
 912     public int read() throws IOException {
 913         return bin.read();
 914     }
 915 
 916     /**
 917      * Reads into an array of bytes.  This method will block until some input
 918      * is available. Consider using java.io.DataInputStream.readFully to read
 919      * exactly 'length' bytes.
 920      *
 921      * @param   buf the buffer into which the data is read
 922      * @param   off the start offset in the destination array {@code buf}
 923      * @param   len the maximum number of bytes read
 924      * @return  the actual number of bytes read, -1 is returned when the end of
 925      *          the stream is reached.
 926      * @throws  NullPointerException if {@code buf} is {@code null}.
 927      * @throws  IndexOutOfBoundsException if {@code off} is negative,
 928      *          {@code len} is negative, or {@code len} is greater than
 929      *          {@code buf.length - off}.
 930      * @throws  IOException If an I/O error has occurred.
 931      * @see java.io.DataInputStream#readFully(byte[],int,int)
 932      */
 933     public int read(byte[] buf, int off, int len) throws IOException {
 934         if (buf == null) {
 935             throw new NullPointerException();
 936         }
 937         int endoff = off + len;
 938         if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
 939             throw new IndexOutOfBoundsException();
 940         }
 941         return bin.read(buf, off, len, false);
 942     }
 943 
 944     /**
 945      * Returns the number of bytes that can be read without blocking.
 946      *
 947      * @return  the number of available bytes.
 948      * @throws  IOException if there are I/O errors while reading from the
 949      *          underlying <code>InputStream</code>
 950      */
 951     public int available() throws IOException {
 952         return bin.available();
 953     }
 954 
 955     /**
 956      * Closes the input stream. Must be called to release any resources
 957      * associated with the stream.
 958      *
 959      * @throws  IOException If an I/O error has occurred.
 960      */
 961     public void close() throws IOException {
 962         /*
 963          * Even if stream already closed, propagate redundant close to
 964          * underlying stream to stay consistent with previous implementations.
 965          */
 966         closed = true;
 967         if (depth == 0) {
 968             clear();
 969         }
 970         bin.close();
 971     }
 972 
 973     /**
 974      * Reads in a boolean.
 975      *
 976      * @return  the boolean read.
 977      * @throws  EOFException If end of file is reached.
 978      * @throws  IOException If other I/O error has occurred.
 979      */
 980     public boolean readBoolean() throws IOException {
 981         return bin.readBoolean();
 982     }
 983 
 984     /**
 985      * Reads an 8 bit byte.
 986      *
 987      * @return  the 8 bit byte read.
 988      * @throws  EOFException If end of file is reached.
 989      * @throws  IOException If other I/O error has occurred.
 990      */
 991     public byte readByte() throws IOException  {
 992         return bin.readByte();
 993     }
 994 
 995     /**
 996      * Reads an unsigned 8 bit byte.
 997      *
 998      * @return  the 8 bit byte read.
 999      * @throws  EOFException If end of file is reached.
1000      * @throws  IOException If other I/O error has occurred.
1001      */
1002     public int readUnsignedByte()  throws IOException {
1003         return bin.readUnsignedByte();
1004     }
1005 
1006     /**
1007      * Reads a 16 bit char.
1008      *
1009      * @return  the 16 bit char read.
1010      * @throws  EOFException If end of file is reached.
1011      * @throws  IOException If other I/O error has occurred.
1012      */
1013     public char readChar()  throws IOException {
1014         return bin.readChar();
1015     }
1016 
1017     /**
1018      * Reads a 16 bit short.
1019      *
1020      * @return  the 16 bit short read.
1021      * @throws  EOFException If end of file is reached.
1022      * @throws  IOException If other I/O error has occurred.
1023      */
1024     public short readShort()  throws IOException {
1025         return bin.readShort();
1026     }
1027 
1028     /**
1029      * Reads an unsigned 16 bit short.
1030      *
1031      * @return  the 16 bit short read.
1032      * @throws  EOFException If end of file is reached.
1033      * @throws  IOException If other I/O error has occurred.
1034      */
1035     public int readUnsignedShort() throws IOException {
1036         return bin.readUnsignedShort();
1037     }
1038 
1039     /**
1040      * Reads a 32 bit int.
1041      *
1042      * @return  the 32 bit integer read.
1043      * @throws  EOFException If end of file is reached.
1044      * @throws  IOException If other I/O error has occurred.
1045      */
1046     public int readInt()  throws IOException {
1047         return bin.readInt();
1048     }
1049 
1050     /**
1051      * Reads a 64 bit long.
1052      *
1053      * @return  the read 64 bit long.
1054      * @throws  EOFException If end of file is reached.
1055      * @throws  IOException If other I/O error has occurred.
1056      */
1057     public long readLong()  throws IOException {
1058         return bin.readLong();
1059     }
1060 
1061     /**
1062      * Reads a 32 bit float.
1063      *
1064      * @return  the 32 bit float read.
1065      * @throws  EOFException If end of file is reached.
1066      * @throws  IOException If other I/O error has occurred.
1067      */
1068     public float readFloat() throws IOException {
1069         return bin.readFloat();
1070     }
1071 
1072     /**
1073      * Reads a 64 bit double.
1074      *
1075      * @return  the 64 bit double read.
1076      * @throws  EOFException If end of file is reached.
1077      * @throws  IOException If other I/O error has occurred.
1078      */
1079     public double readDouble() throws IOException {
1080         return bin.readDouble();
1081     }
1082 
1083     /**
1084      * Reads bytes, blocking until all bytes are read.
1085      *
1086      * @param   buf the buffer into which the data is read
1087      * @throws  NullPointerException If {@code buf} is {@code null}.
1088      * @throws  EOFException If end of file is reached.
1089      * @throws  IOException If other I/O error has occurred.
1090      */
1091     public void readFully(byte[] buf) throws IOException {
1092         bin.readFully(buf, 0, buf.length, false);
1093     }
1094 
1095     /**
1096      * Reads bytes, blocking until all bytes are read.
1097      *
1098      * @param   buf the buffer into which the data is read
1099      * @param   off the start offset into the data array {@code buf}
1100      * @param   len the maximum number of bytes to read
1101      * @throws  NullPointerException If {@code buf} is {@code null}.
1102      * @throws  IndexOutOfBoundsException If {@code off} is negative,
1103      *          {@code len} is negative, or {@code len} is greater than
1104      *          {@code buf.length - off}.
1105      * @throws  EOFException If end of file is reached.
1106      * @throws  IOException If other I/O error has occurred.
1107      */
1108     public void readFully(byte[] buf, int off, int len) throws IOException {
1109         int endoff = off + len;
1110         if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
1111             throw new IndexOutOfBoundsException();
1112         }
1113         bin.readFully(buf, off, len, false);
1114     }
1115 
1116     /**
1117      * Skips bytes.
1118      *
1119      * @param   len the number of bytes to be skipped
1120      * @return  the actual number of bytes skipped.
1121      * @throws  IOException If an I/O error has occurred.
1122      */
1123     public int skipBytes(int len) throws IOException {
1124         return bin.skipBytes(len);
1125     }
1126 
1127     /**
1128      * Reads in a line that has been terminated by a \n, \r, \r\n or EOF.
1129      *
1130      * @return  a String copy of the line.
1131      * @throws  IOException if there are I/O errors while reading from the
1132      *          underlying <code>InputStream</code>
1133      * @deprecated This method does not properly convert bytes to characters.
1134      *          see DataInputStream for the details and alternatives.
1135      */
1136     @Deprecated
1137     public String readLine() throws IOException {
1138         return bin.readLine();
1139     }
1140 
1141     /**
1142      * Reads a String in
1143      * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
1144      * format.
1145      *
1146      * @return  the String.
1147      * @throws  IOException if there are I/O errors while reading from the
1148      *          underlying <code>InputStream</code>
1149      * @throws  UTFDataFormatException if read bytes do not represent a valid
1150      *          modified UTF-8 encoding of a string
1151      */
1152     public String readUTF() throws IOException {
1153         return bin.readUTF();
1154     }
1155 
1156     /**
1157      * Returns the serialization filter for this stream.
1158      * The serialization filter is the most recent filter set in
1159      * {@link #setObjectInputFilter setObjectInputFilter} or
1160      * the initial process-wide filter from
1161      * {@link ObjectInputFilter.Config#getSerialFilter() ObjectInputFilter.Config.getSerialFilter}.
1162      *
1163      * @return the serialization filter for the stream; may be null
1164      * @since 9
1165      */
1166     public final ObjectInputFilter getObjectInputFilter() {
1167         return serialFilter;
1168     }
1169 
1170     /**
1171      * Set the serialization filter for the stream.
1172      * The filter's {@link ObjectInputFilter#checkInput checkInput} method is called
1173      * for each class and reference in the stream.
1174      * The filter can check any or all of the class, the array length, the number
1175      * of references, the depth of the graph, and the size of the input stream.
1176      * The depth is the number of nested {@linkplain #readObject readObject}
1177      * calls starting with the reading of the root of the graph being deserialized
1178      * and the current object being deserialized.
1179      * The number of references is the cumulative number of objects and references
1180      * to objects already read from the stream including the current object being read.
1181      * The filter is invoked only when reading objects from the stream and for
1182      * not primitives.
1183      * <p>
1184      * If the filter returns {@link ObjectInputFilter.Status#REJECTED Status.REJECTED},
1185      * {@code null} or throws a {@link RuntimeException},
1186      * the active {@code readObject} or {@code readUnshared}
1187      * throws {@link InvalidClassException}, otherwise deserialization
1188      * continues uninterrupted.
1189      * <p>
1190      * The serialization filter is initialized to the value of
1191      * {@link ObjectInputFilter.Config#getSerialFilter() ObjectInputFilter.Config.getSerialFilter}
1192      * when the {@code  ObjectInputStream} is constructed and can be set
1193      * to a custom filter only once.
1194      *
1195      * @implSpec
1196      * The filter, when not {@code null}, is invoked during {@link #readObject readObject}
1197      * and {@link #readUnshared readUnshared} for each object (regular or class) in the stream.
1198      * Strings are treated as primitives and do not invoke the filter.
1199      * The filter is called for:
1200      * <ul>
1201      *     <li>each object reference previously deserialized from the stream
1202      *     (class is {@code null}, arrayLength is -1),
1203      *     <li>each regular class (class is not {@code null}, arrayLength is -1),
1204      *     <li>each interface of a dynamic proxy and the dynamic proxy class itself
1205      *     (class is not {@code null}, arrayLength is -1),
1206      *     <li>each array is filtered using the array type and length of the array
1207      *     (class is the array type, arrayLength is the requested length),
1208      *     <li>each object replaced by its class' {@code readResolve} method
1209      *         is filtered using the replacement object's class, if not {@code null},
1210      *         and if it is an array, the arrayLength, otherwise -1,
1211      *     <li>and each object replaced by {@link #resolveObject resolveObject}
1212      *         is filtered using the replacement object's class, if not {@code null},
1213      *         and if it is an array, the arrayLength, otherwise -1.
1214      * </ul>
1215      *
1216      * When the {@link ObjectInputFilter#checkInput checkInput} method is invoked
1217      * it is given access to the current class, the array length,
1218      * the current number of references already read from the stream,
1219      * the depth of nested calls to {@link #readObject readObject} or
1220      * {@link #readUnshared readUnshared},
1221      * and the implementation dependent number of bytes consumed from the input stream.
1222      * <p>
1223      * Each call to {@link #readObject readObject} or
1224      * {@link #readUnshared readUnshared} increases the depth by 1
1225      * before reading an object and decreases by 1 before returning
1226      * normally or exceptionally.
1227      * The depth starts at {@code 1} and increases for each nested object and
1228      * decrements when each nested call returns.
1229      * The count of references in the stream starts at {@code 1} and
1230      * is increased before reading an object.
1231      *
1232      * @param filter the filter, may be null
1233      * @throws SecurityException if there is security manager and the
1234      *       {@code SerializablePermission("serialFilter")} is not granted
1235      * @throws IllegalStateException if the {@linkplain #getObjectInputFilter() current filter}
1236      *       is not {@code null} and is not the process-wide filter
1237      * @since 9
1238      */
1239     public final void setObjectInputFilter(ObjectInputFilter filter) {
1240         SecurityManager sm = System.getSecurityManager();
1241         if (sm != null) {
1242             sm.checkPermission(ObjectStreamConstants.SERIAL_FILTER_PERMISSION);
1243         }
1244         // Allow replacement of the process-wide filter if not already set
1245         if (serialFilter != null &&
1246                 serialFilter != ObjectInputFilter.Config.getSerialFilter()) {
1247             throw new IllegalStateException("filter can not be set more than once");
1248         }
1249         this.serialFilter = filter;
1250     }
1251 
1252     /**
1253      * Invoke the serialization filter if non-null.
1254      * If the filter rejects or an exception is thrown, throws InvalidClassException.
1255      *
1256      * @param clazz the class; may be null
1257      * @param arrayLength the array length requested; use {@code -1} if not creating an array
1258      * @throws InvalidClassException if it rejected by the filter or
1259      *        a {@link RuntimeException} is thrown
1260      */
1261     private void filterCheck(Class<?> clazz, int arrayLength)
1262             throws InvalidClassException {
1263         if (serialFilter != null) {
1264             RuntimeException ex = null;
1265             ObjectInputFilter.Status status;
1266             try {
1267                 status = serialFilter.checkInput(new FilterValues(clazz, arrayLength,
1268                         totalObjectRefs, depth, bin.getBytesRead()));
1269             } catch (RuntimeException e) {
1270                 // Preventive interception of an exception to log
1271                 status = ObjectInputFilter.Status.REJECTED;
1272                 ex = e;
1273             }
1274             if (Logging.filterLogger != null) {
1275                 // Debug logging of filter checks that fail; Tracing for those that succeed
1276                 Logging.filterLogger.log(status == null || status == ObjectInputFilter.Status.REJECTED
1277                                 ? Logger.Level.DEBUG
1278                                 : Logger.Level.TRACE,
1279                         "ObjectInputFilter {0}: {1}, array length: {2}, nRefs: {3}, depth: {4}, bytes: {5}, ex: {6}",
1280                         status, clazz, arrayLength, totalObjectRefs, depth, bin.getBytesRead(),
1281                         Objects.toString(ex, "n/a"));
1282             }
1283             if (status == null ||
1284                     status == ObjectInputFilter.Status.REJECTED) {
1285                 InvalidClassException ice = new InvalidClassException("filter status: " + status);
1286                 ice.initCause(ex);
1287                 throw ice;
1288             }
1289         }
1290     }
1291 
1292     /**
1293      * Checks the given array type and length to ensure that creation of such
1294      * an array is permitted by this ObjectInputStream. The arrayType argument
1295      * must represent an actual array type.
1296      *
1297      * This private method is called via SharedSecrets.
1298      *
1299      * @param arrayType the array type
1300      * @param arrayLength the array length
1301      * @throws NullPointerException if arrayType is null
1302      * @throws IllegalArgumentException if arrayType isn't actually an array type
1303      * @throws NegativeArraySizeException if arrayLength is negative
1304      * @throws InvalidClassException if the filter rejects creation
1305      */
1306     private void checkArray(Class<?> arrayType, int arrayLength) throws InvalidClassException {
1307         if (! arrayType.isArray()) {
1308             throw new IllegalArgumentException("not an array type");
1309         }
1310 
1311         if (arrayLength < 0) {
1312             throw new NegativeArraySizeException();
1313         }
1314 
1315         filterCheck(arrayType, arrayLength);
1316     }
1317 
1318     /**
1319      * Provide access to the persistent fields read from the input stream.
1320      */
1321     public abstract static class GetField {
1322 
1323         /**
1324          * Get the ObjectStreamClass that describes the fields in the stream.
1325          *
1326          * @return  the descriptor class that describes the serializable fields
1327          */
1328         public abstract ObjectStreamClass getObjectStreamClass();
1329 
1330         /**
1331          * Return true if the named field is defaulted and has no value in this
1332          * stream.
1333          *
1334          * @param  name the name of the field
1335          * @return true, if and only if the named field is defaulted
1336          * @throws IOException if there are I/O errors while reading from
1337          *         the underlying <code>InputStream</code>
1338          * @throws IllegalArgumentException if <code>name</code> does not
1339          *         correspond to a serializable field
1340          */
1341         public abstract boolean defaulted(String name) throws IOException;
1342 
1343         /**
1344          * Get the value of the named boolean field from the persistent field.
1345          *
1346          * @param  name the name of the field
1347          * @param  val the default value to use if <code>name</code> does not
1348          *         have a value
1349          * @return the value of the named <code>boolean</code> field
1350          * @throws IOException if there are I/O errors while reading from the
1351          *         underlying <code>InputStream</code>
1352          * @throws IllegalArgumentException if type of <code>name</code> is
1353          *         not serializable or if the field type is incorrect
1354          */
1355         public abstract boolean get(String name, boolean val)
1356             throws IOException;
1357 
1358         /**
1359          * Get the value of the named byte field from the persistent field.
1360          *
1361          * @param  name the name of the field
1362          * @param  val the default value to use if <code>name</code> does not
1363          *         have a value
1364          * @return the value of the named <code>byte</code> field
1365          * @throws IOException if there are I/O errors while reading from the
1366          *         underlying <code>InputStream</code>
1367          * @throws IllegalArgumentException if type of <code>name</code> is
1368          *         not serializable or if the field type is incorrect
1369          */
1370         public abstract byte get(String name, byte val) throws IOException;
1371 
1372         /**
1373          * Get the value of the named char field from the persistent field.
1374          *
1375          * @param  name the name of the field
1376          * @param  val the default value to use if <code>name</code> does not
1377          *         have a value
1378          * @return the value of the named <code>char</code> field
1379          * @throws IOException if there are I/O errors while reading from the
1380          *         underlying <code>InputStream</code>
1381          * @throws IllegalArgumentException if type of <code>name</code> is
1382          *         not serializable or if the field type is incorrect
1383          */
1384         public abstract char get(String name, char val) throws IOException;
1385 
1386         /**
1387          * Get the value of the named short field from the persistent field.
1388          *
1389          * @param  name the name of the field
1390          * @param  val the default value to use if <code>name</code> does not
1391          *         have a value
1392          * @return the value of the named <code>short</code> field
1393          * @throws IOException if there are I/O errors while reading from the
1394          *         underlying <code>InputStream</code>
1395          * @throws IllegalArgumentException if type of <code>name</code> is
1396          *         not serializable or if the field type is incorrect
1397          */
1398         public abstract short get(String name, short val) throws IOException;
1399 
1400         /**
1401          * Get the value of the named int field from the persistent field.
1402          *
1403          * @param  name the name of the field
1404          * @param  val the default value to use if <code>name</code> does not
1405          *         have a value
1406          * @return the value of the named <code>int</code> field
1407          * @throws IOException if there are I/O errors while reading from the
1408          *         underlying <code>InputStream</code>
1409          * @throws IllegalArgumentException if type of <code>name</code> is
1410          *         not serializable or if the field type is incorrect
1411          */
1412         public abstract int get(String name, int val) throws IOException;
1413 
1414         /**
1415          * Get the value of the named long field from the persistent field.
1416          *
1417          * @param  name the name of the field
1418          * @param  val the default value to use if <code>name</code> does not
1419          *         have a value
1420          * @return the value of the named <code>long</code> field
1421          * @throws IOException if there are I/O errors while reading from the
1422          *         underlying <code>InputStream</code>
1423          * @throws IllegalArgumentException if type of <code>name</code> is
1424          *         not serializable or if the field type is incorrect
1425          */
1426         public abstract long get(String name, long val) throws IOException;
1427 
1428         /**
1429          * Get the value of the named float field from the persistent field.
1430          *
1431          * @param  name the name of the field
1432          * @param  val the default value to use if <code>name</code> does not
1433          *         have a value
1434          * @return the value of the named <code>float</code> field
1435          * @throws IOException if there are I/O errors while reading from the
1436          *         underlying <code>InputStream</code>
1437          * @throws IllegalArgumentException if type of <code>name</code> is
1438          *         not serializable or if the field type is incorrect
1439          */
1440         public abstract float get(String name, float val) throws IOException;
1441 
1442         /**
1443          * Get the value of the named double field from the persistent field.
1444          *
1445          * @param  name the name of the field
1446          * @param  val the default value to use if <code>name</code> does not
1447          *         have a value
1448          * @return the value of the named <code>double</code> field
1449          * @throws IOException if there are I/O errors while reading from the
1450          *         underlying <code>InputStream</code>
1451          * @throws IllegalArgumentException if type of <code>name</code> is
1452          *         not serializable or if the field type is incorrect
1453          */
1454         public abstract double get(String name, double val) throws IOException;
1455 
1456         /**
1457          * Get the value of the named Object field from the persistent field.
1458          *
1459          * @param  name the name of the field
1460          * @param  val the default value to use if <code>name</code> does not
1461          *         have a value
1462          * @return the value of the named <code>Object</code> field
1463          * @throws IOException if there are I/O errors while reading from the
1464          *         underlying <code>InputStream</code>
1465          * @throws IllegalArgumentException if type of <code>name</code> is
1466          *         not serializable or if the field type is incorrect
1467          */
1468         public abstract Object get(String name, Object val) throws IOException;
1469     }
1470 
1471     /**
1472      * Verifies that this (possibly subclass) instance can be constructed
1473      * without violating security constraints: the subclass must not override
1474      * security-sensitive non-final methods, or else the
1475      * "enableSubclassImplementation" SerializablePermission is checked.
1476      */
1477     private void verifySubclass() {
1478         Class<?> cl = getClass();
1479         if (cl == ObjectInputStream.class) {
1480             return;
1481         }
1482         SecurityManager sm = System.getSecurityManager();
1483         if (sm == null) {
1484             return;
1485         }
1486         processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1487         WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1488         Boolean result = Caches.subclassAudits.get(key);
1489         if (result == null) {
1490             result = auditSubclass(cl);
1491             Caches.subclassAudits.putIfAbsent(key, result);
1492         }
1493         if (!result) {
1494             sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
1495         }
1496     }
1497 
1498     /**
1499      * Performs reflective checks on given subclass to verify that it doesn't
1500      * override security-sensitive non-final methods.  Returns TRUE if subclass
1501      * is "safe", FALSE otherwise.
1502      */
1503     private static Boolean auditSubclass(Class<?> subcl) {
1504         return AccessController.doPrivileged(
1505             new PrivilegedAction<Boolean>() {
1506                 public Boolean run() {
1507                     for (Class<?> cl = subcl;
1508                          cl != ObjectInputStream.class;
1509                          cl = cl.getSuperclass())
1510                     {
1511                         try {
1512                             cl.getDeclaredMethod(
1513                                 "readUnshared", (Class[]) null);
1514                             return Boolean.FALSE;
1515                         } catch (NoSuchMethodException ex) {
1516                         }
1517                         try {
1518                             cl.getDeclaredMethod("readFields", (Class[]) null);
1519                             return Boolean.FALSE;
1520                         } catch (NoSuchMethodException ex) {
1521                         }
1522                     }
1523                     return Boolean.TRUE;
1524                 }
1525             }
1526         );
1527     }
1528 
1529     /**
1530      * Clears internal data structures.
1531      */
1532     private void clear() {
1533         handles.clear();
1534         vlist.clear();
1535     }
1536 
1537     /**
1538      * Underlying readObject implementation.
1539      */
1540     private Object readObject0(boolean unshared) throws IOException {
1541         boolean oldMode = bin.getBlockDataMode();
1542         if (oldMode) {
1543             int remain = bin.currentBlockRemaining();
1544             if (remain > 0) {
1545                 throw new OptionalDataException(remain);
1546             } else if (defaultDataEnd) {
1547                 /*
1548                  * Fix for 4360508: stream is currently at the end of a field
1549                  * value block written via default serialization; since there
1550                  * is no terminating TC_ENDBLOCKDATA tag, simulate
1551                  * end-of-custom-data behavior explicitly.
1552                  */
1553                 throw new OptionalDataException(true);
1554             }
1555             bin.setBlockDataMode(false);
1556         }
1557 
1558         byte tc;
1559         while ((tc = bin.peekByte()) == TC_RESET) {
1560             bin.readByte();
1561             handleReset();
1562         }
1563 
1564         depth++;
1565         totalObjectRefs++;
1566         try {
1567             switch (tc) {
1568                 case TC_NULL:
1569                     return readNull();
1570 
1571                 case TC_REFERENCE:
1572                     return readHandle(unshared);
1573 
1574                 case TC_CLASS:
1575                     return readClass(unshared);
1576 
1577                 case TC_CLASSDESC:
1578                 case TC_PROXYCLASSDESC:
1579                     return readClassDesc(unshared);
1580 
1581                 case TC_STRING:
1582                 case TC_LONGSTRING:
1583                     return checkResolve(readString(unshared));
1584 
1585                 case TC_ARRAY:
1586                     return checkResolve(readArray(unshared));
1587 
1588                 case TC_ENUM:
1589                     return checkResolve(readEnum(unshared));
1590 
1591                 case TC_OBJECT:
1592                     return checkResolve(readOrdinaryObject(unshared));
1593 
1594                 case TC_EXCEPTION:
1595                     IOException ex = readFatalException();
1596                     throw new WriteAbortedException("writing aborted", ex);
1597 
1598                 case TC_BLOCKDATA:
1599                 case TC_BLOCKDATALONG:
1600                     if (oldMode) {
1601                         bin.setBlockDataMode(true);
1602                         bin.peek();             // force header read
1603                         throw new OptionalDataException(
1604                             bin.currentBlockRemaining());
1605                     } else {
1606                         throw new StreamCorruptedException(
1607                             "unexpected block data");
1608                     }
1609 
1610                 case TC_ENDBLOCKDATA:
1611                     if (oldMode) {
1612                         throw new OptionalDataException(true);
1613                     } else {
1614                         throw new StreamCorruptedException(
1615                             "unexpected end of block data");
1616                     }
1617 
1618                 default:
1619                     throw new StreamCorruptedException(
1620                         String.format("invalid type code: %02X", tc));
1621             }
1622         } finally {
1623             depth--;
1624             bin.setBlockDataMode(oldMode);
1625         }
1626     }
1627 
1628     /**
1629      * If resolveObject has been enabled and given object does not have an
1630      * exception associated with it, calls resolveObject to determine
1631      * replacement for object, and updates handle table accordingly.  Returns
1632      * replacement object, or echoes provided object if no replacement
1633      * occurred.  Expects that passHandle is set to given object's handle prior
1634      * to calling this method.
1635      */
1636     private Object checkResolve(Object obj) throws IOException {
1637         if (!enableResolve || handles.lookupException(passHandle) != null) {
1638             return obj;
1639         }
1640         Object rep = resolveObject(obj);
1641         if (rep != obj) {
1642             // The type of the original object has been filtered but resolveObject
1643             // may have replaced it;  filter the replacement's type
1644             if (rep != null) {
1645                 if (rep.getClass().isArray()) {
1646                     filterCheck(rep.getClass(), Array.getLength(rep));
1647                 } else {
1648                     filterCheck(rep.getClass(), -1);
1649                 }
1650             }
1651             handles.setObject(passHandle, rep);
1652         }
1653         return rep;
1654     }
1655 
1656     /**
1657      * Reads string without allowing it to be replaced in stream.  Called from
1658      * within ObjectStreamClass.read().
1659      */
1660     String readTypeString() throws IOException {
1661         int oldHandle = passHandle;
1662         try {
1663             byte tc = bin.peekByte();
1664             switch (tc) {
1665                 case TC_NULL:
1666                     return (String) readNull();
1667 
1668                 case TC_REFERENCE:
1669                     return (String) readHandle(false);
1670 
1671                 case TC_STRING:
1672                 case TC_LONGSTRING:
1673                     return readString(false);
1674 
1675                 default:
1676                     throw new StreamCorruptedException(
1677                         String.format("invalid type code: %02X", tc));
1678             }
1679         } finally {
1680             passHandle = oldHandle;
1681         }
1682     }
1683 
1684     /**
1685      * Reads in null code, sets passHandle to NULL_HANDLE and returns null.
1686      */
1687     private Object readNull() throws IOException {
1688         if (bin.readByte() != TC_NULL) {
1689             throw new InternalError();
1690         }
1691         passHandle = NULL_HANDLE;
1692         return null;
1693     }
1694 
1695     /**
1696      * Reads in object handle, sets passHandle to the read handle, and returns
1697      * object associated with the handle.
1698      */
1699     private Object readHandle(boolean unshared) throws IOException {
1700         if (bin.readByte() != TC_REFERENCE) {
1701             throw new InternalError();
1702         }
1703         passHandle = bin.readInt() - baseWireHandle;
1704         if (passHandle < 0 || passHandle >= handles.size()) {
1705             throw new StreamCorruptedException(
1706                 String.format("invalid handle value: %08X", passHandle +
1707                 baseWireHandle));
1708         }
1709         if (unshared) {
1710             // REMIND: what type of exception to throw here?
1711             throw new InvalidObjectException(
1712                 "cannot read back reference as unshared");
1713         }
1714 
1715         Object obj = handles.lookupObject(passHandle);
1716         if (obj == unsharedMarker) {
1717             // REMIND: what type of exception to throw here?
1718             throw new InvalidObjectException(
1719                 "cannot read back reference to unshared object");
1720         }
1721         filterCheck(null, -1);       // just a check for number of references, depth, no class
1722         return obj;
1723     }
1724 
1725     /**
1726      * Reads in and returns class object.  Sets passHandle to class object's
1727      * assigned handle.  Returns null if class is unresolvable (in which case a
1728      * ClassNotFoundException will be associated with the class' handle in the
1729      * handle table).
1730      */
1731     private Class<?> readClass(boolean unshared) throws IOException {
1732         if (bin.readByte() != TC_CLASS) {
1733             throw new InternalError();
1734         }
1735         ObjectStreamClass desc = readClassDesc(false);
1736         Class<?> cl = desc.forClass();
1737         passHandle = handles.assign(unshared ? unsharedMarker : cl);
1738 
1739         ClassNotFoundException resolveEx = desc.getResolveException();
1740         if (resolveEx != null) {
1741             handles.markException(passHandle, resolveEx);
1742         }
1743 
1744         handles.finish(passHandle);
1745         return cl;
1746     }
1747 
1748     /**
1749      * Reads in and returns (possibly null) class descriptor.  Sets passHandle
1750      * to class descriptor's assigned handle.  If class descriptor cannot be
1751      * resolved to a class in the local VM, a ClassNotFoundException is
1752      * associated with the class descriptor's handle.
1753      */
1754     private ObjectStreamClass readClassDesc(boolean unshared)
1755         throws IOException
1756     {
1757         byte tc = bin.peekByte();
1758         ObjectStreamClass descriptor;
1759         switch (tc) {
1760             case TC_NULL:
1761                 descriptor = (ObjectStreamClass) readNull();
1762                 break;
1763             case TC_REFERENCE:
1764                 descriptor = (ObjectStreamClass) readHandle(unshared);
1765                 break;
1766             case TC_PROXYCLASSDESC:
1767                 descriptor = readProxyDesc(unshared);
1768                 break;
1769             case TC_CLASSDESC:
1770                 descriptor = readNonProxyDesc(unshared);
1771                 break;
1772             default:
1773                 throw new StreamCorruptedException(
1774                     String.format("invalid type code: %02X", tc));
1775         }
1776         return descriptor;
1777     }
1778 
1779     private boolean isCustomSubclass() {
1780         // Return true if this class is a custom subclass of ObjectInputStream
1781         return getClass().getClassLoader()
1782                     != ObjectInputStream.class.getClassLoader();
1783     }
1784 
1785     /**
1786      * Reads in and returns class descriptor for a dynamic proxy class.  Sets
1787      * passHandle to proxy class descriptor's assigned handle.  If proxy class
1788      * descriptor cannot be resolved to a class in the local VM, a
1789      * ClassNotFoundException is associated with the descriptor's handle.
1790      */
1791     private ObjectStreamClass readProxyDesc(boolean unshared)
1792         throws IOException
1793     {
1794         if (bin.readByte() != TC_PROXYCLASSDESC) {
1795             throw new InternalError();
1796         }
1797 
1798         ObjectStreamClass desc = new ObjectStreamClass();
1799         int descHandle = handles.assign(unshared ? unsharedMarker : desc);
1800         passHandle = NULL_HANDLE;
1801 
1802         int numIfaces = bin.readInt();
1803         if (numIfaces > 65535) {
1804             throw new InvalidObjectException("interface limit exceeded: "
1805                     + numIfaces);
1806         }
1807         String[] ifaces = new String[numIfaces];
1808         for (int i = 0; i < numIfaces; i++) {
1809             ifaces[i] = bin.readUTF();
1810         }
1811 
1812         Class<?> cl = null;
1813         ClassNotFoundException resolveEx = null;
1814         bin.setBlockDataMode(true);
1815         try {
1816             if ((cl = resolveProxyClass(ifaces)) == null) {
1817                 resolveEx = new ClassNotFoundException("null class");
1818             } else if (!Proxy.isProxyClass(cl)) {
1819                 throw new InvalidClassException("Not a proxy");
1820             } else {
1821                 // ReflectUtil.checkProxyPackageAccess makes a test
1822                 // equivalent to isCustomSubclass so there's no need
1823                 // to condition this call to isCustomSubclass == true here.
1824                 ReflectUtil.checkProxyPackageAccess(
1825                         getClass().getClassLoader(),
1826                         cl.getInterfaces());
1827                 // Filter the interfaces
1828                 for (Class<?> clazz : cl.getInterfaces()) {
1829                     filterCheck(clazz, -1);
1830                 }
1831             }
1832         } catch (ClassNotFoundException ex) {
1833             resolveEx = ex;
1834         }
1835 
1836         // Call filterCheck on the class before reading anything else
1837         filterCheck(cl, -1);
1838 
1839         skipCustomData();
1840 
1841         try {
1842             totalObjectRefs++;
1843             depth++;
1844             desc.initProxy(cl, resolveEx, readClassDesc(false));
1845         } finally {
1846             depth--;
1847         }
1848 
1849         handles.finish(descHandle);
1850         passHandle = descHandle;
1851         return desc;
1852     }
1853 
1854     /**
1855      * Reads in and returns class descriptor for a class that is not a dynamic
1856      * proxy class.  Sets passHandle to class descriptor's assigned handle.  If
1857      * class descriptor cannot be resolved to a class in the local VM, a
1858      * ClassNotFoundException is associated with the descriptor's handle.
1859      */
1860     private ObjectStreamClass readNonProxyDesc(boolean unshared)
1861         throws IOException
1862     {
1863         if (bin.readByte() != TC_CLASSDESC) {
1864             throw new InternalError();
1865         }
1866 
1867         ObjectStreamClass desc = new ObjectStreamClass();
1868         int descHandle = handles.assign(unshared ? unsharedMarker : desc);
1869         passHandle = NULL_HANDLE;
1870 
1871         ObjectStreamClass readDesc;
1872         try {
1873             readDesc = readClassDescriptor();
1874         } catch (ClassNotFoundException ex) {
1875             throw (IOException) new InvalidClassException(
1876                 "failed to read class descriptor").initCause(ex);
1877         }
1878 
1879         Class<?> cl = null;
1880         ClassNotFoundException resolveEx = null;
1881         bin.setBlockDataMode(true);
1882         final boolean checksRequired = isCustomSubclass();
1883         try {
1884             if ((cl = resolveClass(readDesc)) == null) {
1885                 resolveEx = new ClassNotFoundException("null class");
1886             } else if (checksRequired) {
1887                 ReflectUtil.checkPackageAccess(cl);
1888             }
1889         } catch (ClassNotFoundException ex) {
1890             resolveEx = ex;
1891         }
1892 
1893         // Call filterCheck on the class before reading anything else
1894         filterCheck(cl, -1);
1895 
1896         skipCustomData();
1897 
1898         try {
1899             totalObjectRefs++;
1900             depth++;
1901             desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false));
1902         } finally {
1903             depth--;
1904         }
1905 
1906         handles.finish(descHandle);
1907         passHandle = descHandle;
1908 
1909         return desc;
1910     }
1911 
1912     /**
1913      * Reads in and returns new string.  Sets passHandle to new string's
1914      * assigned handle.
1915      */
1916     private String readString(boolean unshared) throws IOException {
1917         String str;
1918         byte tc = bin.readByte();
1919         switch (tc) {
1920             case TC_STRING:
1921                 str = bin.readUTF();
1922                 break;
1923 
1924             case TC_LONGSTRING:
1925                 str = bin.readLongUTF();
1926                 break;
1927 
1928             default:
1929                 throw new StreamCorruptedException(
1930                     String.format("invalid type code: %02X", tc));
1931         }
1932         passHandle = handles.assign(unshared ? unsharedMarker : str);
1933         handles.finish(passHandle);
1934         return str;
1935     }
1936 
1937     /**
1938      * Reads in and returns array object, or null if array class is
1939      * unresolvable.  Sets passHandle to array's assigned handle.
1940      */
1941     private Object readArray(boolean unshared) throws IOException {
1942         if (bin.readByte() != TC_ARRAY) {
1943             throw new InternalError();
1944         }
1945 
1946         ObjectStreamClass desc = readClassDesc(false);
1947         int len = bin.readInt();
1948 
1949         filterCheck(desc.forClass(), len);
1950 
1951         Object array = null;
1952         Class<?> cl, ccl = null;
1953         if ((cl = desc.forClass()) != null) {
1954             ccl = cl.getComponentType();
1955             array = Array.newInstance(ccl, len);
1956         }
1957 
1958         int arrayHandle = handles.assign(unshared ? unsharedMarker : array);
1959         ClassNotFoundException resolveEx = desc.getResolveException();
1960         if (resolveEx != null) {
1961             handles.markException(arrayHandle, resolveEx);
1962         }
1963 
1964         if (ccl == null) {
1965             for (int i = 0; i < len; i++) {
1966                 readObject0(false);
1967             }
1968         } else if (ccl.isPrimitive()) {
1969             if (ccl == Integer.TYPE) {
1970                 bin.readInts((int[]) array, 0, len);
1971             } else if (ccl == Byte.TYPE) {
1972                 bin.readFully((byte[]) array, 0, len, true);
1973             } else if (ccl == Long.TYPE) {
1974                 bin.readLongs((long[]) array, 0, len);
1975             } else if (ccl == Float.TYPE) {
1976                 bin.readFloats((float[]) array, 0, len);
1977             } else if (ccl == Double.TYPE) {
1978                 bin.readDoubles((double[]) array, 0, len);
1979             } else if (ccl == Short.TYPE) {
1980                 bin.readShorts((short[]) array, 0, len);
1981             } else if (ccl == Character.TYPE) {
1982                 bin.readChars((char[]) array, 0, len);
1983             } else if (ccl == Boolean.TYPE) {
1984                 bin.readBooleans((boolean[]) array, 0, len);
1985             } else {
1986                 throw new InternalError();
1987             }
1988         } else {
1989             Object[] oa = (Object[]) array;
1990             for (int i = 0; i < len; i++) {
1991                 oa[i] = readObject0(false);
1992                 handles.markDependency(arrayHandle, passHandle);
1993             }
1994         }
1995 
1996         handles.finish(arrayHandle);
1997         passHandle = arrayHandle;
1998         return array;
1999     }
2000 
2001     /**
2002      * Reads in and returns enum constant, or null if enum type is
2003      * unresolvable.  Sets passHandle to enum constant's assigned handle.
2004      */
2005     private Enum<?> readEnum(boolean unshared) throws IOException {
2006         if (bin.readByte() != TC_ENUM) {
2007             throw new InternalError();
2008         }
2009 
2010         ObjectStreamClass desc = readClassDesc(false);
2011         if (!desc.isEnum()) {
2012             throw new InvalidClassException("non-enum class: " + desc);
2013         }
2014 
2015         int enumHandle = handles.assign(unshared ? unsharedMarker : null);
2016         ClassNotFoundException resolveEx = desc.getResolveException();
2017         if (resolveEx != null) {
2018             handles.markException(enumHandle, resolveEx);
2019         }
2020 
2021         String name = readString(false);
2022         Enum<?> result = null;
2023         Class<?> cl = desc.forClass();
2024         if (cl != null) {
2025             try {
2026                 @SuppressWarnings("unchecked")
2027                 Enum<?> en = Enum.valueOf((Class)cl, name);
2028                 result = en;
2029             } catch (IllegalArgumentException ex) {
2030                 throw (IOException) new InvalidObjectException(
2031                     "enum constant " + name + " does not exist in " +
2032                     cl).initCause(ex);
2033             }
2034             if (!unshared) {
2035                 handles.setObject(enumHandle, result);
2036             }
2037         }
2038 
2039         handles.finish(enumHandle);
2040         passHandle = enumHandle;
2041         return result;
2042     }
2043 
2044     /**
2045      * Reads and returns "ordinary" (i.e., not a String, Class,
2046      * ObjectStreamClass, array, or enum constant) object, or null if object's
2047      * class is unresolvable (in which case a ClassNotFoundException will be
2048      * associated with object's handle).  Sets passHandle to object's assigned
2049      * handle.
2050      */
2051     private Object readOrdinaryObject(boolean unshared)
2052         throws IOException
2053     {
2054         if (bin.readByte() != TC_OBJECT) {
2055             throw new InternalError();
2056         }
2057 
2058         ObjectStreamClass desc = readClassDesc(false);
2059         desc.checkDeserialize();
2060 
2061         Class<?> cl = desc.forClass();
2062         if (cl == String.class || cl == Class.class
2063                 || cl == ObjectStreamClass.class) {
2064             throw new InvalidClassException("invalid class descriptor");
2065         }
2066 
2067         Object obj;
2068         try {
2069             obj = desc.isInstantiable() ? desc.newInstance() : null;
2070         } catch (Exception ex) {
2071             throw (IOException) new InvalidClassException(
2072                 desc.forClass().getName(),
2073                 "unable to create instance").initCause(ex);
2074         }
2075 
2076         passHandle = handles.assign(unshared ? unsharedMarker : obj);
2077         ClassNotFoundException resolveEx = desc.getResolveException();
2078         if (resolveEx != null) {
2079             handles.markException(passHandle, resolveEx);
2080         }
2081 
2082         if (desc.isExternalizable()) {
2083             readExternalData((Externalizable) obj, desc);
2084         } else {
2085             readSerialData(obj, desc);
2086         }
2087 
2088         handles.finish(passHandle);
2089 
2090         if (obj != null &&
2091             handles.lookupException(passHandle) == null &&
2092             desc.hasReadResolveMethod())
2093         {
2094             Object rep = desc.invokeReadResolve(obj);
2095             if (unshared && rep.getClass().isArray()) {
2096                 rep = cloneArray(rep);
2097             }
2098             if (rep != obj) {
2099                 // Filter the replacement object
2100                 if (rep != null) {
2101                     if (rep.getClass().isArray()) {
2102                         filterCheck(rep.getClass(), Array.getLength(rep));
2103                     } else {
2104                         filterCheck(rep.getClass(), -1);
2105                     }
2106                 }
2107                 handles.setObject(passHandle, obj = rep);
2108             }
2109         }
2110 
2111         return obj;
2112     }
2113 
2114     /**
2115      * If obj is non-null, reads externalizable data by invoking readExternal()
2116      * method of obj; otherwise, attempts to skip over externalizable data.
2117      * Expects that passHandle is set to obj's handle before this method is
2118      * called.
2119      */
2120     private void readExternalData(Externalizable obj, ObjectStreamClass desc)
2121         throws IOException
2122     {
2123         SerialCallbackContext oldContext = curContext;
2124         if (oldContext != null)
2125             oldContext.check();
2126         curContext = null;
2127         try {
2128             boolean blocked = desc.hasBlockExternalData();
2129             if (blocked) {
2130                 bin.setBlockDataMode(true);
2131             }
2132             if (obj != null) {
2133                 try {
2134                     obj.readExternal(this);
2135                 } catch (ClassNotFoundException ex) {
2136                     /*
2137                      * In most cases, the handle table has already propagated
2138                      * a CNFException to passHandle at this point; this mark
2139                      * call is included to address cases where the readExternal
2140                      * method has cons'ed and thrown a new CNFException of its
2141                      * own.
2142                      */
2143                      handles.markException(passHandle, ex);
2144                 }
2145             }
2146             if (blocked) {
2147                 skipCustomData();
2148             }
2149         } finally {
2150             if (oldContext != null)
2151                 oldContext.check();
2152             curContext = oldContext;
2153         }
2154         /*
2155          * At this point, if the externalizable data was not written in
2156          * block-data form and either the externalizable class doesn't exist
2157          * locally (i.e., obj == null) or readExternal() just threw a
2158          * CNFException, then the stream is probably in an inconsistent state,
2159          * since some (or all) of the externalizable data may not have been
2160          * consumed.  Since there's no "correct" action to take in this case,
2161          * we mimic the behavior of past serialization implementations and
2162          * blindly hope that the stream is in sync; if it isn't and additional
2163          * externalizable data remains in the stream, a subsequent read will
2164          * most likely throw a StreamCorruptedException.
2165          */
2166     }
2167 
2168     /**
2169      * Reads (or attempts to skip, if obj is null or is tagged with a
2170      * ClassNotFoundException) instance data for each serializable class of
2171      * object in stream, from superclass to subclass.  Expects that passHandle
2172      * is set to obj's handle before this method is called.
2173      */
2174     private void readSerialData(Object obj, ObjectStreamClass desc)
2175         throws IOException
2176     {
2177         ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
2178         // Best effort Failure Atomicity; slotValues will be non-null if field
2179         // values can be set after reading all field data in the hierarchy.
2180         // Field values can only be set after reading all data if there are no
2181         // user observable methods in the hierarchy, readObject(NoData). The
2182         // top most Serializable class in the hierarchy can be skipped.
2183         FieldValues[] slotValues = null;
2184 
2185         boolean hasSpecialReadMethod = false;
2186         for (int i = 1; i < slots.length; i++) {
2187             ObjectStreamClass slotDesc = slots[i].desc;
2188             if (slotDesc.hasReadObjectMethod()
2189                   || slotDesc.hasReadObjectNoDataMethod()) {
2190                 hasSpecialReadMethod = true;
2191                 break;
2192             }
2193         }
2194         // No special read methods, can store values and defer setting.
2195         if (!hasSpecialReadMethod)
2196             slotValues = new FieldValues[slots.length];
2197 
2198         for (int i = 0; i < slots.length; i++) {
2199             ObjectStreamClass slotDesc = slots[i].desc;
2200 
2201             if (slots[i].hasData) {
2202                 if (obj == null || handles.lookupException(passHandle) != null) {
2203                     defaultReadFields(null, slotDesc); // skip field values
2204                 } else if (slotDesc.hasReadObjectMethod()) {
2205                     ThreadDeath t = null;
2206                     boolean reset = false;
2207                     SerialCallbackContext oldContext = curContext;
2208                     if (oldContext != null)
2209                         oldContext.check();
2210                     try {
2211                         curContext = new SerialCallbackContext(obj, slotDesc);
2212 
2213                         bin.setBlockDataMode(true);
2214                         slotDesc.invokeReadObject(obj, this);
2215                     } catch (ClassNotFoundException ex) {
2216                         /*
2217                          * In most cases, the handle table has already
2218                          * propagated a CNFException to passHandle at this
2219                          * point; this mark call is included to address cases
2220                          * where the custom readObject method has cons'ed and
2221                          * thrown a new CNFException of its own.
2222                          */
2223                         handles.markException(passHandle, ex);
2224                     } finally {
2225                         do {
2226                             try {
2227                                 curContext.setUsed();
2228                                 if (oldContext!= null)
2229                                     oldContext.check();
2230                                 curContext = oldContext;
2231                                 reset = true;
2232                             } catch (ThreadDeath x) {
2233                                 t = x;  // defer until reset is true
2234                             }
2235                         } while (!reset);
2236                         if (t != null)
2237                             throw t;
2238                     }
2239 
2240                     /*
2241                      * defaultDataEnd may have been set indirectly by custom
2242                      * readObject() method when calling defaultReadObject() or
2243                      * readFields(); clear it to restore normal read behavior.
2244                      */
2245                     defaultDataEnd = false;
2246                 } else {
2247                     FieldValues vals = defaultReadFields(obj, slotDesc);
2248                     if (slotValues != null) {
2249                         slotValues[i] = vals;
2250                     } else if (obj != null) {
2251                         defaultCheckFieldValues(obj, slotDesc, vals);
2252                         defaultSetFieldValues(obj, slotDesc, vals);
2253                     }
2254                 }
2255 
2256                 if (slotDesc.hasWriteObjectData()) {
2257                     skipCustomData();
2258                 } else {
2259                     bin.setBlockDataMode(false);
2260                 }
2261             } else {
2262                 if (obj != null &&
2263                     slotDesc.hasReadObjectNoDataMethod() &&
2264                     handles.lookupException(passHandle) == null)
2265                 {
2266                     slotDesc.invokeReadObjectNoData(obj);
2267                 }
2268             }
2269         }
2270 
2271         if (obj != null && slotValues != null) {
2272             // Check that the non-primitive types are assignable for all slots
2273             // before assigning.
2274             for (int i = 0; i < slots.length; i++) {
2275                 if (slotValues[i] != null)
2276                     defaultCheckFieldValues(obj, slots[i].desc, slotValues[i]);
2277             }
2278             for (int i = 0; i < slots.length; i++) {
2279                 if (slotValues[i] != null)
2280                     defaultSetFieldValues(obj, slots[i].desc, slotValues[i]);
2281             }
2282         }
2283     }
2284 
2285     /**
2286      * Skips over all block data and objects until TC_ENDBLOCKDATA is
2287      * encountered.
2288      */
2289     private void skipCustomData() throws IOException {
2290         int oldHandle = passHandle;
2291         for (;;) {
2292             if (bin.getBlockDataMode()) {
2293                 bin.skipBlockData();
2294                 bin.setBlockDataMode(false);
2295             }
2296             switch (bin.peekByte()) {
2297                 case TC_BLOCKDATA:
2298                 case TC_BLOCKDATALONG:
2299                     bin.setBlockDataMode(true);
2300                     break;
2301 
2302                 case TC_ENDBLOCKDATA:
2303                     bin.readByte();
2304                     passHandle = oldHandle;
2305                     return;
2306 
2307                 default:
2308                     readObject0(false);
2309                     break;
2310             }
2311         }
2312     }
2313 
2314     private class FieldValues {
2315         final byte[] primValues;
2316         final Object[] objValues;
2317 
2318         FieldValues(byte[] primValues, Object[] objValues) {
2319             this.primValues = primValues;
2320             this.objValues = objValues;
2321         }
2322     }
2323 
2324     /**
2325      * Reads in values of serializable fields declared by given class
2326      * descriptor. Expects that passHandle is set to obj's handle before this
2327      * method is called.
2328      */
2329     private FieldValues defaultReadFields(Object obj, ObjectStreamClass desc)
2330         throws IOException
2331     {
2332         Class<?> cl = desc.forClass();
2333         if (cl != null && obj != null && !cl.isInstance(obj)) {
2334             throw new ClassCastException();
2335         }
2336 
2337         byte[] primVals = null;
2338         int primDataSize = desc.getPrimDataSize();
2339         if (primDataSize > 0) {
2340             primVals = new byte[primDataSize];
2341             bin.readFully(primVals, 0, primDataSize, false);
2342         }
2343 
2344         Object[] objVals = null;
2345         int numObjFields = desc.getNumObjFields();
2346         if (numObjFields > 0) {
2347             int objHandle = passHandle;
2348             ObjectStreamField[] fields = desc.getFields(false);
2349             objVals = new Object[numObjFields];
2350             int numPrimFields = fields.length - objVals.length;
2351             for (int i = 0; i < objVals.length; i++) {
2352                 ObjectStreamField f = fields[numPrimFields + i];
2353                 objVals[i] = readObject0(f.isUnshared());
2354                 if (f.getField() != null) {
2355                     handles.markDependency(objHandle, passHandle);
2356                 }
2357             }
2358             passHandle = objHandle;
2359         }
2360 
2361         return new FieldValues(primVals, objVals);
2362     }
2363 
2364     /** Throws ClassCastException if any value is not assignable. */
2365     private void defaultCheckFieldValues(Object obj, ObjectStreamClass desc,
2366                                          FieldValues values) {
2367         Object[] objectValues = values.objValues;
2368         if (objectValues != null)
2369             desc.checkObjFieldValueTypes(obj, objectValues);
2370     }
2371 
2372     /** Sets field values in obj. */
2373     private void defaultSetFieldValues(Object obj, ObjectStreamClass desc,
2374                                        FieldValues values) {
2375         byte[] primValues = values.primValues;
2376         Object[] objectValues = values.objValues;
2377 
2378         if (primValues != null)
2379             desc.setPrimFieldValues(obj, primValues);
2380         if (objectValues != null)
2381             desc.setObjFieldValues(obj, objectValues);
2382     }
2383 
2384     /**
2385      * Reads in and returns IOException that caused serialization to abort.
2386      * All stream state is discarded prior to reading in fatal exception.  Sets
2387      * passHandle to fatal exception's handle.
2388      */
2389     private IOException readFatalException() throws IOException {
2390         if (bin.readByte() != TC_EXCEPTION) {
2391             throw new InternalError();
2392         }
2393         clear();
2394         return (IOException) readObject0(false);
2395     }
2396 
2397     /**
2398      * If recursion depth is 0, clears internal data structures; otherwise,
2399      * throws a StreamCorruptedException.  This method is called when a
2400      * TC_RESET typecode is encountered.
2401      */
2402     private void handleReset() throws StreamCorruptedException {
2403         if (depth > 0) {
2404             throw new StreamCorruptedException(
2405                 "unexpected reset; recursion depth: " + depth);
2406         }
2407         clear();
2408     }
2409 
2410     /**
2411      * Converts specified span of bytes into float values.
2412      */
2413     // REMIND: remove once hotspot inlines Float.intBitsToFloat
2414     private static native void bytesToFloats(byte[] src, int srcpos,
2415                                              float[] dst, int dstpos,
2416                                              int nfloats);
2417 
2418     /**
2419      * Converts specified span of bytes into double values.
2420      */
2421     // REMIND: remove once hotspot inlines Double.longBitsToDouble
2422     private static native void bytesToDoubles(byte[] src, int srcpos,
2423                                               double[] dst, int dstpos,
2424                                               int ndoubles);
2425 
2426     /**
2427      * Returns the first non-null and non-platform class loader (not counting
2428      * class loaders of generated reflection implementation classes) up the
2429      * execution stack, or the platform class loader if only code from the
2430      * bootstrap and platform class loader is on the stack.
2431      */
2432     private static ClassLoader latestUserDefinedLoader() {
2433         return jdk.internal.misc.VM.latestUserDefinedLoader();
2434     }
2435 
2436     /**
2437      * Default GetField implementation.
2438      */
2439     private class GetFieldImpl extends GetField {
2440 
2441         /** class descriptor describing serializable fields */
2442         private final ObjectStreamClass desc;
2443         /** primitive field values */
2444         private final byte[] primVals;
2445         /** object field values */
2446         private final Object[] objVals;
2447         /** object field value handles */
2448         private final int[] objHandles;
2449 
2450         /**
2451          * Creates GetFieldImpl object for reading fields defined in given
2452          * class descriptor.
2453          */
2454         GetFieldImpl(ObjectStreamClass desc) {
2455             this.desc = desc;
2456             primVals = new byte[desc.getPrimDataSize()];
2457             objVals = new Object[desc.getNumObjFields()];
2458             objHandles = new int[objVals.length];
2459         }
2460 
2461         public ObjectStreamClass getObjectStreamClass() {
2462             return desc;
2463         }
2464 
2465         public boolean defaulted(String name) throws IOException {
2466             return (getFieldOffset(name, null) < 0);
2467         }
2468 
2469         public boolean get(String name, boolean val) throws IOException {
2470             int off = getFieldOffset(name, Boolean.TYPE);
2471             return (off >= 0) ? Bits.getBoolean(primVals, off) : val;
2472         }
2473 
2474         public byte get(String name, byte val) throws IOException {
2475             int off = getFieldOffset(name, Byte.TYPE);
2476             return (off >= 0) ? primVals[off] : val;
2477         }
2478 
2479         public char get(String name, char val) throws IOException {
2480             int off = getFieldOffset(name, Character.TYPE);
2481             return (off >= 0) ? Bits.getChar(primVals, off) : val;
2482         }
2483 
2484         public short get(String name, short val) throws IOException {
2485             int off = getFieldOffset(name, Short.TYPE);
2486             return (off >= 0) ? Bits.getShort(primVals, off) : val;
2487         }
2488 
2489         public int get(String name, int val) throws IOException {
2490             int off = getFieldOffset(name, Integer.TYPE);
2491             return (off >= 0) ? Bits.getInt(primVals, off) : val;
2492         }
2493 
2494         public float get(String name, float val) throws IOException {
2495             int off = getFieldOffset(name, Float.TYPE);
2496             return (off >= 0) ? Bits.getFloat(primVals, off) : val;
2497         }
2498 
2499         public long get(String name, long val) throws IOException {
2500             int off = getFieldOffset(name, Long.TYPE);
2501             return (off >= 0) ? Bits.getLong(primVals, off) : val;
2502         }
2503 
2504         public double get(String name, double val) throws IOException {
2505             int off = getFieldOffset(name, Double.TYPE);
2506             return (off >= 0) ? Bits.getDouble(primVals, off) : val;
2507         }
2508 
2509         public Object get(String name, Object val) throws IOException {
2510             int off = getFieldOffset(name, Object.class);
2511             if (off >= 0) {
2512                 int objHandle = objHandles[off];
2513                 handles.markDependency(passHandle, objHandle);
2514                 return (handles.lookupException(objHandle) == null) ?
2515                     objVals[off] : null;
2516             } else {
2517                 return val;
2518             }
2519         }
2520 
2521         /**
2522          * Reads primitive and object field values from stream.
2523          */
2524         void readFields() throws IOException {
2525             bin.readFully(primVals, 0, primVals.length, false);
2526 
2527             int oldHandle = passHandle;
2528             ObjectStreamField[] fields = desc.getFields(false);
2529             int numPrimFields = fields.length - objVals.length;
2530             for (int i = 0; i < objVals.length; i++) {
2531                 objVals[i] =
2532                     readObject0(fields[numPrimFields + i].isUnshared());
2533                 objHandles[i] = passHandle;
2534             }
2535             passHandle = oldHandle;
2536         }
2537 
2538         /**
2539          * Returns offset of field with given name and type.  A specified type
2540          * of null matches all types, Object.class matches all non-primitive
2541          * types, and any other non-null type matches assignable types only.
2542          * If no matching field is found in the (incoming) class
2543          * descriptor but a matching field is present in the associated local
2544          * class descriptor, returns -1.  Throws IllegalArgumentException if
2545          * neither incoming nor local class descriptor contains a match.
2546          */
2547         private int getFieldOffset(String name, Class<?> type) {
2548             ObjectStreamField field = desc.getField(name, type);
2549             if (field != null) {
2550                 return field.getOffset();
2551             } else if (desc.getLocalDesc().getField(name, type) != null) {
2552                 return -1;
2553             } else {
2554                 throw new IllegalArgumentException("no such field " + name +
2555                                                    " with type " + type);
2556             }
2557         }
2558     }
2559 
2560     /**
2561      * Prioritized list of callbacks to be performed once object graph has been
2562      * completely deserialized.
2563      */
2564     private static class ValidationList {
2565 
2566         private static class Callback {
2567             final ObjectInputValidation obj;
2568             final int priority;
2569             Callback next;
2570             final AccessControlContext acc;
2571 
2572             Callback(ObjectInputValidation obj, int priority, Callback next,
2573                 AccessControlContext acc)
2574             {
2575                 this.obj = obj;
2576                 this.priority = priority;
2577                 this.next = next;
2578                 this.acc = acc;
2579             }
2580         }
2581 
2582         /** linked list of callbacks */
2583         private Callback list;
2584 
2585         /**
2586          * Creates new (empty) ValidationList.
2587          */
2588         ValidationList() {
2589         }
2590 
2591         /**
2592          * Registers callback.  Throws InvalidObjectException if callback
2593          * object is null.
2594          */
2595         void register(ObjectInputValidation obj, int priority)
2596             throws InvalidObjectException
2597         {
2598             if (obj == null) {
2599                 throw new InvalidObjectException("null callback");
2600             }
2601 
2602             Callback prev = null, cur = list;
2603             while (cur != null && priority < cur.priority) {
2604                 prev = cur;
2605                 cur = cur.next;
2606             }
2607             AccessControlContext acc = AccessController.getContext();
2608             if (prev != null) {
2609                 prev.next = new Callback(obj, priority, cur, acc);
2610             } else {
2611                 list = new Callback(obj, priority, list, acc);
2612             }
2613         }
2614 
2615         /**
2616          * Invokes all registered callbacks and clears the callback list.
2617          * Callbacks with higher priorities are called first; those with equal
2618          * priorities may be called in any order.  If any of the callbacks
2619          * throws an InvalidObjectException, the callback process is terminated
2620          * and the exception propagated upwards.
2621          */
2622         void doCallbacks() throws InvalidObjectException {
2623             try {
2624                 while (list != null) {
2625                     AccessController.doPrivileged(
2626                         new PrivilegedExceptionAction<Void>()
2627                     {
2628                         public Void run() throws InvalidObjectException {
2629                             list.obj.validateObject();
2630                             return null;
2631                         }
2632                     }, list.acc);
2633                     list = list.next;
2634                 }
2635             } catch (PrivilegedActionException ex) {
2636                 list = null;
2637                 throw (InvalidObjectException) ex.getException();
2638             }
2639         }
2640 
2641         /**
2642          * Resets the callback list to its initial (empty) state.
2643          */
2644         public void clear() {
2645             list = null;
2646         }
2647     }
2648 
2649     /**
2650      * Hold a snapshot of values to be passed to an ObjectInputFilter.
2651      */
2652     static class FilterValues implements ObjectInputFilter.FilterInfo {
2653         final Class<?> clazz;
2654         final long arrayLength;
2655         final long totalObjectRefs;
2656         final long depth;
2657         final long streamBytes;
2658 
2659         public FilterValues(Class<?> clazz, long arrayLength, long totalObjectRefs,
2660                             long depth, long streamBytes) {
2661             this.clazz = clazz;
2662             this.arrayLength = arrayLength;
2663             this.totalObjectRefs = totalObjectRefs;
2664             this.depth = depth;
2665             this.streamBytes = streamBytes;
2666         }
2667 
2668         @Override
2669         public Class<?> serialClass() {
2670             return clazz;
2671         }
2672 
2673         @Override
2674         public long arrayLength() {
2675             return arrayLength;
2676         }
2677 
2678         @Override
2679         public long references() {
2680             return totalObjectRefs;
2681         }
2682 
2683         @Override
2684         public long depth() {
2685             return depth;
2686         }
2687 
2688         @Override
2689         public long streamBytes() {
2690             return streamBytes;
2691         }
2692     }
2693 
2694     /**
2695      * Input stream supporting single-byte peek operations.
2696      */
2697     private static class PeekInputStream extends InputStream {
2698 
2699         /** underlying stream */
2700         private final InputStream in;
2701         /** peeked byte */
2702         private int peekb = -1;
2703         /** total bytes read from the stream */
2704         private long totalBytesRead = 0;
2705 
2706         /**
2707          * Creates new PeekInputStream on top of given underlying stream.
2708          */
2709         PeekInputStream(InputStream in) {
2710             this.in = in;
2711         }
2712 
2713         /**
2714          * Peeks at next byte value in stream.  Similar to read(), except
2715          * that it does not consume the read value.
2716          */
2717         int peek() throws IOException {
2718             if (peekb >= 0) {
2719                 return peekb;
2720             }
2721             peekb = in.read();
2722             totalBytesRead += peekb >= 0 ? 1 : 0;
2723             return peekb;
2724         }
2725 
2726         public int read() throws IOException {
2727             if (peekb >= 0) {
2728                 int v = peekb;
2729                 peekb = -1;
2730                 return v;
2731             } else {
2732                 int nbytes = in.read();
2733                 totalBytesRead += nbytes >= 0 ? 1 : 0;
2734                 return nbytes;
2735             }
2736         }
2737 
2738         public int read(byte[] b, int off, int len) throws IOException {
2739             int nbytes;
2740             if (len == 0) {
2741                 return 0;
2742             } else if (peekb < 0) {
2743                 nbytes = in.read(b, off, len);
2744                 totalBytesRead += nbytes >= 0 ? nbytes : 0;
2745                 return nbytes;
2746             } else {
2747                 b[off++] = (byte) peekb;
2748                 len--;
2749                 peekb = -1;
2750                 nbytes = in.read(b, off, len);
2751                 totalBytesRead += nbytes >= 0 ? nbytes : 0;
2752                 return (nbytes >= 0) ? (nbytes + 1) : 1;
2753             }
2754         }
2755 
2756         void readFully(byte[] b, int off, int len) throws IOException {
2757             int n = 0;
2758             while (n < len) {
2759                 int count = read(b, off + n, len - n);
2760                 if (count < 0) {
2761                     throw new EOFException();
2762                 }
2763                 n += count;
2764             }
2765         }
2766 
2767         public long skip(long n) throws IOException {
2768             if (n <= 0) {
2769                 return 0;
2770             }
2771             int skipped = 0;
2772             if (peekb >= 0) {
2773                 peekb = -1;
2774                 skipped++;
2775                 n--;
2776             }
2777             n = skipped + in.skip(n);
2778             totalBytesRead += n;
2779             return n;
2780         }
2781 
2782         public int available() throws IOException {
2783             return in.available() + ((peekb >= 0) ? 1 : 0);
2784         }
2785 
2786         public void close() throws IOException {
2787             in.close();
2788         }
2789 
2790         public long getBytesRead() {
2791             return totalBytesRead;
2792         }
2793     }
2794 
2795     private static final Unsafe UNSAFE = Unsafe.getUnsafe();
2796 
2797     /**
2798      * Performs a "freeze" action, required to adhere to final field semantics.
2799      *
2800      * <p> This method can be called unconditionally before returning the graph,
2801      * from the topmost readObject call, since it is expected that the
2802      * additional cost of the freeze action is negligible compared to
2803      * reconstituting even the most simple graph.
2804      *
2805      * <p> Nested calls to readObject do not issue freeze actions because the
2806      * sub-graph returned from a nested call is not guaranteed to be fully
2807      * initialized yet (possible cycles).
2808      */
2809     private void freeze() {
2810         // Issue a StoreStore|StoreLoad fence, which is at least sufficient
2811         // to provide final-freeze semantics.
2812         UNSAFE.storeFence();
2813     }
2814 
2815     /**
2816      * Input stream with two modes: in default mode, inputs data written in the
2817      * same format as DataOutputStream; in "block data" mode, inputs data
2818      * bracketed by block data markers (see object serialization specification
2819      * for details).  Buffering depends on block data mode: when in default
2820      * mode, no data is buffered in advance; when in block data mode, all data
2821      * for the current data block is read in at once (and buffered).
2822      */
2823     private class BlockDataInputStream
2824         extends InputStream implements DataInput
2825     {
2826         /** maximum data block length */
2827         private static final int MAX_BLOCK_SIZE = 1024;
2828         /** maximum data block header length */
2829         private static final int MAX_HEADER_SIZE = 5;
2830         /** (tunable) length of char buffer (for reading strings) */
2831         private static final int CHAR_BUF_SIZE = 256;
2832         /** readBlockHeader() return value indicating header read may block */
2833         private static final int HEADER_BLOCKED = -2;
2834 
2835         /** buffer for reading general/block data */
2836         private final byte[] buf = new byte[MAX_BLOCK_SIZE];
2837         /** buffer for reading block data headers */
2838         private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
2839         /** char buffer for fast string reads */
2840         private final char[] cbuf = new char[CHAR_BUF_SIZE];
2841 
2842         /** block data mode */
2843         private boolean blkmode = false;
2844 
2845         // block data state fields; values meaningful only when blkmode true
2846         /** current offset into buf */
2847         private int pos = 0;
2848         /** end offset of valid data in buf, or -1 if no more block data */
2849         private int end = -1;
2850         /** number of bytes in current block yet to be read from stream */
2851         private int unread = 0;
2852 
2853         /** underlying stream (wrapped in peekable filter stream) */
2854         private final PeekInputStream in;
2855         /** loopback stream (for data reads that span data blocks) */
2856         private final DataInputStream din;
2857 
2858         /**
2859          * Creates new BlockDataInputStream on top of given underlying stream.
2860          * Block data mode is turned off by default.
2861          */
2862         BlockDataInputStream(InputStream in) {
2863             this.in = new PeekInputStream(in);
2864             din = new DataInputStream(this);
2865         }
2866 
2867         /**
2868          * Sets block data mode to the given mode (true == on, false == off)
2869          * and returns the previous mode value.  If the new mode is the same as
2870          * the old mode, no action is taken.  Throws IllegalStateException if
2871          * block data mode is being switched from on to off while unconsumed
2872          * block data is still present in the stream.
2873          */
2874         boolean setBlockDataMode(boolean newmode) throws IOException {
2875             if (blkmode == newmode) {
2876                 return blkmode;
2877             }
2878             if (newmode) {
2879                 pos = 0;
2880                 end = 0;
2881                 unread = 0;
2882             } else if (pos < end) {
2883                 throw new IllegalStateException("unread block data");
2884             }
2885             blkmode = newmode;
2886             return !blkmode;
2887         }
2888 
2889         /**
2890          * Returns true if the stream is currently in block data mode, false
2891          * otherwise.
2892          */
2893         boolean getBlockDataMode() {
2894             return blkmode;
2895         }
2896 
2897         /**
2898          * If in block data mode, skips to the end of the current group of data
2899          * blocks (but does not unset block data mode).  If not in block data
2900          * mode, throws an IllegalStateException.
2901          */
2902         void skipBlockData() throws IOException {
2903             if (!blkmode) {
2904                 throw new IllegalStateException("not in block data mode");
2905             }
2906             while (end >= 0) {
2907                 refill();
2908             }
2909         }
2910 
2911         /**
2912          * Attempts to read in the next block data header (if any).  If
2913          * canBlock is false and a full header cannot be read without possibly
2914          * blocking, returns HEADER_BLOCKED, else if the next element in the
2915          * stream is a block data header, returns the block data length
2916          * specified by the header, else returns -1.
2917          */
2918         private int readBlockHeader(boolean canBlock) throws IOException {
2919             if (defaultDataEnd) {
2920                 /*
2921                  * Fix for 4360508: stream is currently at the end of a field
2922                  * value block written via default serialization; since there
2923                  * is no terminating TC_ENDBLOCKDATA tag, simulate
2924                  * end-of-custom-data behavior explicitly.
2925                  */
2926                 return -1;
2927             }
2928             try {
2929                 for (;;) {
2930                     int avail = canBlock ? Integer.MAX_VALUE : in.available();
2931                     if (avail == 0) {
2932                         return HEADER_BLOCKED;
2933                     }
2934 
2935                     int tc = in.peek();
2936                     switch (tc) {
2937                         case TC_BLOCKDATA:
2938                             if (avail < 2) {
2939                                 return HEADER_BLOCKED;
2940                             }
2941                             in.readFully(hbuf, 0, 2);
2942                             return hbuf[1] & 0xFF;
2943 
2944                         case TC_BLOCKDATALONG:
2945                             if (avail < 5) {
2946                                 return HEADER_BLOCKED;
2947                             }
2948                             in.readFully(hbuf, 0, 5);
2949                             int len = Bits.getInt(hbuf, 1);
2950                             if (len < 0) {
2951                                 throw new StreamCorruptedException(
2952                                     "illegal block data header length: " +
2953                                     len);
2954                             }
2955                             return len;
2956 
2957                         /*
2958                          * TC_RESETs may occur in between data blocks.
2959                          * Unfortunately, this case must be parsed at a lower
2960                          * level than other typecodes, since primitive data
2961                          * reads may span data blocks separated by a TC_RESET.
2962                          */
2963                         case TC_RESET:
2964                             in.read();
2965                             handleReset();
2966                             break;
2967 
2968                         default:
2969                             if (tc >= 0 && (tc < TC_BASE || tc > TC_MAX)) {
2970                                 throw new StreamCorruptedException(
2971                                     String.format("invalid type code: %02X",
2972                                     tc));
2973                             }
2974                             return -1;
2975                     }
2976                 }
2977             } catch (EOFException ex) {
2978                 throw new StreamCorruptedException(
2979                     "unexpected EOF while reading block data header");
2980             }
2981         }
2982 
2983         /**
2984          * Refills internal buffer buf with block data.  Any data in buf at the
2985          * time of the call is considered consumed.  Sets the pos, end, and
2986          * unread fields to reflect the new amount of available block data; if
2987          * the next element in the stream is not a data block, sets pos and
2988          * unread to 0 and end to -1.
2989          */
2990         private void refill() throws IOException {
2991             try {
2992                 do {
2993                     pos = 0;
2994                     if (unread > 0) {
2995                         int n =
2996                             in.read(buf, 0, Math.min(unread, MAX_BLOCK_SIZE));
2997                         if (n >= 0) {
2998                             end = n;
2999                             unread -= n;
3000                         } else {
3001                             throw new StreamCorruptedException(
3002                                 "unexpected EOF in middle of data block");
3003                         }
3004                     } else {
3005                         int n = readBlockHeader(true);
3006                         if (n >= 0) {
3007                             end = 0;
3008                             unread = n;
3009                         } else {
3010                             end = -1;
3011                             unread = 0;
3012                         }
3013                     }
3014                 } while (pos == end);
3015             } catch (IOException ex) {
3016                 pos = 0;
3017                 end = -1;
3018                 unread = 0;
3019                 throw ex;
3020             }
3021         }
3022 
3023         /**
3024          * If in block data mode, returns the number of unconsumed bytes
3025          * remaining in the current data block.  If not in block data mode,
3026          * throws an IllegalStateException.
3027          */
3028         int currentBlockRemaining() {
3029             if (blkmode) {
3030                 return (end >= 0) ? (end - pos) + unread : 0;
3031             } else {
3032                 throw new IllegalStateException();
3033             }
3034         }
3035 
3036         /**
3037          * Peeks at (but does not consume) and returns the next byte value in
3038          * the stream, or -1 if the end of the stream/block data (if in block
3039          * data mode) has been reached.
3040          */
3041         int peek() throws IOException {
3042             if (blkmode) {
3043                 if (pos == end) {
3044                     refill();
3045                 }
3046                 return (end >= 0) ? (buf[pos] & 0xFF) : -1;
3047             } else {
3048                 return in.peek();
3049             }
3050         }
3051 
3052         /**
3053          * Peeks at (but does not consume) and returns the next byte value in
3054          * the stream, or throws EOFException if end of stream/block data has
3055          * been reached.
3056          */
3057         byte peekByte() throws IOException {
3058             int val = peek();
3059             if (val < 0) {
3060                 throw new EOFException();
3061             }
3062             return (byte) val;
3063         }
3064 
3065 
3066         /* ----------------- generic input stream methods ------------------ */
3067         /*
3068          * The following methods are equivalent to their counterparts in
3069          * InputStream, except that they interpret data block boundaries and
3070          * read the requested data from within data blocks when in block data
3071          * mode.
3072          */
3073 
3074         public int read() throws IOException {
3075             if (blkmode) {
3076                 if (pos == end) {
3077                     refill();
3078                 }
3079                 return (end >= 0) ? (buf[pos++] & 0xFF) : -1;
3080             } else {
3081                 return in.read();
3082             }
3083         }
3084 
3085         public int read(byte[] b, int off, int len) throws IOException {
3086             return read(b, off, len, false);
3087         }
3088 
3089         public long skip(long len) throws IOException {
3090             long remain = len;
3091             while (remain > 0) {
3092                 if (blkmode) {
3093                     if (pos == end) {
3094                         refill();
3095                     }
3096                     if (end < 0) {
3097                         break;
3098                     }
3099                     int nread = (int) Math.min(remain, end - pos);
3100                     remain -= nread;
3101                     pos += nread;
3102                 } else {
3103                     int nread = (int) Math.min(remain, MAX_BLOCK_SIZE);
3104                     if ((nread = in.read(buf, 0, nread)) < 0) {
3105                         break;
3106                     }
3107                     remain -= nread;
3108                 }
3109             }
3110             return len - remain;
3111         }
3112 
3113         public int available() throws IOException {
3114             if (blkmode) {
3115                 if ((pos == end) && (unread == 0)) {
3116                     int n;
3117                     while ((n = readBlockHeader(false)) == 0) ;
3118                     switch (n) {
3119                         case HEADER_BLOCKED:
3120                             break;
3121 
3122                         case -1:
3123                             pos = 0;
3124                             end = -1;
3125                             break;
3126 
3127                         default:
3128                             pos = 0;
3129                             end = 0;
3130                             unread = n;
3131                             break;
3132                     }
3133                 }
3134                 // avoid unnecessary call to in.available() if possible
3135                 int unreadAvail = (unread > 0) ?
3136                     Math.min(in.available(), unread) : 0;
3137                 return (end >= 0) ? (end - pos) + unreadAvail : 0;
3138             } else {
3139                 return in.available();
3140             }
3141         }
3142 
3143         public void close() throws IOException {
3144             if (blkmode) {
3145                 pos = 0;
3146                 end = -1;
3147                 unread = 0;
3148             }
3149             in.close();
3150         }
3151 
3152         /**
3153          * Attempts to read len bytes into byte array b at offset off.  Returns
3154          * the number of bytes read, or -1 if the end of stream/block data has
3155          * been reached.  If copy is true, reads values into an intermediate
3156          * buffer before copying them to b (to avoid exposing a reference to
3157          * b).
3158          */
3159         int read(byte[] b, int off, int len, boolean copy) throws IOException {
3160             if (len == 0) {
3161                 return 0;
3162             } else if (blkmode) {
3163                 if (pos == end) {
3164                     refill();
3165                 }
3166                 if (end < 0) {
3167                     return -1;
3168                 }
3169                 int nread = Math.min(len, end - pos);
3170                 System.arraycopy(buf, pos, b, off, nread);
3171                 pos += nread;
3172                 return nread;
3173             } else if (copy) {
3174                 int nread = in.read(buf, 0, Math.min(len, MAX_BLOCK_SIZE));
3175                 if (nread > 0) {
3176                     System.arraycopy(buf, 0, b, off, nread);
3177                 }
3178                 return nread;
3179             } else {
3180                 return in.read(b, off, len);
3181             }
3182         }
3183 
3184         /* ----------------- primitive data input methods ------------------ */
3185         /*
3186          * The following methods are equivalent to their counterparts in
3187          * DataInputStream, except that they interpret data block boundaries
3188          * and read the requested data from within data blocks when in block
3189          * data mode.
3190          */
3191 
3192         public void readFully(byte[] b) throws IOException {
3193             readFully(b, 0, b.length, false);
3194         }
3195 
3196         public void readFully(byte[] b, int off, int len) throws IOException {
3197             readFully(b, off, len, false);
3198         }
3199 
3200         public void readFully(byte[] b, int off, int len, boolean copy)
3201             throws IOException
3202         {
3203             while (len > 0) {
3204                 int n = read(b, off, len, copy);
3205                 if (n < 0) {
3206                     throw new EOFException();
3207                 }
3208                 off += n;
3209                 len -= n;
3210             }
3211         }
3212 
3213         public int skipBytes(int n) throws IOException {
3214             return din.skipBytes(n);
3215         }
3216 
3217         public boolean readBoolean() throws IOException {
3218             int v = read();
3219             if (v < 0) {
3220                 throw new EOFException();
3221             }
3222             return (v != 0);
3223         }
3224 
3225         public byte readByte() throws IOException {
3226             int v = read();
3227             if (v < 0) {
3228                 throw new EOFException();
3229             }
3230             return (byte) v;
3231         }
3232 
3233         public int readUnsignedByte() throws IOException {
3234             int v = read();
3235             if (v < 0) {
3236                 throw new EOFException();
3237             }
3238             return v;
3239         }
3240 
3241         public char readChar() throws IOException {
3242             if (!blkmode) {
3243                 pos = 0;
3244                 in.readFully(buf, 0, 2);
3245             } else if (end - pos < 2) {
3246                 return din.readChar();
3247             }
3248             char v = Bits.getChar(buf, pos);
3249             pos += 2;
3250             return v;
3251         }
3252 
3253         public short readShort() throws IOException {
3254             if (!blkmode) {
3255                 pos = 0;
3256                 in.readFully(buf, 0, 2);
3257             } else if (end - pos < 2) {
3258                 return din.readShort();
3259             }
3260             short v = Bits.getShort(buf, pos);
3261             pos += 2;
3262             return v;
3263         }
3264 
3265         public int readUnsignedShort() throws IOException {
3266             if (!blkmode) {
3267                 pos = 0;
3268                 in.readFully(buf, 0, 2);
3269             } else if (end - pos < 2) {
3270                 return din.readUnsignedShort();
3271             }
3272             int v = Bits.getShort(buf, pos) & 0xFFFF;
3273             pos += 2;
3274             return v;
3275         }
3276 
3277         public int readInt() throws IOException {
3278             if (!blkmode) {
3279                 pos = 0;
3280                 in.readFully(buf, 0, 4);
3281             } else if (end - pos < 4) {
3282                 return din.readInt();
3283             }
3284             int v = Bits.getInt(buf, pos);
3285             pos += 4;
3286             return v;
3287         }
3288 
3289         public float readFloat() throws IOException {
3290             if (!blkmode) {
3291                 pos = 0;
3292                 in.readFully(buf, 0, 4);
3293             } else if (end - pos < 4) {
3294                 return din.readFloat();
3295             }
3296             float v = Bits.getFloat(buf, pos);
3297             pos += 4;
3298             return v;
3299         }
3300 
3301         public long readLong() throws IOException {
3302             if (!blkmode) {
3303                 pos = 0;
3304                 in.readFully(buf, 0, 8);
3305             } else if (end - pos < 8) {
3306                 return din.readLong();
3307             }
3308             long v = Bits.getLong(buf, pos);
3309             pos += 8;
3310             return v;
3311         }
3312 
3313         public double readDouble() throws IOException {
3314             if (!blkmode) {
3315                 pos = 0;
3316                 in.readFully(buf, 0, 8);
3317             } else if (end - pos < 8) {
3318                 return din.readDouble();
3319             }
3320             double v = Bits.getDouble(buf, pos);
3321             pos += 8;
3322             return v;
3323         }
3324 
3325         public String readUTF() throws IOException {
3326             return readUTFBody(readUnsignedShort());
3327         }
3328 
3329         @SuppressWarnings("deprecation")
3330         public String readLine() throws IOException {
3331             return din.readLine();      // deprecated, not worth optimizing
3332         }
3333 
3334         /* -------------- primitive data array input methods --------------- */
3335         /*
3336          * The following methods read in spans of primitive data values.
3337          * Though equivalent to calling the corresponding primitive read
3338          * methods repeatedly, these methods are optimized for reading groups
3339          * of primitive data values more efficiently.
3340          */
3341 
3342         void readBooleans(boolean[] v, int off, int len) throws IOException {
3343             int stop, endoff = off + len;
3344             while (off < endoff) {
3345                 if (!blkmode) {
3346                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE);
3347                     in.readFully(buf, 0, span);
3348                     stop = off + span;
3349                     pos = 0;
3350                 } else if (end - pos < 1) {
3351                     v[off++] = din.readBoolean();
3352                     continue;
3353                 } else {
3354                     stop = Math.min(endoff, off + end - pos);
3355                 }
3356 
3357                 while (off < stop) {
3358                     v[off++] = Bits.getBoolean(buf, pos++);
3359                 }
3360             }
3361         }
3362 
3363         void readChars(char[] v, int off, int len) throws IOException {
3364             int stop, endoff = off + len;
3365             while (off < endoff) {
3366                 if (!blkmode) {
3367                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1);
3368                     in.readFully(buf, 0, span << 1);
3369                     stop = off + span;
3370                     pos = 0;
3371                 } else if (end - pos < 2) {
3372                     v[off++] = din.readChar();
3373                     continue;
3374                 } else {
3375                     stop = Math.min(endoff, off + ((end - pos) >> 1));
3376                 }
3377 
3378                 while (off < stop) {
3379                     v[off++] = Bits.getChar(buf, pos);
3380                     pos += 2;
3381                 }
3382             }
3383         }
3384 
3385         void readShorts(short[] v, int off, int len) throws IOException {
3386             int stop, endoff = off + len;
3387             while (off < endoff) {
3388                 if (!blkmode) {
3389                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1);
3390                     in.readFully(buf, 0, span << 1);
3391                     stop = off + span;
3392                     pos = 0;
3393                 } else if (end - pos < 2) {
3394                     v[off++] = din.readShort();
3395                     continue;
3396                 } else {
3397                     stop = Math.min(endoff, off + ((end - pos) >> 1));
3398                 }
3399 
3400                 while (off < stop) {
3401                     v[off++] = Bits.getShort(buf, pos);
3402                     pos += 2;
3403                 }
3404             }
3405         }
3406 
3407         void readInts(int[] v, int off, int len) throws IOException {
3408             int stop, endoff = off + len;
3409             while (off < endoff) {
3410                 if (!blkmode) {
3411                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
3412                     in.readFully(buf, 0, span << 2);
3413                     stop = off + span;
3414                     pos = 0;
3415                 } else if (end - pos < 4) {
3416                     v[off++] = din.readInt();
3417                     continue;
3418                 } else {
3419                     stop = Math.min(endoff, off + ((end - pos) >> 2));
3420                 }
3421 
3422                 while (off < stop) {
3423                     v[off++] = Bits.getInt(buf, pos);
3424                     pos += 4;
3425                 }
3426             }
3427         }
3428 
3429         void readFloats(float[] v, int off, int len) throws IOException {
3430             int span, endoff = off + len;
3431             while (off < endoff) {
3432                 if (!blkmode) {
3433                     span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
3434                     in.readFully(buf, 0, span << 2);
3435                     pos = 0;
3436                 } else if (end - pos < 4) {
3437                     v[off++] = din.readFloat();
3438                     continue;
3439                 } else {
3440                     span = Math.min(endoff - off, ((end - pos) >> 2));
3441                 }
3442 
3443                 bytesToFloats(buf, pos, v, off, span);
3444                 off += span;
3445                 pos += span << 2;
3446             }
3447         }
3448 
3449         void readLongs(long[] v, int off, int len) throws IOException {
3450             int stop, endoff = off + len;
3451             while (off < endoff) {
3452                 if (!blkmode) {
3453                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
3454                     in.readFully(buf, 0, span << 3);
3455                     stop = off + span;
3456                     pos = 0;
3457                 } else if (end - pos < 8) {
3458                     v[off++] = din.readLong();
3459                     continue;
3460                 } else {
3461                     stop = Math.min(endoff, off + ((end - pos) >> 3));
3462                 }
3463 
3464                 while (off < stop) {
3465                     v[off++] = Bits.getLong(buf, pos);
3466                     pos += 8;
3467                 }
3468             }
3469         }
3470 
3471         void readDoubles(double[] v, int off, int len) throws IOException {
3472             int span, endoff = off + len;
3473             while (off < endoff) {
3474                 if (!blkmode) {
3475                     span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
3476                     in.readFully(buf, 0, span << 3);
3477                     pos = 0;
3478                 } else if (end - pos < 8) {
3479                     v[off++] = din.readDouble();
3480                     continue;
3481                 } else {
3482                     span = Math.min(endoff - off, ((end - pos) >> 3));
3483                 }
3484 
3485                 bytesToDoubles(buf, pos, v, off, span);
3486                 off += span;
3487                 pos += span << 3;
3488             }
3489         }
3490 
3491         /**
3492          * Reads in string written in "long" UTF format.  "Long" UTF format is
3493          * identical to standard UTF, except that it uses an 8 byte header
3494          * (instead of the standard 2 bytes) to convey the UTF encoding length.
3495          */
3496         String readLongUTF() throws IOException {
3497             return readUTFBody(readLong());
3498         }
3499 
3500         /**
3501          * Reads in the "body" (i.e., the UTF representation minus the 2-byte
3502          * or 8-byte length header) of a UTF encoding, which occupies the next
3503          * utflen bytes.
3504          */
3505         private String readUTFBody(long utflen) throws IOException {
3506             StringBuilder sbuf;
3507             if (utflen > 0 && utflen < Integer.MAX_VALUE) {
3508                 // a reasonable initial capacity based on the UTF length
3509                 int initialCapacity = Math.min((int)utflen, 0xFFFF);
3510                 sbuf = new StringBuilder(initialCapacity);
3511             } else {
3512                 sbuf = new StringBuilder();
3513             }
3514 
3515             if (!blkmode) {
3516                 end = pos = 0;
3517             }
3518 
3519             while (utflen > 0) {
3520                 int avail = end - pos;
3521                 if (avail >= 3 || (long) avail == utflen) {
3522                     utflen -= readUTFSpan(sbuf, utflen);
3523                 } else {
3524                     if (blkmode) {
3525                         // near block boundary, read one byte at a time
3526                         utflen -= readUTFChar(sbuf, utflen);
3527                     } else {
3528                         // shift and refill buffer manually
3529                         if (avail > 0) {
3530                             System.arraycopy(buf, pos, buf, 0, avail);
3531                         }
3532                         pos = 0;
3533                         end = (int) Math.min(MAX_BLOCK_SIZE, utflen);
3534                         in.readFully(buf, avail, end - avail);
3535                     }
3536                 }
3537             }
3538 
3539             return sbuf.toString();
3540         }
3541 
3542         /**
3543          * Reads span of UTF-encoded characters out of internal buffer
3544          * (starting at offset pos and ending at or before offset end),
3545          * consuming no more than utflen bytes.  Appends read characters to
3546          * sbuf.  Returns the number of bytes consumed.
3547          */
3548         private long readUTFSpan(StringBuilder sbuf, long utflen)
3549             throws IOException
3550         {
3551             int cpos = 0;
3552             int start = pos;
3553             int avail = Math.min(end - pos, CHAR_BUF_SIZE);
3554             // stop short of last char unless all of utf bytes in buffer
3555             int stop = pos + ((utflen > avail) ? avail - 2 : (int) utflen);
3556             boolean outOfBounds = false;
3557 
3558             try {
3559                 while (pos < stop) {
3560                     int b1, b2, b3;
3561                     b1 = buf[pos++] & 0xFF;
3562                     switch (b1 >> 4) {
3563                         case 0:
3564                         case 1:
3565                         case 2:
3566                         case 3:
3567                         case 4:
3568                         case 5:
3569                         case 6:
3570                         case 7:   // 1 byte format: 0xxxxxxx
3571                             cbuf[cpos++] = (char) b1;
3572                             break;
3573 
3574                         case 12:
3575                         case 13:  // 2 byte format: 110xxxxx 10xxxxxx
3576                             b2 = buf[pos++];
3577                             if ((b2 & 0xC0) != 0x80) {
3578                                 throw new UTFDataFormatException();
3579                             }
3580                             cbuf[cpos++] = (char) (((b1 & 0x1F) << 6) |
3581                                                    ((b2 & 0x3F) << 0));
3582                             break;
3583 
3584                         case 14:  // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
3585                             b3 = buf[pos + 1];
3586                             b2 = buf[pos + 0];
3587                             pos += 2;
3588                             if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
3589                                 throw new UTFDataFormatException();
3590                             }
3591                             cbuf[cpos++] = (char) (((b1 & 0x0F) << 12) |
3592                                                    ((b2 & 0x3F) << 6) |
3593                                                    ((b3 & 0x3F) << 0));
3594                             break;
3595 
3596                         default:  // 10xx xxxx, 1111 xxxx
3597                             throw new UTFDataFormatException();
3598                     }
3599                 }
3600             } catch (ArrayIndexOutOfBoundsException ex) {
3601                 outOfBounds = true;
3602             } finally {
3603                 if (outOfBounds || (pos - start) > utflen) {
3604                     /*
3605                      * Fix for 4450867: if a malformed utf char causes the
3606                      * conversion loop to scan past the expected end of the utf
3607                      * string, only consume the expected number of utf bytes.
3608                      */
3609                     pos = start + (int) utflen;
3610                     throw new UTFDataFormatException();
3611                 }
3612             }
3613 
3614             sbuf.append(cbuf, 0, cpos);
3615             return pos - start;
3616         }
3617 
3618         /**
3619          * Reads in single UTF-encoded character one byte at a time, appends
3620          * the character to sbuf, and returns the number of bytes consumed.
3621          * This method is used when reading in UTF strings written in block
3622          * data mode to handle UTF-encoded characters which (potentially)
3623          * straddle block-data boundaries.
3624          */
3625         private int readUTFChar(StringBuilder sbuf, long utflen)
3626             throws IOException
3627         {
3628             int b1, b2, b3;
3629             b1 = readByte() & 0xFF;
3630             switch (b1 >> 4) {
3631                 case 0:
3632                 case 1:
3633                 case 2:
3634                 case 3:
3635                 case 4:
3636                 case 5:
3637                 case 6:
3638                 case 7:     // 1 byte format: 0xxxxxxx
3639                     sbuf.append((char) b1);
3640                     return 1;
3641 
3642                 case 12:
3643                 case 13:    // 2 byte format: 110xxxxx 10xxxxxx
3644                     if (utflen < 2) {
3645                         throw new UTFDataFormatException();
3646                     }
3647                     b2 = readByte();
3648                     if ((b2 & 0xC0) != 0x80) {
3649                         throw new UTFDataFormatException();
3650                     }
3651                     sbuf.append((char) (((b1 & 0x1F) << 6) |
3652                                         ((b2 & 0x3F) << 0)));
3653                     return 2;
3654 
3655                 case 14:    // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
3656                     if (utflen < 3) {
3657                         if (utflen == 2) {
3658                             readByte();         // consume remaining byte
3659                         }
3660                         throw new UTFDataFormatException();
3661                     }
3662                     b2 = readByte();
3663                     b3 = readByte();
3664                     if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
3665                         throw new UTFDataFormatException();
3666                     }
3667                     sbuf.append((char) (((b1 & 0x0F) << 12) |
3668                                         ((b2 & 0x3F) << 6) |
3669                                         ((b3 & 0x3F) << 0)));
3670                     return 3;
3671 
3672                 default:   // 10xx xxxx, 1111 xxxx
3673                     throw new UTFDataFormatException();
3674             }
3675         }
3676 
3677         /**
3678          * Returns the number of bytes read from the input stream.
3679          * @return the number of bytes read from the input stream
3680          */
3681         long getBytesRead() {
3682             return in.getBytesRead();
3683         }
3684     }
3685 
3686     /**
3687      * Unsynchronized table which tracks wire handle to object mappings, as
3688      * well as ClassNotFoundExceptions associated with deserialized objects.
3689      * This class implements an exception-propagation algorithm for
3690      * determining which objects should have ClassNotFoundExceptions associated
3691      * with them, taking into account cycles and discontinuities (e.g., skipped
3692      * fields) in the object graph.
3693      *
3694      * <p>General use of the table is as follows: during deserialization, a
3695      * given object is first assigned a handle by calling the assign method.
3696      * This method leaves the assigned handle in an "open" state, wherein
3697      * dependencies on the exception status of other handles can be registered
3698      * by calling the markDependency method, or an exception can be directly
3699      * associated with the handle by calling markException.  When a handle is
3700      * tagged with an exception, the HandleTable assumes responsibility for
3701      * propagating the exception to any other objects which depend
3702      * (transitively) on the exception-tagged object.
3703      *
3704      * <p>Once all exception information/dependencies for the handle have been
3705      * registered, the handle should be "closed" by calling the finish method
3706      * on it.  The act of finishing a handle allows the exception propagation
3707      * algorithm to aggressively prune dependency links, lessening the
3708      * performance/memory impact of exception tracking.
3709      *
3710      * <p>Note that the exception propagation algorithm used depends on handles
3711      * being assigned/finished in LIFO order; however, for simplicity as well
3712      * as memory conservation, it does not enforce this constraint.
3713      */
3714     // REMIND: add full description of exception propagation algorithm?
3715     private static class HandleTable {
3716 
3717         /* status codes indicating whether object has associated exception */
3718         private static final byte STATUS_OK = 1;
3719         private static final byte STATUS_UNKNOWN = 2;
3720         private static final byte STATUS_EXCEPTION = 3;
3721 
3722         /** array mapping handle -> object status */
3723         byte[] status;
3724         /** array mapping handle -> object/exception (depending on status) */
3725         Object[] entries;
3726         /** array mapping handle -> list of dependent handles (if any) */
3727         HandleList[] deps;
3728         /** lowest unresolved dependency */
3729         int lowDep = -1;
3730         /** number of handles in table */
3731         int size = 0;
3732 
3733         /**
3734          * Creates handle table with the given initial capacity.
3735          */
3736         HandleTable(int initialCapacity) {
3737             status = new byte[initialCapacity];
3738             entries = new Object[initialCapacity];
3739             deps = new HandleList[initialCapacity];
3740         }
3741 
3742         /**
3743          * Assigns next available handle to given object, and returns assigned
3744          * handle.  Once object has been completely deserialized (and all
3745          * dependencies on other objects identified), the handle should be
3746          * "closed" by passing it to finish().
3747          */
3748         int assign(Object obj) {
3749             if (size >= entries.length) {
3750                 grow();
3751             }
3752             status[size] = STATUS_UNKNOWN;
3753             entries[size] = obj;
3754             return size++;
3755         }
3756 
3757         /**
3758          * Registers a dependency (in exception status) of one handle on
3759          * another.  The dependent handle must be "open" (i.e., assigned, but
3760          * not finished yet).  No action is taken if either dependent or target
3761          * handle is NULL_HANDLE. Additionally, no action is taken if the
3762          * dependent and target are the same.
3763          */
3764         void markDependency(int dependent, int target) {
3765             if (dependent == target || dependent == NULL_HANDLE || target == NULL_HANDLE) {
3766                 return;
3767             }
3768             switch (status[dependent]) {
3769 
3770                 case STATUS_UNKNOWN:
3771                     switch (status[target]) {
3772                         case STATUS_OK:
3773                             // ignore dependencies on objs with no exception
3774                             break;
3775 
3776                         case STATUS_EXCEPTION:
3777                             // eagerly propagate exception
3778                             markException(dependent,
3779                                 (ClassNotFoundException) entries[target]);
3780                             break;
3781 
3782                         case STATUS_UNKNOWN:
3783                             // add to dependency list of target
3784                             if (deps[target] == null) {
3785                                 deps[target] = new HandleList();
3786                             }
3787                             deps[target].add(dependent);
3788 
3789                             // remember lowest unresolved target seen
3790                             if (lowDep < 0 || lowDep > target) {
3791                                 lowDep = target;
3792                             }
3793                             break;
3794 
3795                         default:
3796                             throw new InternalError();
3797                     }
3798                     break;
3799 
3800                 case STATUS_EXCEPTION:
3801                     break;
3802 
3803                 default:
3804                     throw new InternalError();
3805             }
3806         }
3807 
3808         /**
3809          * Associates a ClassNotFoundException (if one not already associated)
3810          * with the currently active handle and propagates it to other
3811          * referencing objects as appropriate.  The specified handle must be
3812          * "open" (i.e., assigned, but not finished yet).
3813          */
3814         void markException(int handle, ClassNotFoundException ex) {
3815             switch (status[handle]) {
3816                 case STATUS_UNKNOWN:
3817                     status[handle] = STATUS_EXCEPTION;
3818                     entries[handle] = ex;
3819 
3820                     // propagate exception to dependents
3821                     HandleList dlist = deps[handle];
3822                     if (dlist != null) {
3823                         int ndeps = dlist.size();
3824                         for (int i = 0; i < ndeps; i++) {
3825                             markException(dlist.get(i), ex);
3826                         }
3827                         deps[handle] = null;
3828                     }
3829                     break;
3830 
3831                 case STATUS_EXCEPTION:
3832                     break;
3833 
3834                 default:
3835                     throw new InternalError();
3836             }
3837         }
3838 
3839         /**
3840          * Marks given handle as finished, meaning that no new dependencies
3841          * will be marked for handle.  Calls to the assign and finish methods
3842          * must occur in LIFO order.
3843          */
3844         void finish(int handle) {
3845             int end;
3846             if (lowDep < 0) {
3847                 // no pending unknowns, only resolve current handle
3848                 end = handle + 1;
3849             } else if (lowDep >= handle) {
3850                 // pending unknowns now clearable, resolve all upward handles
3851                 end = size;
3852                 lowDep = -1;
3853             } else {
3854                 // unresolved backrefs present, can't resolve anything yet
3855                 return;
3856             }
3857 
3858             // change STATUS_UNKNOWN -> STATUS_OK in selected span of handles
3859             for (int i = handle; i < end; i++) {
3860                 switch (status[i]) {
3861                     case STATUS_UNKNOWN:
3862                         status[i] = STATUS_OK;
3863                         deps[i] = null;
3864                         break;
3865 
3866                     case STATUS_OK:
3867                     case STATUS_EXCEPTION:
3868                         break;
3869 
3870                     default:
3871                         throw new InternalError();
3872                 }
3873             }
3874         }
3875 
3876         /**
3877          * Assigns a new object to the given handle.  The object previously
3878          * associated with the handle is forgotten.  This method has no effect
3879          * if the given handle already has an exception associated with it.
3880          * This method may be called at any time after the handle is assigned.
3881          */
3882         void setObject(int handle, Object obj) {
3883             switch (status[handle]) {
3884                 case STATUS_UNKNOWN:
3885                 case STATUS_OK:
3886                     entries[handle] = obj;
3887                     break;
3888 
3889                 case STATUS_EXCEPTION:
3890                     break;
3891 
3892                 default:
3893                     throw new InternalError();
3894             }
3895         }
3896 
3897         /**
3898          * Looks up and returns object associated with the given handle.
3899          * Returns null if the given handle is NULL_HANDLE, or if it has an
3900          * associated ClassNotFoundException.
3901          */
3902         Object lookupObject(int handle) {
3903             return (handle != NULL_HANDLE &&
3904                     status[handle] != STATUS_EXCEPTION) ?
3905                 entries[handle] : null;
3906         }
3907 
3908         /**
3909          * Looks up and returns ClassNotFoundException associated with the
3910          * given handle.  Returns null if the given handle is NULL_HANDLE, or
3911          * if there is no ClassNotFoundException associated with the handle.
3912          */
3913         ClassNotFoundException lookupException(int handle) {
3914             return (handle != NULL_HANDLE &&
3915                     status[handle] == STATUS_EXCEPTION) ?
3916                 (ClassNotFoundException) entries[handle] : null;
3917         }
3918 
3919         /**
3920          * Resets table to its initial state.
3921          */
3922         void clear() {
3923             Arrays.fill(status, 0, size, (byte) 0);
3924             Arrays.fill(entries, 0, size, null);
3925             Arrays.fill(deps, 0, size, null);
3926             lowDep = -1;
3927             size = 0;
3928         }
3929 
3930         /**
3931          * Returns number of handles registered in table.
3932          */
3933         int size() {
3934             return size;
3935         }
3936 
3937         /**
3938          * Expands capacity of internal arrays.
3939          */
3940         private void grow() {
3941             int newCapacity = (entries.length << 1) + 1;
3942 
3943             byte[] newStatus = new byte[newCapacity];
3944             Object[] newEntries = new Object[newCapacity];
3945             HandleList[] newDeps = new HandleList[newCapacity];
3946 
3947             System.arraycopy(status, 0, newStatus, 0, size);
3948             System.arraycopy(entries, 0, newEntries, 0, size);
3949             System.arraycopy(deps, 0, newDeps, 0, size);
3950 
3951             status = newStatus;
3952             entries = newEntries;
3953             deps = newDeps;
3954         }
3955 
3956         /**
3957          * Simple growable list of (integer) handles.
3958          */
3959         private static class HandleList {
3960             private int[] list = new int[4];
3961             private int size = 0;
3962 
3963             public HandleList() {
3964             }
3965 
3966             public void add(int handle) {
3967                 if (size >= list.length) {
3968                     int[] newList = new int[list.length << 1];
3969                     System.arraycopy(list, 0, newList, 0, list.length);
3970                     list = newList;
3971                 }
3972                 list[size++] = handle;
3973             }
3974 
3975             public int get(int index) {
3976                 if (index >= size) {
3977                     throw new ArrayIndexOutOfBoundsException();
3978                 }
3979                 return list[index];
3980             }
3981 
3982             public int size() {
3983                 return size;
3984             }
3985         }
3986     }
3987 
3988     /**
3989      * Method for cloning arrays in case of using unsharing reading
3990      */
3991     private static Object cloneArray(Object array) {
3992         if (array instanceof Object[]) {
3993             return ((Object[]) array).clone();
3994         } else if (array instanceof boolean[]) {
3995             return ((boolean[]) array).clone();
3996         } else if (array instanceof byte[]) {
3997             return ((byte[]) array).clone();
3998         } else if (array instanceof char[]) {
3999             return ((char[]) array).clone();
4000         } else if (array instanceof double[]) {
4001             return ((double[]) array).clone();
4002         } else if (array instanceof float[]) {
4003             return ((float[]) array).clone();
4004         } else if (array instanceof int[]) {
4005             return ((int[]) array).clone();
4006         } else if (array instanceof long[]) {
4007             return ((long[]) array).clone();
4008         } else if (array instanceof short[]) {
4009             return ((short[]) array).clone();
4010         } else {
4011             throw new AssertionError();
4012         }
4013     }
4014 
4015     static {
4016         SharedSecrets.setJavaObjectInputStreamAccess(ObjectInputStream::checkArray);
4017     }
4018 
4019 }