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