1 /*
   2  * Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;
  27 
  28 import java.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.access.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) system-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 system-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 system-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 ObjectInputStream that
 451      + constructed ObjectInputStream 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 system-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 system-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 system-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             // Info about the stream is not available if overridden by subclass, return 0
1267             long bytesRead = (bin == null) ? 0 : bin.getBytesRead();
1268             try {
1269                 status = serialFilter.checkInput(new FilterValues(clazz, arrayLength,
1270                         totalObjectRefs, depth, bytesRead));
1271             } catch (RuntimeException e) {
1272                 // Preventive interception of an exception to log
1273                 status = ObjectInputFilter.Status.REJECTED;
1274                 ex = e;
1275             }
1276             if (Logging.filterLogger != null) {
1277                 // Debug logging of filter checks that fail; Tracing for those that succeed
1278                 Logging.filterLogger.log(status == null || status == ObjectInputFilter.Status.REJECTED
1279                                 ? Logger.Level.DEBUG
1280                                 : Logger.Level.TRACE,
1281                         "ObjectInputFilter {0}: {1}, array length: {2}, nRefs: {3}, depth: {4}, bytes: {5}, ex: {6}",
1282                         status, clazz, arrayLength, totalObjectRefs, depth, bytesRead,
1283                         Objects.toString(ex, "n/a"));
1284             }
1285             if (status == null ||
1286                     status == ObjectInputFilter.Status.REJECTED) {
1287                 InvalidClassException ice = new InvalidClassException("filter status: " + status);
1288                 ice.initCause(ex);
1289                 throw ice;
1290             }
1291         }
1292     }
1293 
1294     /**
1295      * Checks the given array type and length to ensure that creation of such
1296      * an array is permitted by this ObjectInputStream. The arrayType argument
1297      * must represent an actual array type.
1298      *
1299      * This private method is called via SharedSecrets.
1300      *
1301      * @param arrayType the array type
1302      * @param arrayLength the array length
1303      * @throws NullPointerException if arrayType is null
1304      * @throws IllegalArgumentException if arrayType isn't actually an array type
1305      * @throws NegativeArraySizeException if arrayLength is negative
1306      * @throws InvalidClassException if the filter rejects creation
1307      */
1308     private void checkArray(Class<?> arrayType, int arrayLength) throws InvalidClassException {
1309         if (! arrayType.isArray()) {
1310             throw new IllegalArgumentException("not an array type");
1311         }
1312 
1313         if (arrayLength < 0) {
1314             throw new NegativeArraySizeException();
1315         }
1316 
1317         filterCheck(arrayType, arrayLength);
1318     }
1319 
1320     /**
1321      * Provide access to the persistent fields read from the input stream.
1322      */
1323     public abstract static class GetField {
1324         /**
1325          * Constructor for subclasses to call.
1326          */
1327         public GetField() {}
1328 
1329         /**
1330          * Get the ObjectStreamClass that describes the fields in the stream.
1331          *
1332          * @return  the descriptor class that describes the serializable fields
1333          */
1334         public abstract ObjectStreamClass getObjectStreamClass();
1335 
1336         /**
1337          * Return true if the named field is defaulted and has no value in this
1338          * stream.
1339          *
1340          * @param  name the name of the field
1341          * @return true, if and only if the named field is defaulted
1342          * @throws IOException if there are I/O errors while reading from
1343          *         the underlying <code>InputStream</code>
1344          * @throws IllegalArgumentException if <code>name</code> does not
1345          *         correspond to a serializable field
1346          */
1347         public abstract boolean defaulted(String name) throws IOException;
1348 
1349         /**
1350          * Get the value of the named boolean field from the persistent field.
1351          *
1352          * @param  name the name of the field
1353          * @param  val the default value to use if <code>name</code> does not
1354          *         have a value
1355          * @return the value of the named <code>boolean</code> field
1356          * @throws IOException if there are I/O errors while reading from the
1357          *         underlying <code>InputStream</code>
1358          * @throws IllegalArgumentException if type of <code>name</code> is
1359          *         not serializable or if the field type is incorrect
1360          */
1361         public abstract boolean get(String name, boolean val)
1362             throws IOException;
1363 
1364         /**
1365          * Get the value of the named byte field from the persistent field.
1366          *
1367          * @param  name the name of the field
1368          * @param  val the default value to use if <code>name</code> does not
1369          *         have a value
1370          * @return the value of the named <code>byte</code> field
1371          * @throws IOException if there are I/O errors while reading from the
1372          *         underlying <code>InputStream</code>
1373          * @throws IllegalArgumentException if type of <code>name</code> is
1374          *         not serializable or if the field type is incorrect
1375          */
1376         public abstract byte get(String name, byte val) throws IOException;
1377 
1378         /**
1379          * Get the value of the named char field from the persistent field.
1380          *
1381          * @param  name the name of the field
1382          * @param  val the default value to use if <code>name</code> does not
1383          *         have a value
1384          * @return the value of the named <code>char</code> field
1385          * @throws IOException if there are I/O errors while reading from the
1386          *         underlying <code>InputStream</code>
1387          * @throws IllegalArgumentException if type of <code>name</code> is
1388          *         not serializable or if the field type is incorrect
1389          */
1390         public abstract char get(String name, char val) throws IOException;
1391 
1392         /**
1393          * Get the value of the named short field from the persistent field.
1394          *
1395          * @param  name the name of the field
1396          * @param  val the default value to use if <code>name</code> does not
1397          *         have a value
1398          * @return the value of the named <code>short</code> field
1399          * @throws IOException if there are I/O errors while reading from the
1400          *         underlying <code>InputStream</code>
1401          * @throws IllegalArgumentException if type of <code>name</code> is
1402          *         not serializable or if the field type is incorrect
1403          */
1404         public abstract short get(String name, short val) throws IOException;
1405 
1406         /**
1407          * Get the value of the named int field from the persistent field.
1408          *
1409          * @param  name the name of the field
1410          * @param  val the default value to use if <code>name</code> does not
1411          *         have a value
1412          * @return the value of the named <code>int</code> field
1413          * @throws IOException if there are I/O errors while reading from the
1414          *         underlying <code>InputStream</code>
1415          * @throws IllegalArgumentException if type of <code>name</code> is
1416          *         not serializable or if the field type is incorrect
1417          */
1418         public abstract int get(String name, int val) throws IOException;
1419 
1420         /**
1421          * Get the value of the named long field from the persistent field.
1422          *
1423          * @param  name the name of the field
1424          * @param  val the default value to use if <code>name</code> does not
1425          *         have a value
1426          * @return the value of the named <code>long</code> field
1427          * @throws IOException if there are I/O errors while reading from the
1428          *         underlying <code>InputStream</code>
1429          * @throws IllegalArgumentException if type of <code>name</code> is
1430          *         not serializable or if the field type is incorrect
1431          */
1432         public abstract long get(String name, long val) throws IOException;
1433 
1434         /**
1435          * Get the value of the named float field from the persistent field.
1436          *
1437          * @param  name the name of the field
1438          * @param  val the default value to use if <code>name</code> does not
1439          *         have a value
1440          * @return the value of the named <code>float</code> field
1441          * @throws IOException if there are I/O errors while reading from the
1442          *         underlying <code>InputStream</code>
1443          * @throws IllegalArgumentException if type of <code>name</code> is
1444          *         not serializable or if the field type is incorrect
1445          */
1446         public abstract float get(String name, float val) throws IOException;
1447 
1448         /**
1449          * Get the value of the named double field from the persistent field.
1450          *
1451          * @param  name the name of the field
1452          * @param  val the default value to use if <code>name</code> does not
1453          *         have a value
1454          * @return the value of the named <code>double</code> field
1455          * @throws IOException if there are I/O errors while reading from the
1456          *         underlying <code>InputStream</code>
1457          * @throws IllegalArgumentException if type of <code>name</code> is
1458          *         not serializable or if the field type is incorrect
1459          */
1460         public abstract double get(String name, double val) throws IOException;
1461 
1462         /**
1463          * Get the value of the named Object field from the persistent field.
1464          *
1465          * @param  name the name of the field
1466          * @param  val the default value to use if <code>name</code> does not
1467          *         have a value
1468          * @return the value of the named <code>Object</code> field
1469          * @throws IOException if there are I/O errors while reading from the
1470          *         underlying <code>InputStream</code>
1471          * @throws IllegalArgumentException if type of <code>name</code> is
1472          *         not serializable or if the field type is incorrect
1473          */
1474         public abstract Object get(String name, Object val) throws IOException;
1475     }
1476 
1477     /**
1478      * Verifies that this (possibly subclass) instance can be constructed
1479      * without violating security constraints: the subclass must not override
1480      * security-sensitive non-final methods, or else the
1481      * "enableSubclassImplementation" SerializablePermission is checked.
1482      */
1483     private void verifySubclass() {
1484         Class<?> cl = getClass();
1485         if (cl == ObjectInputStream.class) {
1486             return;
1487         }
1488         SecurityManager sm = System.getSecurityManager();
1489         if (sm == null) {
1490             return;
1491         }
1492         processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1493         WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1494         Boolean result = Caches.subclassAudits.get(key);
1495         if (result == null) {
1496             result = auditSubclass(cl);
1497             Caches.subclassAudits.putIfAbsent(key, result);
1498         }
1499         if (!result) {
1500             sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
1501         }
1502     }
1503 
1504     /**
1505      * Performs reflective checks on given subclass to verify that it doesn't
1506      * override security-sensitive non-final methods.  Returns TRUE if subclass
1507      * is "safe", FALSE otherwise.
1508      */
1509     private static Boolean auditSubclass(Class<?> subcl) {
1510         return AccessController.doPrivileged(
1511             new PrivilegedAction<Boolean>() {
1512                 public Boolean run() {
1513                     for (Class<?> cl = subcl;
1514                          cl != ObjectInputStream.class;
1515                          cl = cl.getSuperclass())
1516                     {
1517                         try {
1518                             cl.getDeclaredMethod(
1519                                 "readUnshared", (Class[]) null);
1520                             return Boolean.FALSE;
1521                         } catch (NoSuchMethodException ex) {
1522                         }
1523                         try {
1524                             cl.getDeclaredMethod("readFields", (Class[]) null);
1525                             return Boolean.FALSE;
1526                         } catch (NoSuchMethodException ex) {
1527                         }
1528                     }
1529                     return Boolean.TRUE;
1530                 }
1531             }
1532         );
1533     }
1534 
1535     /**
1536      * Clears internal data structures.
1537      */
1538     private void clear() {
1539         handles.clear();
1540         vlist.clear();
1541     }
1542 
1543     /**
1544      * Underlying readObject implementation.
1545      */
1546     private Object readObject0(boolean unshared) throws IOException {
1547         boolean oldMode = bin.getBlockDataMode();
1548         if (oldMode) {
1549             int remain = bin.currentBlockRemaining();
1550             if (remain > 0) {
1551                 throw new OptionalDataException(remain);
1552             } else if (defaultDataEnd) {
1553                 /*
1554                  * Fix for 4360508: stream is currently at the end of a field
1555                  * value block written via default serialization; since there
1556                  * is no terminating TC_ENDBLOCKDATA tag, simulate
1557                  * end-of-custom-data behavior explicitly.
1558                  */
1559                 throw new OptionalDataException(true);
1560             }
1561             bin.setBlockDataMode(false);
1562         }
1563 
1564         byte tc;
1565         while ((tc = bin.peekByte()) == TC_RESET) {
1566             bin.readByte();
1567             handleReset();
1568         }
1569 
1570         depth++;
1571         totalObjectRefs++;
1572         try {
1573             switch (tc) {
1574                 case TC_NULL:
1575                     return readNull();
1576 
1577                 case TC_REFERENCE:
1578                     return readHandle(unshared);
1579 
1580                 case TC_CLASS:
1581                     return readClass(unshared);
1582 
1583                 case TC_CLASSDESC:
1584                 case TC_PROXYCLASSDESC:
1585                     return readClassDesc(unshared);
1586 
1587                 case TC_STRING:
1588                 case TC_LONGSTRING:
1589                     return checkResolve(readString(unshared));
1590 
1591                 case TC_ARRAY:
1592                     return checkResolve(readArray(unshared));
1593 
1594                 case TC_ENUM:
1595                     return checkResolve(readEnum(unshared));
1596 
1597                 case TC_OBJECT:
1598                     return checkResolve(readOrdinaryObject(unshared));
1599 
1600                 case TC_EXCEPTION:
1601                     IOException ex = readFatalException();
1602                     throw new WriteAbortedException("writing aborted", ex);
1603 
1604                 case TC_BLOCKDATA:
1605                 case TC_BLOCKDATALONG:
1606                     if (oldMode) {
1607                         bin.setBlockDataMode(true);
1608                         bin.peek();             // force header read
1609                         throw new OptionalDataException(
1610                             bin.currentBlockRemaining());
1611                     } else {
1612                         throw new StreamCorruptedException(
1613                             "unexpected block data");
1614                     }
1615 
1616                 case TC_ENDBLOCKDATA:
1617                     if (oldMode) {
1618                         throw new OptionalDataException(true);
1619                     } else {
1620                         throw new StreamCorruptedException(
1621                             "unexpected end of block data");
1622                     }
1623 
1624                 default:
1625                     throw new StreamCorruptedException(
1626                         String.format("invalid type code: %02X", tc));
1627             }
1628         } finally {
1629             depth--;
1630             bin.setBlockDataMode(oldMode);
1631         }
1632     }
1633 
1634     /**
1635      * If resolveObject has been enabled and given object does not have an
1636      * exception associated with it, calls resolveObject to determine
1637      * replacement for object, and updates handle table accordingly.  Returns
1638      * replacement object, or echoes provided object if no replacement
1639      * occurred.  Expects that passHandle is set to given object's handle prior
1640      * to calling this method.
1641      */
1642     private Object checkResolve(Object obj) throws IOException {
1643         if (!enableResolve || handles.lookupException(passHandle) != null) {
1644             return obj;
1645         }
1646         Object rep = resolveObject(obj);
1647         if (rep != obj) {
1648             // The type of the original object has been filtered but resolveObject
1649             // may have replaced it;  filter the replacement's type
1650             if (rep != null) {
1651                 if (rep.getClass().isArray()) {
1652                     filterCheck(rep.getClass(), Array.getLength(rep));
1653                 } else {
1654                     filterCheck(rep.getClass(), -1);
1655                 }
1656             }
1657             handles.setObject(passHandle, rep);
1658         }
1659         return rep;
1660     }
1661 
1662     /**
1663      * Reads string without allowing it to be replaced in stream.  Called from
1664      * within ObjectStreamClass.read().
1665      */
1666     String readTypeString() throws IOException {
1667         int oldHandle = passHandle;
1668         try {
1669             byte tc = bin.peekByte();
1670             switch (tc) {
1671                 case TC_NULL:
1672                     return (String) readNull();
1673 
1674                 case TC_REFERENCE:
1675                     return (String) readHandle(false);
1676 
1677                 case TC_STRING:
1678                 case TC_LONGSTRING:
1679                     return readString(false);
1680 
1681                 default:
1682                     throw new StreamCorruptedException(
1683                         String.format("invalid type code: %02X", tc));
1684             }
1685         } finally {
1686             passHandle = oldHandle;
1687         }
1688     }
1689 
1690     /**
1691      * Reads in null code, sets passHandle to NULL_HANDLE and returns null.
1692      */
1693     private Object readNull() throws IOException {
1694         if (bin.readByte() != TC_NULL) {
1695             throw new InternalError();
1696         }
1697         passHandle = NULL_HANDLE;
1698         return null;
1699     }
1700 
1701     /**
1702      * Reads in object handle, sets passHandle to the read handle, and returns
1703      * object associated with the handle.
1704      */
1705     private Object readHandle(boolean unshared) throws IOException {
1706         if (bin.readByte() != TC_REFERENCE) {
1707             throw new InternalError();
1708         }
1709         passHandle = bin.readInt() - baseWireHandle;
1710         if (passHandle < 0 || passHandle >= handles.size()) {
1711             throw new StreamCorruptedException(
1712                 String.format("invalid handle value: %08X", passHandle +
1713                 baseWireHandle));
1714         }
1715         if (unshared) {
1716             // REMIND: what type of exception to throw here?
1717             throw new InvalidObjectException(
1718                 "cannot read back reference as unshared");
1719         }
1720 
1721         Object obj = handles.lookupObject(passHandle);
1722         if (obj == unsharedMarker) {
1723             // REMIND: what type of exception to throw here?
1724             throw new InvalidObjectException(
1725                 "cannot read back reference to unshared object");
1726         }
1727         filterCheck(null, -1);       // just a check for number of references, depth, no class
1728         return obj;
1729     }
1730 
1731     /**
1732      * Reads in and returns class object.  Sets passHandle to class object's
1733      * assigned handle.  Returns null if class is unresolvable (in which case a
1734      * ClassNotFoundException will be associated with the class' handle in the
1735      * handle table).
1736      */
1737     private Class<?> readClass(boolean unshared) throws IOException {
1738         if (bin.readByte() != TC_CLASS) {
1739             throw new InternalError();
1740         }
1741         ObjectStreamClass desc = readClassDesc(false);
1742         Class<?> cl = desc.forClass();
1743         passHandle = handles.assign(unshared ? unsharedMarker : cl);
1744 
1745         ClassNotFoundException resolveEx = desc.getResolveException();
1746         if (resolveEx != null) {
1747             handles.markException(passHandle, resolveEx);
1748         }
1749 
1750         handles.finish(passHandle);
1751         return cl;
1752     }
1753 
1754     /**
1755      * Reads in and returns (possibly null) class descriptor.  Sets passHandle
1756      * to class descriptor's assigned handle.  If class descriptor cannot be
1757      * resolved to a class in the local VM, a ClassNotFoundException is
1758      * associated with the class descriptor's handle.
1759      */
1760     private ObjectStreamClass readClassDesc(boolean unshared)
1761         throws IOException
1762     {
1763         byte tc = bin.peekByte();
1764         ObjectStreamClass descriptor;
1765         switch (tc) {
1766             case TC_NULL:
1767                 descriptor = (ObjectStreamClass) readNull();
1768                 break;
1769             case TC_REFERENCE:
1770                 descriptor = (ObjectStreamClass) readHandle(unshared);
1771                 break;
1772             case TC_PROXYCLASSDESC:
1773                 descriptor = readProxyDesc(unshared);
1774                 break;
1775             case TC_CLASSDESC:
1776                 descriptor = readNonProxyDesc(unshared);
1777                 break;
1778             default:
1779                 throw new StreamCorruptedException(
1780                     String.format("invalid type code: %02X", tc));
1781         }
1782         return descriptor;
1783     }
1784 
1785     private boolean isCustomSubclass() {
1786         // Return true if this class is a custom subclass of ObjectInputStream
1787         return getClass().getClassLoader()
1788                     != ObjectInputStream.class.getClassLoader();
1789     }
1790 
1791     /**
1792      * Reads in and returns class descriptor for a dynamic proxy class.  Sets
1793      * passHandle to proxy class descriptor's assigned handle.  If proxy class
1794      * descriptor cannot be resolved to a class in the local VM, a
1795      * ClassNotFoundException is associated with the descriptor's handle.
1796      */
1797     private ObjectStreamClass readProxyDesc(boolean unshared)
1798         throws IOException
1799     {
1800         if (bin.readByte() != TC_PROXYCLASSDESC) {
1801             throw new InternalError();
1802         }
1803 
1804         ObjectStreamClass desc = new ObjectStreamClass();
1805         int descHandle = handles.assign(unshared ? unsharedMarker : desc);
1806         passHandle = NULL_HANDLE;
1807 
1808         int numIfaces = bin.readInt();
1809         if (numIfaces > 65535) {
1810             throw new InvalidObjectException("interface limit exceeded: "
1811                     + numIfaces);
1812         }
1813         String[] ifaces = new String[numIfaces];
1814         for (int i = 0; i < numIfaces; i++) {
1815             ifaces[i] = bin.readUTF();
1816         }
1817 
1818         Class<?> cl = null;
1819         ClassNotFoundException resolveEx = null;
1820         bin.setBlockDataMode(true);
1821         try {
1822             if ((cl = resolveProxyClass(ifaces)) == null) {
1823                 resolveEx = new ClassNotFoundException("null class");
1824             } else if (!Proxy.isProxyClass(cl)) {
1825                 throw new InvalidClassException("Not a proxy");
1826             } else {
1827                 // ReflectUtil.checkProxyPackageAccess makes a test
1828                 // equivalent to isCustomSubclass so there's no need
1829                 // to condition this call to isCustomSubclass == true here.
1830                 ReflectUtil.checkProxyPackageAccess(
1831                         getClass().getClassLoader(),
1832                         cl.getInterfaces());
1833                 // Filter the interfaces
1834                 for (Class<?> clazz : cl.getInterfaces()) {
1835                     filterCheck(clazz, -1);
1836                 }
1837             }
1838         } catch (ClassNotFoundException ex) {
1839             resolveEx = ex;
1840         }
1841 
1842         // Call filterCheck on the class before reading anything else
1843         filterCheck(cl, -1);
1844 
1845         skipCustomData();
1846 
1847         try {
1848             totalObjectRefs++;
1849             depth++;
1850             desc.initProxy(cl, resolveEx, readClassDesc(false));
1851         } finally {
1852             depth--;
1853         }
1854 
1855         handles.finish(descHandle);
1856         passHandle = descHandle;
1857         return desc;
1858     }
1859 
1860     /**
1861      * Reads in and returns class descriptor for a class that is not a dynamic
1862      * proxy class.  Sets passHandle to class descriptor's assigned handle.  If
1863      * class descriptor cannot be resolved to a class in the local VM, a
1864      * ClassNotFoundException is associated with the descriptor's handle.
1865      */
1866     private ObjectStreamClass readNonProxyDesc(boolean unshared)
1867         throws IOException
1868     {
1869         if (bin.readByte() != TC_CLASSDESC) {
1870             throw new InternalError();
1871         }
1872 
1873         ObjectStreamClass desc = new ObjectStreamClass();
1874         int descHandle = handles.assign(unshared ? unsharedMarker : desc);
1875         passHandle = NULL_HANDLE;
1876 
1877         ObjectStreamClass readDesc;
1878         try {
1879             readDesc = readClassDescriptor();
1880         } catch (ClassNotFoundException ex) {
1881             throw (IOException) new InvalidClassException(
1882                 "failed to read class descriptor").initCause(ex);
1883         }
1884 
1885         Class<?> cl = null;
1886         ClassNotFoundException resolveEx = null;
1887         bin.setBlockDataMode(true);
1888         final boolean checksRequired = isCustomSubclass();
1889         try {
1890             if ((cl = resolveClass(readDesc)) == null) {
1891                 resolveEx = new ClassNotFoundException("null class");
1892             } else if (checksRequired) {
1893                 ReflectUtil.checkPackageAccess(cl);
1894             }
1895         } catch (ClassNotFoundException ex) {
1896             resolveEx = ex;
1897         }
1898 
1899         // Call filterCheck on the class before reading anything else
1900         filterCheck(cl, -1);
1901 
1902         skipCustomData();
1903 
1904         try {
1905             totalObjectRefs++;
1906             depth++;
1907             desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false));
1908         } finally {
1909             depth--;
1910         }
1911 
1912         handles.finish(descHandle);
1913         passHandle = descHandle;
1914 
1915         return desc;
1916     }
1917 
1918     /**
1919      * Reads in and returns new string.  Sets passHandle to new string's
1920      * assigned handle.
1921      */
1922     private String readString(boolean unshared) throws IOException {
1923         String str;
1924         byte tc = bin.readByte();
1925         switch (tc) {
1926             case TC_STRING:
1927                 str = bin.readUTF();
1928                 break;
1929 
1930             case TC_LONGSTRING:
1931                 str = bin.readLongUTF();
1932                 break;
1933 
1934             default:
1935                 throw new StreamCorruptedException(
1936                     String.format("invalid type code: %02X", tc));
1937         }
1938         passHandle = handles.assign(unshared ? unsharedMarker : str);
1939         handles.finish(passHandle);
1940         return str;
1941     }
1942 
1943     /**
1944      * Reads in and returns array object, or null if array class is
1945      * unresolvable.  Sets passHandle to array's assigned handle.
1946      */
1947     private Object readArray(boolean unshared) throws IOException {
1948         if (bin.readByte() != TC_ARRAY) {
1949             throw new InternalError();
1950         }
1951 
1952         ObjectStreamClass desc = readClassDesc(false);
1953         int len = bin.readInt();
1954 
1955         filterCheck(desc.forClass(), len);
1956 
1957         Object array = null;
1958         Class<?> cl, ccl = null;
1959         if ((cl = desc.forClass()) != null) {
1960             ccl = cl.getComponentType();
1961             array = Array.newInstance(ccl, len);
1962         }
1963 
1964         int arrayHandle = handles.assign(unshared ? unsharedMarker : array);
1965         ClassNotFoundException resolveEx = desc.getResolveException();
1966         if (resolveEx != null) {
1967             handles.markException(arrayHandle, resolveEx);
1968         }
1969 
1970         if (ccl == null) {
1971             for (int i = 0; i < len; i++) {
1972                 readObject0(false);
1973             }
1974         } else if (ccl.isPrimitive()) {
1975             if (ccl == Integer.TYPE) {
1976                 bin.readInts((int[]) array, 0, len);
1977             } else if (ccl == Byte.TYPE) {
1978                 bin.readFully((byte[]) array, 0, len, true);
1979             } else if (ccl == Long.TYPE) {
1980                 bin.readLongs((long[]) array, 0, len);
1981             } else if (ccl == Float.TYPE) {
1982                 bin.readFloats((float[]) array, 0, len);
1983             } else if (ccl == Double.TYPE) {
1984                 bin.readDoubles((double[]) array, 0, len);
1985             } else if (ccl == Short.TYPE) {
1986                 bin.readShorts((short[]) array, 0, len);
1987             } else if (ccl == Character.TYPE) {
1988                 bin.readChars((char[]) array, 0, len);
1989             } else if (ccl == Boolean.TYPE) {
1990                 bin.readBooleans((boolean[]) array, 0, len);
1991             } else {
1992                 throw new InternalError();
1993             }
1994         } else {
1995             Object[] oa = (Object[]) array;
1996             for (int i = 0; i < len; i++) {
1997                 oa[i] = readObject0(false);
1998                 handles.markDependency(arrayHandle, passHandle);
1999             }
2000         }
2001 
2002         handles.finish(arrayHandle);
2003         passHandle = arrayHandle;
2004         return array;
2005     }
2006 
2007     /**
2008      * Reads in and returns enum constant, or null if enum type is
2009      * unresolvable.  Sets passHandle to enum constant's assigned handle.
2010      */
2011     private Enum<?> readEnum(boolean unshared) throws IOException {
2012         if (bin.readByte() != TC_ENUM) {
2013             throw new InternalError();
2014         }
2015 
2016         ObjectStreamClass desc = readClassDesc(false);
2017         if (!desc.isEnum()) {
2018             throw new InvalidClassException("non-enum class: " + desc);
2019         }
2020 
2021         int enumHandle = handles.assign(unshared ? unsharedMarker : null);
2022         ClassNotFoundException resolveEx = desc.getResolveException();
2023         if (resolveEx != null) {
2024             handles.markException(enumHandle, resolveEx);
2025         }
2026 
2027         String name = readString(false);
2028         Enum<?> result = null;
2029         Class<?> cl = desc.forClass();
2030         if (cl != null) {
2031             try {
2032                 @SuppressWarnings("unchecked")
2033                 Enum<?> en = Enum.valueOf((Class)cl, name);
2034                 result = en;
2035             } catch (IllegalArgumentException ex) {
2036                 throw (IOException) new InvalidObjectException(
2037                     "enum constant " + name + " does not exist in " +
2038                     cl).initCause(ex);
2039             }
2040             if (!unshared) {
2041                 handles.setObject(enumHandle, result);
2042             }
2043         }
2044 
2045         handles.finish(enumHandle);
2046         passHandle = enumHandle;
2047         return result;
2048     }
2049 
2050     /**
2051      * Reads and returns "ordinary" (i.e., not a String, Class,
2052      * ObjectStreamClass, array, or enum constant) object, or null if object's
2053      * class is unresolvable (in which case a ClassNotFoundException will be
2054      * associated with object's handle).  Sets passHandle to object's assigned
2055      * handle.
2056      */
2057     private Object readOrdinaryObject(boolean unshared)
2058         throws IOException
2059     {
2060         if (bin.readByte() != TC_OBJECT) {
2061             throw new InternalError();
2062         }
2063 
2064         ObjectStreamClass desc = readClassDesc(false);
2065         desc.checkDeserialize();
2066 
2067         Class<?> cl = desc.forClass();
2068         if (cl == String.class || cl == Class.class
2069                 || cl == ObjectStreamClass.class) {
2070             throw new InvalidClassException("invalid class descriptor");
2071         }
2072 
2073         Object obj;
2074         try {
2075             obj = desc.isInstantiable() ? desc.newInstance() : null;
2076         } catch (Exception ex) {
2077             throw (IOException) new InvalidClassException(
2078                 desc.forClass().getName(),
2079                 "unable to create instance").initCause(ex);
2080         }
2081 
2082         passHandle = handles.assign(unshared ? unsharedMarker : obj);
2083         ClassNotFoundException resolveEx = desc.getResolveException();
2084         if (resolveEx != null) {
2085             handles.markException(passHandle, resolveEx);
2086         }
2087 
2088         if (desc.isExternalizable()) {
2089             readExternalData((Externalizable) obj, desc);
2090         } else {
2091             readSerialData(obj, desc);
2092         }
2093 
2094         handles.finish(passHandle);
2095 
2096         if (obj != null &&
2097             handles.lookupException(passHandle) == null &&
2098             desc.hasReadResolveMethod())
2099         {
2100             Object rep = desc.invokeReadResolve(obj);
2101             if (unshared && rep.getClass().isArray()) {
2102                 rep = cloneArray(rep);
2103             }
2104             if (rep != obj) {
2105                 // Filter the replacement object
2106                 if (rep != null) {
2107                     if (rep.getClass().isArray()) {
2108                         filterCheck(rep.getClass(), Array.getLength(rep));
2109                     } else {
2110                         filterCheck(rep.getClass(), -1);
2111                     }
2112                 }
2113                 handles.setObject(passHandle, obj = rep);
2114             }
2115         }
2116 
2117         return obj;
2118     }
2119 
2120     /**
2121      * If obj is non-null, reads externalizable data by invoking readExternal()
2122      * method of obj; otherwise, attempts to skip over externalizable data.
2123      * Expects that passHandle is set to obj's handle before this method is
2124      * called.
2125      */
2126     private void readExternalData(Externalizable obj, ObjectStreamClass desc)
2127         throws IOException
2128     {
2129         SerialCallbackContext oldContext = curContext;
2130         if (oldContext != null)
2131             oldContext.check();
2132         curContext = null;
2133         try {
2134             boolean blocked = desc.hasBlockExternalData();
2135             if (blocked) {
2136                 bin.setBlockDataMode(true);
2137             }
2138             if (obj != null) {
2139                 try {
2140                     obj.readExternal(this);
2141                 } catch (ClassNotFoundException ex) {
2142                     /*
2143                      * In most cases, the handle table has already propagated
2144                      * a CNFException to passHandle at this point; this mark
2145                      * call is included to address cases where the readExternal
2146                      * method has cons'ed and thrown a new CNFException of its
2147                      * own.
2148                      */
2149                      handles.markException(passHandle, ex);
2150                 }
2151             }
2152             if (blocked) {
2153                 skipCustomData();
2154             }
2155         } finally {
2156             if (oldContext != null)
2157                 oldContext.check();
2158             curContext = oldContext;
2159         }
2160         /*
2161          * At this point, if the externalizable data was not written in
2162          * block-data form and either the externalizable class doesn't exist
2163          * locally (i.e., obj == null) or readExternal() just threw a
2164          * CNFException, then the stream is probably in an inconsistent state,
2165          * since some (or all) of the externalizable data may not have been
2166          * consumed.  Since there's no "correct" action to take in this case,
2167          * we mimic the behavior of past serialization implementations and
2168          * blindly hope that the stream is in sync; if it isn't and additional
2169          * externalizable data remains in the stream, a subsequent read will
2170          * most likely throw a StreamCorruptedException.
2171          */
2172     }
2173 
2174     /**
2175      * Reads (or attempts to skip, if obj is null or is tagged with a
2176      * ClassNotFoundException) instance data for each serializable class of
2177      * object in stream, from superclass to subclass.  Expects that passHandle
2178      * is set to obj's handle before this method is called.
2179      */
2180     private void readSerialData(Object obj, ObjectStreamClass desc)
2181         throws IOException
2182     {
2183         ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
2184         // Best effort Failure Atomicity; slotValues will be non-null if field
2185         // values can be set after reading all field data in the hierarchy.
2186         // Field values can only be set after reading all data if there are no
2187         // user observable methods in the hierarchy, readObject(NoData). The
2188         // top most Serializable class in the hierarchy can be skipped.
2189         FieldValues[] slotValues = null;
2190 
2191         boolean hasSpecialReadMethod = false;
2192         for (int i = 1; i < slots.length; i++) {
2193             ObjectStreamClass slotDesc = slots[i].desc;
2194             if (slotDesc.hasReadObjectMethod()
2195                   || slotDesc.hasReadObjectNoDataMethod()) {
2196                 hasSpecialReadMethod = true;
2197                 break;
2198             }
2199         }
2200         // No special read methods, can store values and defer setting.
2201         if (!hasSpecialReadMethod)
2202             slotValues = new FieldValues[slots.length];
2203 
2204         for (int i = 0; i < slots.length; i++) {
2205             ObjectStreamClass slotDesc = slots[i].desc;
2206 
2207             if (slots[i].hasData) {
2208                 if (obj == null || handles.lookupException(passHandle) != null) {
2209                     defaultReadFields(null, slotDesc); // skip field values
2210                 } else if (slotDesc.hasReadObjectMethod()) {
2211                     ThreadDeath t = null;
2212                     boolean reset = false;
2213                     SerialCallbackContext oldContext = curContext;
2214                     if (oldContext != null)
2215                         oldContext.check();
2216                     try {
2217                         curContext = new SerialCallbackContext(obj, slotDesc);
2218 
2219                         bin.setBlockDataMode(true);
2220                         slotDesc.invokeReadObject(obj, this);
2221                     } catch (ClassNotFoundException ex) {
2222                         /*
2223                          * In most cases, the handle table has already
2224                          * propagated a CNFException to passHandle at this
2225                          * point; this mark call is included to address cases
2226                          * where the custom readObject method has cons'ed and
2227                          * thrown a new CNFException of its own.
2228                          */
2229                         handles.markException(passHandle, ex);
2230                     } finally {
2231                         do {
2232                             try {
2233                                 curContext.setUsed();
2234                                 if (oldContext!= null)
2235                                     oldContext.check();
2236                                 curContext = oldContext;
2237                                 reset = true;
2238                             } catch (ThreadDeath x) {
2239                                 t = x;  // defer until reset is true
2240                             }
2241                         } while (!reset);
2242                         if (t != null)
2243                             throw t;
2244                     }
2245 
2246                     /*
2247                      * defaultDataEnd may have been set indirectly by custom
2248                      * readObject() method when calling defaultReadObject() or
2249                      * readFields(); clear it to restore normal read behavior.
2250                      */
2251                     defaultDataEnd = false;
2252                 } else {
2253                     FieldValues vals = defaultReadFields(obj, slotDesc);
2254                     if (slotValues != null) {
2255                         slotValues[i] = vals;
2256                     } else if (obj != null) {
2257                         defaultCheckFieldValues(obj, slotDesc, vals);
2258                         defaultSetFieldValues(obj, slotDesc, vals);
2259                     }
2260                 }
2261 
2262                 if (slotDesc.hasWriteObjectData()) {
2263                     skipCustomData();
2264                 } else {
2265                     bin.setBlockDataMode(false);
2266                 }
2267             } else {
2268                 if (obj != null &&
2269                     slotDesc.hasReadObjectNoDataMethod() &&
2270                     handles.lookupException(passHandle) == null)
2271                 {
2272                     slotDesc.invokeReadObjectNoData(obj);
2273                 }
2274             }
2275         }
2276 
2277         if (obj != null && slotValues != null) {
2278             // Check that the non-primitive types are assignable for all slots
2279             // before assigning.
2280             for (int i = 0; i < slots.length; i++) {
2281                 if (slotValues[i] != null)
2282                     defaultCheckFieldValues(obj, slots[i].desc, slotValues[i]);
2283             }
2284             for (int i = 0; i < slots.length; i++) {
2285                 if (slotValues[i] != null)
2286                     defaultSetFieldValues(obj, slots[i].desc, slotValues[i]);
2287             }
2288         }
2289     }
2290 
2291     /**
2292      * Skips over all block data and objects until TC_ENDBLOCKDATA is
2293      * encountered.
2294      */
2295     private void skipCustomData() throws IOException {
2296         int oldHandle = passHandle;
2297         for (;;) {
2298             if (bin.getBlockDataMode()) {
2299                 bin.skipBlockData();
2300                 bin.setBlockDataMode(false);
2301             }
2302             switch (bin.peekByte()) {
2303                 case TC_BLOCKDATA:
2304                 case TC_BLOCKDATALONG:
2305                     bin.setBlockDataMode(true);
2306                     break;
2307 
2308                 case TC_ENDBLOCKDATA:
2309                     bin.readByte();
2310                     passHandle = oldHandle;
2311                     return;
2312 
2313                 default:
2314                     readObject0(false);
2315                     break;
2316             }
2317         }
2318     }
2319 
2320     private class FieldValues {
2321         final byte[] primValues;
2322         final Object[] objValues;
2323 
2324         FieldValues(byte[] primValues, Object[] objValues) {
2325             this.primValues = primValues;
2326             this.objValues = objValues;
2327         }
2328     }
2329 
2330     /**
2331      * Reads in values of serializable fields declared by given class
2332      * descriptor. Expects that passHandle is set to obj's handle before this
2333      * method is called.
2334      */
2335     private FieldValues defaultReadFields(Object obj, ObjectStreamClass desc)
2336         throws IOException
2337     {
2338         Class<?> cl = desc.forClass();
2339         if (cl != null && obj != null && !cl.isInstance(obj)) {
2340             throw new ClassCastException();
2341         }
2342 
2343         byte[] primVals = null;
2344         int primDataSize = desc.getPrimDataSize();
2345         if (primDataSize > 0) {
2346             primVals = new byte[primDataSize];
2347             bin.readFully(primVals, 0, primDataSize, false);
2348         }
2349 
2350         Object[] objVals = null;
2351         int numObjFields = desc.getNumObjFields();
2352         if (numObjFields > 0) {
2353             int objHandle = passHandle;
2354             ObjectStreamField[] fields = desc.getFields(false);
2355             objVals = new Object[numObjFields];
2356             int numPrimFields = fields.length - objVals.length;
2357             for (int i = 0; i < objVals.length; i++) {
2358                 ObjectStreamField f = fields[numPrimFields + i];
2359                 objVals[i] = readObject0(f.isUnshared());
2360                 if (f.getField() != null) {
2361                     handles.markDependency(objHandle, passHandle);
2362                 }
2363             }
2364             passHandle = objHandle;
2365         }
2366 
2367         return new FieldValues(primVals, objVals);
2368     }
2369 
2370     /** Throws ClassCastException if any value is not assignable. */
2371     private void defaultCheckFieldValues(Object obj, ObjectStreamClass desc,
2372                                          FieldValues values) {
2373         Object[] objectValues = values.objValues;
2374         if (objectValues != null)
2375             desc.checkObjFieldValueTypes(obj, objectValues);
2376     }
2377 
2378     /** Sets field values in obj. */
2379     private void defaultSetFieldValues(Object obj, ObjectStreamClass desc,
2380                                        FieldValues values) {
2381         byte[] primValues = values.primValues;
2382         Object[] objectValues = values.objValues;
2383 
2384         if (primValues != null)
2385             desc.setPrimFieldValues(obj, primValues);
2386         if (objectValues != null)
2387             desc.setObjFieldValues(obj, objectValues);
2388     }
2389 
2390     /**
2391      * Reads in and returns IOException that caused serialization to abort.
2392      * All stream state is discarded prior to reading in fatal exception.  Sets
2393      * passHandle to fatal exception's handle.
2394      */
2395     private IOException readFatalException() throws IOException {
2396         if (bin.readByte() != TC_EXCEPTION) {
2397             throw new InternalError();
2398         }
2399         clear();
2400         return (IOException) readObject0(false);
2401     }
2402 
2403     /**
2404      * If recursion depth is 0, clears internal data structures; otherwise,
2405      * throws a StreamCorruptedException.  This method is called when a
2406      * TC_RESET typecode is encountered.
2407      */
2408     private void handleReset() throws StreamCorruptedException {
2409         if (depth > 0) {
2410             throw new StreamCorruptedException(
2411                 "unexpected reset; recursion depth: " + depth);
2412         }
2413         clear();
2414     }
2415 
2416     /**
2417      * Converts specified span of bytes into float values.
2418      */
2419     // REMIND: remove once hotspot inlines Float.intBitsToFloat
2420     private static native void bytesToFloats(byte[] src, int srcpos,
2421                                              float[] dst, int dstpos,
2422                                              int nfloats);
2423 
2424     /**
2425      * Converts specified span of bytes into double values.
2426      */
2427     // REMIND: remove once hotspot inlines Double.longBitsToDouble
2428     private static native void bytesToDoubles(byte[] src, int srcpos,
2429                                               double[] dst, int dstpos,
2430                                               int ndoubles);
2431 
2432     /**
2433      * Returns the first non-null and non-platform class loader (not counting
2434      * class loaders of generated reflection implementation classes) up the
2435      * execution stack, or the platform class loader if only code from the
2436      * bootstrap and platform class loader is on the stack.
2437      */
2438     private static ClassLoader latestUserDefinedLoader() {
2439         return jdk.internal.misc.VM.latestUserDefinedLoader();
2440     }
2441 
2442     /**
2443      * Default GetField implementation.
2444      */
2445     private class GetFieldImpl extends GetField {
2446 
2447         /** class descriptor describing serializable fields */
2448         private final ObjectStreamClass desc;
2449         /** primitive field values */
2450         private final byte[] primVals;
2451         /** object field values */
2452         private final Object[] objVals;
2453         /** object field value handles */
2454         private final int[] objHandles;
2455 
2456         /**
2457          * Creates GetFieldImpl object for reading fields defined in given
2458          * class descriptor.
2459          */
2460         GetFieldImpl(ObjectStreamClass desc) {
2461             this.desc = desc;
2462             primVals = new byte[desc.getPrimDataSize()];
2463             objVals = new Object[desc.getNumObjFields()];
2464             objHandles = new int[objVals.length];
2465         }
2466 
2467         public ObjectStreamClass getObjectStreamClass() {
2468             return desc;
2469         }
2470 
2471         public boolean defaulted(String name) throws IOException {
2472             return (getFieldOffset(name, null) < 0);
2473         }
2474 
2475         public boolean get(String name, boolean val) throws IOException {
2476             int off = getFieldOffset(name, Boolean.TYPE);
2477             return (off >= 0) ? Bits.getBoolean(primVals, off) : val;
2478         }
2479 
2480         public byte get(String name, byte val) throws IOException {
2481             int off = getFieldOffset(name, Byte.TYPE);
2482             return (off >= 0) ? primVals[off] : val;
2483         }
2484 
2485         public char get(String name, char val) throws IOException {
2486             int off = getFieldOffset(name, Character.TYPE);
2487             return (off >= 0) ? Bits.getChar(primVals, off) : val;
2488         }
2489 
2490         public short get(String name, short val) throws IOException {
2491             int off = getFieldOffset(name, Short.TYPE);
2492             return (off >= 0) ? Bits.getShort(primVals, off) : val;
2493         }
2494 
2495         public int get(String name, int val) throws IOException {
2496             int off = getFieldOffset(name, Integer.TYPE);
2497             return (off >= 0) ? Bits.getInt(primVals, off) : val;
2498         }
2499 
2500         public float get(String name, float val) throws IOException {
2501             int off = getFieldOffset(name, Float.TYPE);
2502             return (off >= 0) ? Bits.getFloat(primVals, off) : val;
2503         }
2504 
2505         public long get(String name, long val) throws IOException {
2506             int off = getFieldOffset(name, Long.TYPE);
2507             return (off >= 0) ? Bits.getLong(primVals, off) : val;
2508         }
2509 
2510         public double get(String name, double val) throws IOException {
2511             int off = getFieldOffset(name, Double.TYPE);
2512             return (off >= 0) ? Bits.getDouble(primVals, off) : val;
2513         }
2514 
2515         public Object get(String name, Object val) throws IOException {
2516             int off = getFieldOffset(name, Object.class);
2517             if (off >= 0) {
2518                 int objHandle = objHandles[off];
2519                 handles.markDependency(passHandle, objHandle);
2520                 return (handles.lookupException(objHandle) == null) ?
2521                     objVals[off] : null;
2522             } else {
2523                 return val;
2524             }
2525         }
2526 
2527         /**
2528          * Reads primitive and object field values from stream.
2529          */
2530         void readFields() throws IOException {
2531             bin.readFully(primVals, 0, primVals.length, false);
2532 
2533             int oldHandle = passHandle;
2534             ObjectStreamField[] fields = desc.getFields(false);
2535             int numPrimFields = fields.length - objVals.length;
2536             for (int i = 0; i < objVals.length; i++) {
2537                 objVals[i] =
2538                     readObject0(fields[numPrimFields + i].isUnshared());
2539                 objHandles[i] = passHandle;
2540             }
2541             passHandle = oldHandle;
2542         }
2543 
2544         /**
2545          * Returns offset of field with given name and type.  A specified type
2546          * of null matches all types, Object.class matches all non-primitive
2547          * types, and any other non-null type matches assignable types only.
2548          * If no matching field is found in the (incoming) class
2549          * descriptor but a matching field is present in the associated local
2550          * class descriptor, returns -1.  Throws IllegalArgumentException if
2551          * neither incoming nor local class descriptor contains a match.
2552          */
2553         private int getFieldOffset(String name, Class<?> type) {
2554             ObjectStreamField field = desc.getField(name, type);
2555             if (field != null) {
2556                 return field.getOffset();
2557             } else if (desc.getLocalDesc().getField(name, type) != null) {
2558                 return -1;
2559             } else {
2560                 throw new IllegalArgumentException("no such field " + name +
2561                                                    " with type " + type);
2562             }
2563         }
2564     }
2565 
2566     /**
2567      * Prioritized list of callbacks to be performed once object graph has been
2568      * completely deserialized.
2569      */
2570     private static class ValidationList {
2571 
2572         private static class Callback {
2573             final ObjectInputValidation obj;
2574             final int priority;
2575             Callback next;
2576             final AccessControlContext acc;
2577 
2578             Callback(ObjectInputValidation obj, int priority, Callback next,
2579                 AccessControlContext acc)
2580             {
2581                 this.obj = obj;
2582                 this.priority = priority;
2583                 this.next = next;
2584                 this.acc = acc;
2585             }
2586         }
2587 
2588         /** linked list of callbacks */
2589         private Callback list;
2590 
2591         /**
2592          * Creates new (empty) ValidationList.
2593          */
2594         ValidationList() {
2595         }
2596 
2597         /**
2598          * Registers callback.  Throws InvalidObjectException if callback
2599          * object is null.
2600          */
2601         void register(ObjectInputValidation obj, int priority)
2602             throws InvalidObjectException
2603         {
2604             if (obj == null) {
2605                 throw new InvalidObjectException("null callback");
2606             }
2607 
2608             Callback prev = null, cur = list;
2609             while (cur != null && priority < cur.priority) {
2610                 prev = cur;
2611                 cur = cur.next;
2612             }
2613             AccessControlContext acc = AccessController.getContext();
2614             if (prev != null) {
2615                 prev.next = new Callback(obj, priority, cur, acc);
2616             } else {
2617                 list = new Callback(obj, priority, list, acc);
2618             }
2619         }
2620 
2621         /**
2622          * Invokes all registered callbacks and clears the callback list.
2623          * Callbacks with higher priorities are called first; those with equal
2624          * priorities may be called in any order.  If any of the callbacks
2625          * throws an InvalidObjectException, the callback process is terminated
2626          * and the exception propagated upwards.
2627          */
2628         void doCallbacks() throws InvalidObjectException {
2629             try {
2630                 while (list != null) {
2631                     AccessController.doPrivileged(
2632                         new PrivilegedExceptionAction<Void>()
2633                     {
2634                         public Void run() throws InvalidObjectException {
2635                             list.obj.validateObject();
2636                             return null;
2637                         }
2638                     }, list.acc);
2639                     list = list.next;
2640                 }
2641             } catch (PrivilegedActionException ex) {
2642                 list = null;
2643                 throw (InvalidObjectException) ex.getException();
2644             }
2645         }
2646 
2647         /**
2648          * Resets the callback list to its initial (empty) state.
2649          */
2650         public void clear() {
2651             list = null;
2652         }
2653     }
2654 
2655     /**
2656      * Hold a snapshot of values to be passed to an ObjectInputFilter.
2657      */
2658     static class FilterValues implements ObjectInputFilter.FilterInfo {
2659         final Class<?> clazz;
2660         final long arrayLength;
2661         final long totalObjectRefs;
2662         final long depth;
2663         final long streamBytes;
2664 
2665         public FilterValues(Class<?> clazz, long arrayLength, long totalObjectRefs,
2666                             long depth, long streamBytes) {
2667             this.clazz = clazz;
2668             this.arrayLength = arrayLength;
2669             this.totalObjectRefs = totalObjectRefs;
2670             this.depth = depth;
2671             this.streamBytes = streamBytes;
2672         }
2673 
2674         @Override
2675         public Class<?> serialClass() {
2676             return clazz;
2677         }
2678 
2679         @Override
2680         public long arrayLength() {
2681             return arrayLength;
2682         }
2683 
2684         @Override
2685         public long references() {
2686             return totalObjectRefs;
2687         }
2688 
2689         @Override
2690         public long depth() {
2691             return depth;
2692         }
2693 
2694         @Override
2695         public long streamBytes() {
2696             return streamBytes;
2697         }
2698     }
2699 
2700     /**
2701      * Input stream supporting single-byte peek operations.
2702      */
2703     private static class PeekInputStream extends InputStream {
2704 
2705         /** underlying stream */
2706         private final InputStream in;
2707         /** peeked byte */
2708         private int peekb = -1;
2709         /** total bytes read from the stream */
2710         private long totalBytesRead = 0;
2711 
2712         /**
2713          * Creates new PeekInputStream on top of given underlying stream.
2714          */
2715         PeekInputStream(InputStream in) {
2716             this.in = in;
2717         }
2718 
2719         /**
2720          * Peeks at next byte value in stream.  Similar to read(), except
2721          * that it does not consume the read value.
2722          */
2723         int peek() throws IOException {
2724             if (peekb >= 0) {
2725                 return peekb;
2726             }
2727             peekb = in.read();
2728             totalBytesRead += peekb >= 0 ? 1 : 0;
2729             return peekb;
2730         }
2731 
2732         public int read() throws IOException {
2733             if (peekb >= 0) {
2734                 int v = peekb;
2735                 peekb = -1;
2736                 return v;
2737             } else {
2738                 int nbytes = in.read();
2739                 totalBytesRead += nbytes >= 0 ? 1 : 0;
2740                 return nbytes;
2741             }
2742         }
2743 
2744         public int read(byte[] b, int off, int len) throws IOException {
2745             int nbytes;
2746             if (len == 0) {
2747                 return 0;
2748             } else if (peekb < 0) {
2749                 nbytes = in.read(b, off, len);
2750                 totalBytesRead += nbytes >= 0 ? nbytes : 0;
2751                 return nbytes;
2752             } else {
2753                 b[off++] = (byte) peekb;
2754                 len--;
2755                 peekb = -1;
2756                 nbytes = in.read(b, off, len);
2757                 totalBytesRead += nbytes >= 0 ? nbytes : 0;
2758                 return (nbytes >= 0) ? (nbytes + 1) : 1;
2759             }
2760         }
2761 
2762         void readFully(byte[] b, int off, int len) throws IOException {
2763             int n = 0;
2764             while (n < len) {
2765                 int count = read(b, off + n, len - n);
2766                 if (count < 0) {
2767                     throw new EOFException();
2768                 }
2769                 n += count;
2770             }
2771         }
2772 
2773         public long skip(long n) throws IOException {
2774             if (n <= 0) {
2775                 return 0;
2776             }
2777             int skipped = 0;
2778             if (peekb >= 0) {
2779                 peekb = -1;
2780                 skipped++;
2781                 n--;
2782             }
2783             n = skipped + in.skip(n);
2784             totalBytesRead += n;
2785             return n;
2786         }
2787 
2788         public int available() throws IOException {
2789             return in.available() + ((peekb >= 0) ? 1 : 0);
2790         }
2791 
2792         public void close() throws IOException {
2793             in.close();
2794         }
2795 
2796         public long getBytesRead() {
2797             return totalBytesRead;
2798         }
2799     }
2800 
2801     private static final Unsafe UNSAFE = Unsafe.getUnsafe();
2802 
2803     /**
2804      * Performs a "freeze" action, required to adhere to final field semantics.
2805      *
2806      * <p> This method can be called unconditionally before returning the graph,
2807      * from the topmost readObject call, since it is expected that the
2808      * additional cost of the freeze action is negligible compared to
2809      * reconstituting even the most simple graph.
2810      *
2811      * <p> Nested calls to readObject do not issue freeze actions because the
2812      * sub-graph returned from a nested call is not guaranteed to be fully
2813      * initialized yet (possible cycles).
2814      */
2815     private void freeze() {
2816         // Issue a StoreStore|StoreLoad fence, which is at least sufficient
2817         // to provide final-freeze semantics.
2818         UNSAFE.storeFence();
2819     }
2820 
2821     /**
2822      * Input stream with two modes: in default mode, inputs data written in the
2823      * same format as DataOutputStream; in "block data" mode, inputs data
2824      * bracketed by block data markers (see object serialization specification
2825      * for details).  Buffering depends on block data mode: when in default
2826      * mode, no data is buffered in advance; when in block data mode, all data
2827      * for the current data block is read in at once (and buffered).
2828      */
2829     private class BlockDataInputStream
2830         extends InputStream implements DataInput
2831     {
2832         /** maximum data block length */
2833         private static final int MAX_BLOCK_SIZE = 1024;
2834         /** maximum data block header length */
2835         private static final int MAX_HEADER_SIZE = 5;
2836         /** (tunable) length of char buffer (for reading strings) */
2837         private static final int CHAR_BUF_SIZE = 256;
2838         /** readBlockHeader() return value indicating header read may block */
2839         private static final int HEADER_BLOCKED = -2;
2840 
2841         /** buffer for reading general/block data */
2842         private final byte[] buf = new byte[MAX_BLOCK_SIZE];
2843         /** buffer for reading block data headers */
2844         private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
2845         /** char buffer for fast string reads */
2846         private final char[] cbuf = new char[CHAR_BUF_SIZE];
2847 
2848         /** block data mode */
2849         private boolean blkmode = false;
2850 
2851         // block data state fields; values meaningful only when blkmode true
2852         /** current offset into buf */
2853         private int pos = 0;
2854         /** end offset of valid data in buf, or -1 if no more block data */
2855         private int end = -1;
2856         /** number of bytes in current block yet to be read from stream */
2857         private int unread = 0;
2858 
2859         /** underlying stream (wrapped in peekable filter stream) */
2860         private final PeekInputStream in;
2861         /** loopback stream (for data reads that span data blocks) */
2862         private final DataInputStream din;
2863 
2864         /**
2865          * Creates new BlockDataInputStream on top of given underlying stream.
2866          * Block data mode is turned off by default.
2867          */
2868         BlockDataInputStream(InputStream in) {
2869             this.in = new PeekInputStream(in);
2870             din = new DataInputStream(this);
2871         }
2872 
2873         /**
2874          * Sets block data mode to the given mode (true == on, false == off)
2875          * and returns the previous mode value.  If the new mode is the same as
2876          * the old mode, no action is taken.  Throws IllegalStateException if
2877          * block data mode is being switched from on to off while unconsumed
2878          * block data is still present in the stream.
2879          */
2880         boolean setBlockDataMode(boolean newmode) throws IOException {
2881             if (blkmode == newmode) {
2882                 return blkmode;
2883             }
2884             if (newmode) {
2885                 pos = 0;
2886                 end = 0;
2887                 unread = 0;
2888             } else if (pos < end) {
2889                 throw new IllegalStateException("unread block data");
2890             }
2891             blkmode = newmode;
2892             return !blkmode;
2893         }
2894 
2895         /**
2896          * Returns true if the stream is currently in block data mode, false
2897          * otherwise.
2898          */
2899         boolean getBlockDataMode() {
2900             return blkmode;
2901         }
2902 
2903         /**
2904          * If in block data mode, skips to the end of the current group of data
2905          * blocks (but does not unset block data mode).  If not in block data
2906          * mode, throws an IllegalStateException.
2907          */
2908         void skipBlockData() throws IOException {
2909             if (!blkmode) {
2910                 throw new IllegalStateException("not in block data mode");
2911             }
2912             while (end >= 0) {
2913                 refill();
2914             }
2915         }
2916 
2917         /**
2918          * Attempts to read in the next block data header (if any).  If
2919          * canBlock is false and a full header cannot be read without possibly
2920          * blocking, returns HEADER_BLOCKED, else if the next element in the
2921          * stream is a block data header, returns the block data length
2922          * specified by the header, else returns -1.
2923          */
2924         private int readBlockHeader(boolean canBlock) throws IOException {
2925             if (defaultDataEnd) {
2926                 /*
2927                  * Fix for 4360508: stream is currently at the end of a field
2928                  * value block written via default serialization; since there
2929                  * is no terminating TC_ENDBLOCKDATA tag, simulate
2930                  * end-of-custom-data behavior explicitly.
2931                  */
2932                 return -1;
2933             }
2934             try {
2935                 for (;;) {
2936                     int avail = canBlock ? Integer.MAX_VALUE : in.available();
2937                     if (avail == 0) {
2938                         return HEADER_BLOCKED;
2939                     }
2940 
2941                     int tc = in.peek();
2942                     switch (tc) {
2943                         case TC_BLOCKDATA:
2944                             if (avail < 2) {
2945                                 return HEADER_BLOCKED;
2946                             }
2947                             in.readFully(hbuf, 0, 2);
2948                             return hbuf[1] & 0xFF;
2949 
2950                         case TC_BLOCKDATALONG:
2951                             if (avail < 5) {
2952                                 return HEADER_BLOCKED;
2953                             }
2954                             in.readFully(hbuf, 0, 5);
2955                             int len = Bits.getInt(hbuf, 1);
2956                             if (len < 0) {
2957                                 throw new StreamCorruptedException(
2958                                     "illegal block data header length: " +
2959                                     len);
2960                             }
2961                             return len;
2962 
2963                         /*
2964                          * TC_RESETs may occur in between data blocks.
2965                          * Unfortunately, this case must be parsed at a lower
2966                          * level than other typecodes, since primitive data
2967                          * reads may span data blocks separated by a TC_RESET.
2968                          */
2969                         case TC_RESET:
2970                             in.read();
2971                             handleReset();
2972                             break;
2973 
2974                         default:
2975                             if (tc >= 0 && (tc < TC_BASE || tc > TC_MAX)) {
2976                                 throw new StreamCorruptedException(
2977                                     String.format("invalid type code: %02X",
2978                                     tc));
2979                             }
2980                             return -1;
2981                     }
2982                 }
2983             } catch (EOFException ex) {
2984                 throw new StreamCorruptedException(
2985                     "unexpected EOF while reading block data header");
2986             }
2987         }
2988 
2989         /**
2990          * Refills internal buffer buf with block data.  Any data in buf at the
2991          * time of the call is considered consumed.  Sets the pos, end, and
2992          * unread fields to reflect the new amount of available block data; if
2993          * the next element in the stream is not a data block, sets pos and
2994          * unread to 0 and end to -1.
2995          */
2996         private void refill() throws IOException {
2997             try {
2998                 do {
2999                     pos = 0;
3000                     if (unread > 0) {
3001                         int n =
3002                             in.read(buf, 0, Math.min(unread, MAX_BLOCK_SIZE));
3003                         if (n >= 0) {
3004                             end = n;
3005                             unread -= n;
3006                         } else {
3007                             throw new StreamCorruptedException(
3008                                 "unexpected EOF in middle of data block");
3009                         }
3010                     } else {
3011                         int n = readBlockHeader(true);
3012                         if (n >= 0) {
3013                             end = 0;
3014                             unread = n;
3015                         } else {
3016                             end = -1;
3017                             unread = 0;
3018                         }
3019                     }
3020                 } while (pos == end);
3021             } catch (IOException ex) {
3022                 pos = 0;
3023                 end = -1;
3024                 unread = 0;
3025                 throw ex;
3026             }
3027         }
3028 
3029         /**
3030          * If in block data mode, returns the number of unconsumed bytes
3031          * remaining in the current data block.  If not in block data mode,
3032          * throws an IllegalStateException.
3033          */
3034         int currentBlockRemaining() {
3035             if (blkmode) {
3036                 return (end >= 0) ? (end - pos) + unread : 0;
3037             } else {
3038                 throw new IllegalStateException();
3039             }
3040         }
3041 
3042         /**
3043          * Peeks at (but does not consume) and returns the next byte value in
3044          * the stream, or -1 if the end of the stream/block data (if in block
3045          * data mode) has been reached.
3046          */
3047         int peek() throws IOException {
3048             if (blkmode) {
3049                 if (pos == end) {
3050                     refill();
3051                 }
3052                 return (end >= 0) ? (buf[pos] & 0xFF) : -1;
3053             } else {
3054                 return in.peek();
3055             }
3056         }
3057 
3058         /**
3059          * Peeks at (but does not consume) and returns the next byte value in
3060          * the stream, or throws EOFException if end of stream/block data has
3061          * been reached.
3062          */
3063         byte peekByte() throws IOException {
3064             int val = peek();
3065             if (val < 0) {
3066                 throw new EOFException();
3067             }
3068             return (byte) val;
3069         }
3070 
3071 
3072         /* ----------------- generic input stream methods ------------------ */
3073         /*
3074          * The following methods are equivalent to their counterparts in
3075          * InputStream, except that they interpret data block boundaries and
3076          * read the requested data from within data blocks when in block data
3077          * mode.
3078          */
3079 
3080         public int read() throws IOException {
3081             if (blkmode) {
3082                 if (pos == end) {
3083                     refill();
3084                 }
3085                 return (end >= 0) ? (buf[pos++] & 0xFF) : -1;
3086             } else {
3087                 return in.read();
3088             }
3089         }
3090 
3091         public int read(byte[] b, int off, int len) throws IOException {
3092             return read(b, off, len, false);
3093         }
3094 
3095         public long skip(long len) throws IOException {
3096             long remain = len;
3097             while (remain > 0) {
3098                 if (blkmode) {
3099                     if (pos == end) {
3100                         refill();
3101                     }
3102                     if (end < 0) {
3103                         break;
3104                     }
3105                     int nread = (int) Math.min(remain, end - pos);
3106                     remain -= nread;
3107                     pos += nread;
3108                 } else {
3109                     int nread = (int) Math.min(remain, MAX_BLOCK_SIZE);
3110                     if ((nread = in.read(buf, 0, nread)) < 0) {
3111                         break;
3112                     }
3113                     remain -= nread;
3114                 }
3115             }
3116             return len - remain;
3117         }
3118 
3119         public int available() throws IOException {
3120             if (blkmode) {
3121                 if ((pos == end) && (unread == 0)) {
3122                     int n;
3123                     while ((n = readBlockHeader(false)) == 0) ;
3124                     switch (n) {
3125                         case HEADER_BLOCKED:
3126                             break;
3127 
3128                         case -1:
3129                             pos = 0;
3130                             end = -1;
3131                             break;
3132 
3133                         default:
3134                             pos = 0;
3135                             end = 0;
3136                             unread = n;
3137                             break;
3138                     }
3139                 }
3140                 // avoid unnecessary call to in.available() if possible
3141                 int unreadAvail = (unread > 0) ?
3142                     Math.min(in.available(), unread) : 0;
3143                 return (end >= 0) ? (end - pos) + unreadAvail : 0;
3144             } else {
3145                 return in.available();
3146             }
3147         }
3148 
3149         public void close() throws IOException {
3150             if (blkmode) {
3151                 pos = 0;
3152                 end = -1;
3153                 unread = 0;
3154             }
3155             in.close();
3156         }
3157 
3158         /**
3159          * Attempts to read len bytes into byte array b at offset off.  Returns
3160          * the number of bytes read, or -1 if the end of stream/block data has
3161          * been reached.  If copy is true, reads values into an intermediate
3162          * buffer before copying them to b (to avoid exposing a reference to
3163          * b).
3164          */
3165         int read(byte[] b, int off, int len, boolean copy) throws IOException {
3166             if (len == 0) {
3167                 return 0;
3168             } else if (blkmode) {
3169                 if (pos == end) {
3170                     refill();
3171                 }
3172                 if (end < 0) {
3173                     return -1;
3174                 }
3175                 int nread = Math.min(len, end - pos);
3176                 System.arraycopy(buf, pos, b, off, nread);
3177                 pos += nread;
3178                 return nread;
3179             } else if (copy) {
3180                 int nread = in.read(buf, 0, Math.min(len, MAX_BLOCK_SIZE));
3181                 if (nread > 0) {
3182                     System.arraycopy(buf, 0, b, off, nread);
3183                 }
3184                 return nread;
3185             } else {
3186                 return in.read(b, off, len);
3187             }
3188         }
3189 
3190         /* ----------------- primitive data input methods ------------------ */
3191         /*
3192          * The following methods are equivalent to their counterparts in
3193          * DataInputStream, except that they interpret data block boundaries
3194          * and read the requested data from within data blocks when in block
3195          * data mode.
3196          */
3197 
3198         public void readFully(byte[] b) throws IOException {
3199             readFully(b, 0, b.length, false);
3200         }
3201 
3202         public void readFully(byte[] b, int off, int len) throws IOException {
3203             readFully(b, off, len, false);
3204         }
3205 
3206         public void readFully(byte[] b, int off, int len, boolean copy)
3207             throws IOException
3208         {
3209             while (len > 0) {
3210                 int n = read(b, off, len, copy);
3211                 if (n < 0) {
3212                     throw new EOFException();
3213                 }
3214                 off += n;
3215                 len -= n;
3216             }
3217         }
3218 
3219         public int skipBytes(int n) throws IOException {
3220             return din.skipBytes(n);
3221         }
3222 
3223         public boolean readBoolean() throws IOException {
3224             int v = read();
3225             if (v < 0) {
3226                 throw new EOFException();
3227             }
3228             return (v != 0);
3229         }
3230 
3231         public byte readByte() throws IOException {
3232             int v = read();
3233             if (v < 0) {
3234                 throw new EOFException();
3235             }
3236             return (byte) v;
3237         }
3238 
3239         public int readUnsignedByte() throws IOException {
3240             int v = read();
3241             if (v < 0) {
3242                 throw new EOFException();
3243             }
3244             return v;
3245         }
3246 
3247         public char readChar() throws IOException {
3248             if (!blkmode) {
3249                 pos = 0;
3250                 in.readFully(buf, 0, 2);
3251             } else if (end - pos < 2) {
3252                 return din.readChar();
3253             }
3254             char v = Bits.getChar(buf, pos);
3255             pos += 2;
3256             return v;
3257         }
3258 
3259         public short readShort() throws IOException {
3260             if (!blkmode) {
3261                 pos = 0;
3262                 in.readFully(buf, 0, 2);
3263             } else if (end - pos < 2) {
3264                 return din.readShort();
3265             }
3266             short v = Bits.getShort(buf, pos);
3267             pos += 2;
3268             return v;
3269         }
3270 
3271         public int readUnsignedShort() throws IOException {
3272             if (!blkmode) {
3273                 pos = 0;
3274                 in.readFully(buf, 0, 2);
3275             } else if (end - pos < 2) {
3276                 return din.readUnsignedShort();
3277             }
3278             int v = Bits.getShort(buf, pos) & 0xFFFF;
3279             pos += 2;
3280             return v;
3281         }
3282 
3283         public int readInt() throws IOException {
3284             if (!blkmode) {
3285                 pos = 0;
3286                 in.readFully(buf, 0, 4);
3287             } else if (end - pos < 4) {
3288                 return din.readInt();
3289             }
3290             int v = Bits.getInt(buf, pos);
3291             pos += 4;
3292             return v;
3293         }
3294 
3295         public float readFloat() throws IOException {
3296             if (!blkmode) {
3297                 pos = 0;
3298                 in.readFully(buf, 0, 4);
3299             } else if (end - pos < 4) {
3300                 return din.readFloat();
3301             }
3302             float v = Bits.getFloat(buf, pos);
3303             pos += 4;
3304             return v;
3305         }
3306 
3307         public long readLong() throws IOException {
3308             if (!blkmode) {
3309                 pos = 0;
3310                 in.readFully(buf, 0, 8);
3311             } else if (end - pos < 8) {
3312                 return din.readLong();
3313             }
3314             long v = Bits.getLong(buf, pos);
3315             pos += 8;
3316             return v;
3317         }
3318 
3319         public double readDouble() throws IOException {
3320             if (!blkmode) {
3321                 pos = 0;
3322                 in.readFully(buf, 0, 8);
3323             } else if (end - pos < 8) {
3324                 return din.readDouble();
3325             }
3326             double v = Bits.getDouble(buf, pos);
3327             pos += 8;
3328             return v;
3329         }
3330 
3331         public String readUTF() throws IOException {
3332             return readUTFBody(readUnsignedShort());
3333         }
3334 
3335         @SuppressWarnings("deprecation")
3336         public String readLine() throws IOException {
3337             return din.readLine();      // deprecated, not worth optimizing
3338         }
3339 
3340         /* -------------- primitive data array input methods --------------- */
3341         /*
3342          * The following methods read in spans of primitive data values.
3343          * Though equivalent to calling the corresponding primitive read
3344          * methods repeatedly, these methods are optimized for reading groups
3345          * of primitive data values more efficiently.
3346          */
3347 
3348         void readBooleans(boolean[] v, int off, int len) throws IOException {
3349             int stop, endoff = off + len;
3350             while (off < endoff) {
3351                 if (!blkmode) {
3352                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE);
3353                     in.readFully(buf, 0, span);
3354                     stop = off + span;
3355                     pos = 0;
3356                 } else if (end - pos < 1) {
3357                     v[off++] = din.readBoolean();
3358                     continue;
3359                 } else {
3360                     stop = Math.min(endoff, off + end - pos);
3361                 }
3362 
3363                 while (off < stop) {
3364                     v[off++] = Bits.getBoolean(buf, pos++);
3365                 }
3366             }
3367         }
3368 
3369         void readChars(char[] v, int off, int len) throws IOException {
3370             int stop, endoff = off + len;
3371             while (off < endoff) {
3372                 if (!blkmode) {
3373                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1);
3374                     in.readFully(buf, 0, span << 1);
3375                     stop = off + span;
3376                     pos = 0;
3377                 } else if (end - pos < 2) {
3378                     v[off++] = din.readChar();
3379                     continue;
3380                 } else {
3381                     stop = Math.min(endoff, off + ((end - pos) >> 1));
3382                 }
3383 
3384                 while (off < stop) {
3385                     v[off++] = Bits.getChar(buf, pos);
3386                     pos += 2;
3387                 }
3388             }
3389         }
3390 
3391         void readShorts(short[] v, int off, int len) throws IOException {
3392             int stop, endoff = off + len;
3393             while (off < endoff) {
3394                 if (!blkmode) {
3395                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1);
3396                     in.readFully(buf, 0, span << 1);
3397                     stop = off + span;
3398                     pos = 0;
3399                 } else if (end - pos < 2) {
3400                     v[off++] = din.readShort();
3401                     continue;
3402                 } else {
3403                     stop = Math.min(endoff, off + ((end - pos) >> 1));
3404                 }
3405 
3406                 while (off < stop) {
3407                     v[off++] = Bits.getShort(buf, pos);
3408                     pos += 2;
3409                 }
3410             }
3411         }
3412 
3413         void readInts(int[] v, int off, int len) throws IOException {
3414             int stop, endoff = off + len;
3415             while (off < endoff) {
3416                 if (!blkmode) {
3417                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
3418                     in.readFully(buf, 0, span << 2);
3419                     stop = off + span;
3420                     pos = 0;
3421                 } else if (end - pos < 4) {
3422                     v[off++] = din.readInt();
3423                     continue;
3424                 } else {
3425                     stop = Math.min(endoff, off + ((end - pos) >> 2));
3426                 }
3427 
3428                 while (off < stop) {
3429                     v[off++] = Bits.getInt(buf, pos);
3430                     pos += 4;
3431                 }
3432             }
3433         }
3434 
3435         void readFloats(float[] v, int off, int len) throws IOException {
3436             int span, endoff = off + len;
3437             while (off < endoff) {
3438                 if (!blkmode) {
3439                     span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
3440                     in.readFully(buf, 0, span << 2);
3441                     pos = 0;
3442                 } else if (end - pos < 4) {
3443                     v[off++] = din.readFloat();
3444                     continue;
3445                 } else {
3446                     span = Math.min(endoff - off, ((end - pos) >> 2));
3447                 }
3448 
3449                 bytesToFloats(buf, pos, v, off, span);
3450                 off += span;
3451                 pos += span << 2;
3452             }
3453         }
3454 
3455         void readLongs(long[] v, int off, int len) throws IOException {
3456             int stop, endoff = off + len;
3457             while (off < endoff) {
3458                 if (!blkmode) {
3459                     int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
3460                     in.readFully(buf, 0, span << 3);
3461                     stop = off + span;
3462                     pos = 0;
3463                 } else if (end - pos < 8) {
3464                     v[off++] = din.readLong();
3465                     continue;
3466                 } else {
3467                     stop = Math.min(endoff, off + ((end - pos) >> 3));
3468                 }
3469 
3470                 while (off < stop) {
3471                     v[off++] = Bits.getLong(buf, pos);
3472                     pos += 8;
3473                 }
3474             }
3475         }
3476 
3477         void readDoubles(double[] v, int off, int len) throws IOException {
3478             int span, endoff = off + len;
3479             while (off < endoff) {
3480                 if (!blkmode) {
3481                     span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
3482                     in.readFully(buf, 0, span << 3);
3483                     pos = 0;
3484                 } else if (end - pos < 8) {
3485                     v[off++] = din.readDouble();
3486                     continue;
3487                 } else {
3488                     span = Math.min(endoff - off, ((end - pos) >> 3));
3489                 }
3490 
3491                 bytesToDoubles(buf, pos, v, off, span);
3492                 off += span;
3493                 pos += span << 3;
3494             }
3495         }
3496 
3497         /**
3498          * Reads in string written in "long" UTF format.  "Long" UTF format is
3499          * identical to standard UTF, except that it uses an 8 byte header
3500          * (instead of the standard 2 bytes) to convey the UTF encoding length.
3501          */
3502         String readLongUTF() throws IOException {
3503             return readUTFBody(readLong());
3504         }
3505 
3506         /**
3507          * Reads in the "body" (i.e., the UTF representation minus the 2-byte
3508          * or 8-byte length header) of a UTF encoding, which occupies the next
3509          * utflen bytes.
3510          */
3511         private String readUTFBody(long utflen) throws IOException {
3512             StringBuilder sbuf;
3513             if (utflen > 0 && utflen < Integer.MAX_VALUE) {
3514                 // a reasonable initial capacity based on the UTF length
3515                 int initialCapacity = Math.min((int)utflen, 0xFFFF);
3516                 sbuf = new StringBuilder(initialCapacity);
3517             } else {
3518                 sbuf = new StringBuilder();
3519             }
3520 
3521             if (!blkmode) {
3522                 end = pos = 0;
3523             }
3524 
3525             while (utflen > 0) {
3526                 int avail = end - pos;
3527                 if (avail >= 3 || (long) avail == utflen) {
3528                     utflen -= readUTFSpan(sbuf, utflen);
3529                 } else {
3530                     if (blkmode) {
3531                         // near block boundary, read one byte at a time
3532                         utflen -= readUTFChar(sbuf, utflen);
3533                     } else {
3534                         // shift and refill buffer manually
3535                         if (avail > 0) {
3536                             System.arraycopy(buf, pos, buf, 0, avail);
3537                         }
3538                         pos = 0;
3539                         end = (int) Math.min(MAX_BLOCK_SIZE, utflen);
3540                         in.readFully(buf, avail, end - avail);
3541                     }
3542                 }
3543             }
3544 
3545             return sbuf.toString();
3546         }
3547 
3548         /**
3549          * Reads span of UTF-encoded characters out of internal buffer
3550          * (starting at offset pos and ending at or before offset end),
3551          * consuming no more than utflen bytes.  Appends read characters to
3552          * sbuf.  Returns the number of bytes consumed.
3553          */
3554         private long readUTFSpan(StringBuilder sbuf, long utflen)
3555             throws IOException
3556         {
3557             int cpos = 0;
3558             int start = pos;
3559             int avail = Math.min(end - pos, CHAR_BUF_SIZE);
3560             // stop short of last char unless all of utf bytes in buffer
3561             int stop = pos + ((utflen > avail) ? avail - 2 : (int) utflen);
3562             boolean outOfBounds = false;
3563 
3564             try {
3565                 while (pos < stop) {
3566                     int b1, b2, b3;
3567                     b1 = buf[pos++] & 0xFF;
3568                     switch (b1 >> 4) {
3569                         case 0:
3570                         case 1:
3571                         case 2:
3572                         case 3:
3573                         case 4:
3574                         case 5:
3575                         case 6:
3576                         case 7:   // 1 byte format: 0xxxxxxx
3577                             cbuf[cpos++] = (char) b1;
3578                             break;
3579 
3580                         case 12:
3581                         case 13:  // 2 byte format: 110xxxxx 10xxxxxx
3582                             b2 = buf[pos++];
3583                             if ((b2 & 0xC0) != 0x80) {
3584                                 throw new UTFDataFormatException();
3585                             }
3586                             cbuf[cpos++] = (char) (((b1 & 0x1F) << 6) |
3587                                                    ((b2 & 0x3F) << 0));
3588                             break;
3589 
3590                         case 14:  // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
3591                             b3 = buf[pos + 1];
3592                             b2 = buf[pos + 0];
3593                             pos += 2;
3594                             if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
3595                                 throw new UTFDataFormatException();
3596                             }
3597                             cbuf[cpos++] = (char) (((b1 & 0x0F) << 12) |
3598                                                    ((b2 & 0x3F) << 6) |
3599                                                    ((b3 & 0x3F) << 0));
3600                             break;
3601 
3602                         default:  // 10xx xxxx, 1111 xxxx
3603                             throw new UTFDataFormatException();
3604                     }
3605                 }
3606             } catch (ArrayIndexOutOfBoundsException ex) {
3607                 outOfBounds = true;
3608             } finally {
3609                 if (outOfBounds || (pos - start) > utflen) {
3610                     /*
3611                      * Fix for 4450867: if a malformed utf char causes the
3612                      * conversion loop to scan past the expected end of the utf
3613                      * string, only consume the expected number of utf bytes.
3614                      */
3615                     pos = start + (int) utflen;
3616                     throw new UTFDataFormatException();
3617                 }
3618             }
3619 
3620             sbuf.append(cbuf, 0, cpos);
3621             return pos - start;
3622         }
3623 
3624         /**
3625          * Reads in single UTF-encoded character one byte at a time, appends
3626          * the character to sbuf, and returns the number of bytes consumed.
3627          * This method is used when reading in UTF strings written in block
3628          * data mode to handle UTF-encoded characters which (potentially)
3629          * straddle block-data boundaries.
3630          */
3631         private int readUTFChar(StringBuilder sbuf, long utflen)
3632             throws IOException
3633         {
3634             int b1, b2, b3;
3635             b1 = readByte() & 0xFF;
3636             switch (b1 >> 4) {
3637                 case 0:
3638                 case 1:
3639                 case 2:
3640                 case 3:
3641                 case 4:
3642                 case 5:
3643                 case 6:
3644                 case 7:     // 1 byte format: 0xxxxxxx
3645                     sbuf.append((char) b1);
3646                     return 1;
3647 
3648                 case 12:
3649                 case 13:    // 2 byte format: 110xxxxx 10xxxxxx
3650                     if (utflen < 2) {
3651                         throw new UTFDataFormatException();
3652                     }
3653                     b2 = readByte();
3654                     if ((b2 & 0xC0) != 0x80) {
3655                         throw new UTFDataFormatException();
3656                     }
3657                     sbuf.append((char) (((b1 & 0x1F) << 6) |
3658                                         ((b2 & 0x3F) << 0)));
3659                     return 2;
3660 
3661                 case 14:    // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
3662                     if (utflen < 3) {
3663                         if (utflen == 2) {
3664                             readByte();         // consume remaining byte
3665                         }
3666                         throw new UTFDataFormatException();
3667                     }
3668                     b2 = readByte();
3669                     b3 = readByte();
3670                     if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
3671                         throw new UTFDataFormatException();
3672                     }
3673                     sbuf.append((char) (((b1 & 0x0F) << 12) |
3674                                         ((b2 & 0x3F) << 6) |
3675                                         ((b3 & 0x3F) << 0)));
3676                     return 3;
3677 
3678                 default:   // 10xx xxxx, 1111 xxxx
3679                     throw new UTFDataFormatException();
3680             }
3681         }
3682 
3683         /**
3684          * Returns the number of bytes read from the input stream.
3685          * @return the number of bytes read from the input stream
3686          */
3687         long getBytesRead() {
3688             return in.getBytesRead();
3689         }
3690     }
3691 
3692     /**
3693      * Unsynchronized table which tracks wire handle to object mappings, as
3694      * well as ClassNotFoundExceptions associated with deserialized objects.
3695      * This class implements an exception-propagation algorithm for
3696      * determining which objects should have ClassNotFoundExceptions associated
3697      * with them, taking into account cycles and discontinuities (e.g., skipped
3698      * fields) in the object graph.
3699      *
3700      * <p>General use of the table is as follows: during deserialization, a
3701      * given object is first assigned a handle by calling the assign method.
3702      * This method leaves the assigned handle in an "open" state, wherein
3703      * dependencies on the exception status of other handles can be registered
3704      * by calling the markDependency method, or an exception can be directly
3705      * associated with the handle by calling markException.  When a handle is
3706      * tagged with an exception, the HandleTable assumes responsibility for
3707      * propagating the exception to any other objects which depend
3708      * (transitively) on the exception-tagged object.
3709      *
3710      * <p>Once all exception information/dependencies for the handle have been
3711      * registered, the handle should be "closed" by calling the finish method
3712      * on it.  The act of finishing a handle allows the exception propagation
3713      * algorithm to aggressively prune dependency links, lessening the
3714      * performance/memory impact of exception tracking.
3715      *
3716      * <p>Note that the exception propagation algorithm used depends on handles
3717      * being assigned/finished in LIFO order; however, for simplicity as well
3718      * as memory conservation, it does not enforce this constraint.
3719      */
3720     // REMIND: add full description of exception propagation algorithm?
3721     private static class HandleTable {
3722 
3723         /* status codes indicating whether object has associated exception */
3724         private static final byte STATUS_OK = 1;
3725         private static final byte STATUS_UNKNOWN = 2;
3726         private static final byte STATUS_EXCEPTION = 3;
3727 
3728         /** array mapping handle -> object status */
3729         byte[] status;
3730         /** array mapping handle -> object/exception (depending on status) */
3731         Object[] entries;
3732         /** array mapping handle -> list of dependent handles (if any) */
3733         HandleList[] deps;
3734         /** lowest unresolved dependency */
3735         int lowDep = -1;
3736         /** number of handles in table */
3737         int size = 0;
3738 
3739         /**
3740          * Creates handle table with the given initial capacity.
3741          */
3742         HandleTable(int initialCapacity) {
3743             status = new byte[initialCapacity];
3744             entries = new Object[initialCapacity];
3745             deps = new HandleList[initialCapacity];
3746         }
3747 
3748         /**
3749          * Assigns next available handle to given object, and returns assigned
3750          * handle.  Once object has been completely deserialized (and all
3751          * dependencies on other objects identified), the handle should be
3752          * "closed" by passing it to finish().
3753          */
3754         int assign(Object obj) {
3755             if (size >= entries.length) {
3756                 grow();
3757             }
3758             status[size] = STATUS_UNKNOWN;
3759             entries[size] = obj;
3760             return size++;
3761         }
3762 
3763         /**
3764          * Registers a dependency (in exception status) of one handle on
3765          * another.  The dependent handle must be "open" (i.e., assigned, but
3766          * not finished yet).  No action is taken if either dependent or target
3767          * handle is NULL_HANDLE. Additionally, no action is taken if the
3768          * dependent and target are the same.
3769          */
3770         void markDependency(int dependent, int target) {
3771             if (dependent == target || dependent == NULL_HANDLE || target == NULL_HANDLE) {
3772                 return;
3773             }
3774             switch (status[dependent]) {
3775 
3776                 case STATUS_UNKNOWN:
3777                     switch (status[target]) {
3778                         case STATUS_OK:
3779                             // ignore dependencies on objs with no exception
3780                             break;
3781 
3782                         case STATUS_EXCEPTION:
3783                             // eagerly propagate exception
3784                             markException(dependent,
3785                                 (ClassNotFoundException) entries[target]);
3786                             break;
3787 
3788                         case STATUS_UNKNOWN:
3789                             // add to dependency list of target
3790                             if (deps[target] == null) {
3791                                 deps[target] = new HandleList();
3792                             }
3793                             deps[target].add(dependent);
3794 
3795                             // remember lowest unresolved target seen
3796                             if (lowDep < 0 || lowDep > target) {
3797                                 lowDep = target;
3798                             }
3799                             break;
3800 
3801                         default:
3802                             throw new InternalError();
3803                     }
3804                     break;
3805 
3806                 case STATUS_EXCEPTION:
3807                     break;
3808 
3809                 default:
3810                     throw new InternalError();
3811             }
3812         }
3813 
3814         /**
3815          * Associates a ClassNotFoundException (if one not already associated)
3816          * with the currently active handle and propagates it to other
3817          * referencing objects as appropriate.  The specified handle must be
3818          * "open" (i.e., assigned, but not finished yet).
3819          */
3820         void markException(int handle, ClassNotFoundException ex) {
3821             switch (status[handle]) {
3822                 case STATUS_UNKNOWN:
3823                     status[handle] = STATUS_EXCEPTION;
3824                     entries[handle] = ex;
3825 
3826                     // propagate exception to dependents
3827                     HandleList dlist = deps[handle];
3828                     if (dlist != null) {
3829                         int ndeps = dlist.size();
3830                         for (int i = 0; i < ndeps; i++) {
3831                             markException(dlist.get(i), ex);
3832                         }
3833                         deps[handle] = null;
3834                     }
3835                     break;
3836 
3837                 case STATUS_EXCEPTION:
3838                     break;
3839 
3840                 default:
3841                     throw new InternalError();
3842             }
3843         }
3844 
3845         /**
3846          * Marks given handle as finished, meaning that no new dependencies
3847          * will be marked for handle.  Calls to the assign and finish methods
3848          * must occur in LIFO order.
3849          */
3850         void finish(int handle) {
3851             int end;
3852             if (lowDep < 0) {
3853                 // no pending unknowns, only resolve current handle
3854                 end = handle + 1;
3855             } else if (lowDep >= handle) {
3856                 // pending unknowns now clearable, resolve all upward handles
3857                 end = size;
3858                 lowDep = -1;
3859             } else {
3860                 // unresolved backrefs present, can't resolve anything yet
3861                 return;
3862             }
3863 
3864             // change STATUS_UNKNOWN -> STATUS_OK in selected span of handles
3865             for (int i = handle; i < end; i++) {
3866                 switch (status[i]) {
3867                     case STATUS_UNKNOWN:
3868                         status[i] = STATUS_OK;
3869                         deps[i] = null;
3870                         break;
3871 
3872                     case STATUS_OK:
3873                     case STATUS_EXCEPTION:
3874                         break;
3875 
3876                     default:
3877                         throw new InternalError();
3878                 }
3879             }
3880         }
3881 
3882         /**
3883          * Assigns a new object to the given handle.  The object previously
3884          * associated with the handle is forgotten.  This method has no effect
3885          * if the given handle already has an exception associated with it.
3886          * This method may be called at any time after the handle is assigned.
3887          */
3888         void setObject(int handle, Object obj) {
3889             switch (status[handle]) {
3890                 case STATUS_UNKNOWN:
3891                 case STATUS_OK:
3892                     entries[handle] = obj;
3893                     break;
3894 
3895                 case STATUS_EXCEPTION:
3896                     break;
3897 
3898                 default:
3899                     throw new InternalError();
3900             }
3901         }
3902 
3903         /**
3904          * Looks up and returns object associated with the given handle.
3905          * Returns null if the given handle is NULL_HANDLE, or if it has an
3906          * associated ClassNotFoundException.
3907          */
3908         Object lookupObject(int handle) {
3909             return (handle != NULL_HANDLE &&
3910                     status[handle] != STATUS_EXCEPTION) ?
3911                 entries[handle] : null;
3912         }
3913 
3914         /**
3915          * Looks up and returns ClassNotFoundException associated with the
3916          * given handle.  Returns null if the given handle is NULL_HANDLE, or
3917          * if there is no ClassNotFoundException associated with the handle.
3918          */
3919         ClassNotFoundException lookupException(int handle) {
3920             return (handle != NULL_HANDLE &&
3921                     status[handle] == STATUS_EXCEPTION) ?
3922                 (ClassNotFoundException) entries[handle] : null;
3923         }
3924 
3925         /**
3926          * Resets table to its initial state.
3927          */
3928         void clear() {
3929             Arrays.fill(status, 0, size, (byte) 0);
3930             Arrays.fill(entries, 0, size, null);
3931             Arrays.fill(deps, 0, size, null);
3932             lowDep = -1;
3933             size = 0;
3934         }
3935 
3936         /**
3937          * Returns number of handles registered in table.
3938          */
3939         int size() {
3940             return size;
3941         }
3942 
3943         /**
3944          * Expands capacity of internal arrays.
3945          */
3946         private void grow() {
3947             int newCapacity = (entries.length << 1) + 1;
3948 
3949             byte[] newStatus = new byte[newCapacity];
3950             Object[] newEntries = new Object[newCapacity];
3951             HandleList[] newDeps = new HandleList[newCapacity];
3952 
3953             System.arraycopy(status, 0, newStatus, 0, size);
3954             System.arraycopy(entries, 0, newEntries, 0, size);
3955             System.arraycopy(deps, 0, newDeps, 0, size);
3956 
3957             status = newStatus;
3958             entries = newEntries;
3959             deps = newDeps;
3960         }
3961 
3962         /**
3963          * Simple growable list of (integer) handles.
3964          */
3965         private static class HandleList {
3966             private int[] list = new int[4];
3967             private int size = 0;
3968 
3969             public HandleList() {
3970             }
3971 
3972             public void add(int handle) {
3973                 if (size >= list.length) {
3974                     int[] newList = new int[list.length << 1];
3975                     System.arraycopy(list, 0, newList, 0, list.length);
3976                     list = newList;
3977                 }
3978                 list[size++] = handle;
3979             }
3980 
3981             public int get(int index) {
3982                 if (index >= size) {
3983                     throw new ArrayIndexOutOfBoundsException();
3984                 }
3985                 return list[index];
3986             }
3987 
3988             public int size() {
3989                 return size;
3990             }
3991         }
3992     }
3993 
3994     /**
3995      * Method for cloning arrays in case of using unsharing reading
3996      */
3997     private static Object cloneArray(Object array) {
3998         if (array instanceof Object[]) {
3999             return ((Object[]) array).clone();
4000         } else if (array instanceof boolean[]) {
4001             return ((boolean[]) array).clone();
4002         } else if (array instanceof byte[]) {
4003             return ((byte[]) array).clone();
4004         } else if (array instanceof char[]) {
4005             return ((char[]) array).clone();
4006         } else if (array instanceof double[]) {
4007             return ((double[]) array).clone();
4008         } else if (array instanceof float[]) {
4009             return ((float[]) array).clone();
4010         } else if (array instanceof int[]) {
4011             return ((int[]) array).clone();
4012         } else if (array instanceof long[]) {
4013             return ((long[]) array).clone();
4014         } else if (array instanceof short[]) {
4015             return ((short[]) array).clone();
4016         } else {
4017             throw new AssertionError();
4018         }
4019     }
4020 
4021     static {
4022         SharedSecrets.setJavaObjectInputStreamAccess(ObjectInputStream::checkArray);
4023     }
4024 
4025 }