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