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