1 /*
   2  * Copyright (c) 1996, 2021, 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.security.AccessController;
  31 import java.security.PrivilegedAction;
  32 import java.util.ArrayList;
  33 import java.util.Arrays;
  34 import java.util.List;
  35 import java.util.StringJoiner;
  36 import java.util.concurrent.ConcurrentHashMap;
  37 import java.util.concurrent.ConcurrentMap;
  38 import static java.io.ObjectStreamClass.processQueue;
  39 import sun.reflect.misc.ReflectUtil;
  40 
  41 /**
  42  * An ObjectOutputStream writes primitive data types and graphs of Java objects
  43  * to an OutputStream.  The objects can be read (reconstituted) using an
  44  * ObjectInputStream.  Persistent storage of objects can be accomplished by
  45  * using a file for the stream.  If the stream is a network socket stream, the
  46  * objects can be reconstituted on another host or in another process.
  47  *
  48  * <p>Only objects that support the java.io.Serializable interface can be
  49  * written to streams.  The class of each serializable object is encoded
  50  * including the class name and signature of the class, the values of the
  51  * object's fields and arrays, and the closure of any other objects referenced
  52  * from the initial objects.
  53  *
  54  * <p>The method writeObject is used to write an object to the stream.  Any
  55  * object, including Strings and arrays, is written with writeObject. Multiple
  56  * objects or primitives can be written to the stream.  The objects must be
  57  * read back from the corresponding ObjectInputstream with the same types and
  58  * in the same order as they were written.
  59  *
  60  * <p>Primitive data types can also be written to the stream using the
  61  * appropriate methods from DataOutput. Strings can also be written using the
  62  * writeUTF method.
  63  *
  64  * <p>The default serialization mechanism for an object writes the class of the
  65  * object, the class signature, and the values of all non-transient and
  66  * non-static fields.  References to other objects (except in transient or
  67  * static fields) cause those objects to be written also. Multiple references
  68  * to a single object are encoded using a reference sharing mechanism so that
  69  * graphs of objects can be restored to the same shape as when the original was
  70  * written.
  71  *
  72  * <p>For example to write an object that can be read by the example in
  73  * ObjectInputStream:
  74  * <br>
  75  * <pre>
  76  *      FileOutputStream fos = new FileOutputStream("t.tmp");
  77  *      ObjectOutputStream oos = new ObjectOutputStream(fos);
  78  *
  79  *      oos.writeInt(12345);
  80  *      oos.writeObject("Today");
  81  *      oos.writeObject(new Date());
  82  *
  83  *      oos.close();
  84  * </pre>
  85  *
  86  * <p>Classes that require special handling during the serialization and
  87  * deserialization process must implement special methods with these exact
  88  * signatures:
  89  * <br>
  90  * <pre>
  91  * private void readObject(java.io.ObjectInputStream stream)
  92  *     throws IOException, ClassNotFoundException;
  93  * private void writeObject(java.io.ObjectOutputStream stream)
  94  *     throws IOException
  95  * private void readObjectNoData()
  96  *     throws ObjectStreamException;
  97  * </pre>
  98  *
  99  * <p>The writeObject method is responsible for writing the state of the object
 100  * for its particular class so that the corresponding readObject method can
 101  * restore it.  The method does not need to concern itself with the state
 102  * belonging to the object's superclasses or subclasses.  State is saved by
 103  * writing the individual fields to the ObjectOutputStream using the
 104  * writeObject method or by using the methods for primitive data types
 105  * supported by DataOutput.
 106  *
 107  * <p>Serialization does not write out the fields of any object that does not
 108  * implement the java.io.Serializable interface.  Subclasses of Objects that
 109  * are not serializable can be serializable. In this case the non-serializable
 110  * class must have a no-arg constructor to allow its fields to be initialized.
 111  * In this case it is the responsibility of the subclass to save and restore
 112  * the state of the non-serializable class. It is frequently the case that the
 113  * fields of that class are accessible (public, package, or protected) or that
 114  * there are get and set methods that can be used to restore the state.
 115  *
 116  * <p>Serialization of an object can be prevented by implementing writeObject
 117  * and readObject methods that throw the NotSerializableException.  The
 118  * exception will be caught by the ObjectOutputStream and abort the
 119  * serialization process.
 120  *
 121  * <p>Implementing the Externalizable interface allows the object to assume
 122  * complete control over the contents and format of the object's serialized
 123  * form.  The methods of the Externalizable interface, writeExternal and
 124  * readExternal, are called to save and restore the objects state.  When
 125  * implemented by a class they can write and read their own state using all of
 126  * the methods of ObjectOutput and ObjectInput.  It is the responsibility of
 127  * the objects to handle any versioning that occurs.
 128  *
 129  * <p>Enum constants are serialized differently than ordinary serializable or
 130  * externalizable objects.  The serialized form of an enum constant consists
 131  * solely of its name; field values of the constant are not transmitted.  To
 132  * serialize an enum constant, ObjectOutputStream writes the string returned by
 133  * the constant's name method.  Like other serializable or externalizable
 134  * objects, enum constants can function as the targets of back references
 135  * appearing subsequently in the serialization stream.  The process by which
 136  * enum constants are serialized cannot be customized; any class-specific
 137  * writeObject and writeReplace methods defined by enum types are ignored
 138  * during serialization.  Similarly, any serialPersistentFields or
 139  * serialVersionUID field declarations are also ignored--all enum types have a
 140  * fixed serialVersionUID of 0L.
 141  *
 142  * <p>Primitive data, excluding serializable fields and externalizable data, is
 143  * written to the ObjectOutputStream in block-data records. A block data record
 144  * is composed of a header and data. The block data header consists of a marker
 145  * and the number of bytes to follow the header.  Consecutive primitive data
 146  * writes are merged into one block-data record.  The blocking factor used for
 147  * a block-data record will be 1024 bytes.  Each block-data record will be
 148  * filled up to 1024 bytes, or be written whenever there is a termination of
 149  * block-data mode.  Calls to the ObjectOutputStream methods writeObject,
 150  * defaultWriteObject and writeFields initially terminate any existing
 151  * block-data record.
 152  *
 153  * <p>Records are serialized differently than ordinary serializable or externalizable
 154  * objects, see <a href="ObjectInputStream.html#record-serialization">record serialization</a>.
 155  *
 156  * @author      Mike Warres
 157  * @author      Roger Riggs
 158  * @see java.io.DataOutput
 159  * @see java.io.ObjectInputStream
 160  * @see java.io.Serializable
 161  * @see java.io.Externalizable
 162  * @see <a href="{@docRoot}/../specs/serialization/output.html">
 163  *      <cite>Java Object Serialization Specification,</cite> Section 2, "Object Output Classes"</a>
 164  * @since       1.1
 165  */
 166 public class ObjectOutputStream
 167     extends OutputStream implements ObjectOutput, ObjectStreamConstants
 168 {
 169 
 170     private static class Caches {
 171         /** cache of subclass security audit results */
 172         static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
 173             new ConcurrentHashMap<>();
 174 
 175         /** queue for WeakReferences to audited subclasses */
 176         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
 177             new ReferenceQueue<>();
 178     }
 179 
 180     /** filter stream for handling block data conversion */
 181     private final BlockDataOutputStream bout;
 182     /** obj -> wire handle map */
 183     private final HandleTable handles;
 184     /** obj -> replacement obj map */
 185     private final ReplaceTable subs;
 186     /** stream protocol version */
 187     private int protocol = PROTOCOL_VERSION_2;
 188     /** recursion depth */
 189     private int depth;
 190 
 191     /** buffer for writing primitive field values */
 192     private byte[] primVals;
 193 
 194     /** if true, invoke writeObjectOverride() instead of writeObject() */
 195     private final boolean enableOverride;
 196     /** if true, invoke replaceObject() */
 197     private boolean enableReplace;
 198 
 199     // values below valid only during upcalls to writeObject()/writeExternal()
 200     /**
 201      * Context during upcalls to class-defined writeObject methods; holds
 202      * object currently being serialized and descriptor for current class.
 203      * Null when not during writeObject upcall.
 204      */
 205     private SerialCallbackContext curContext;
 206     /** current PutField object */
 207     private PutFieldImpl curPut;
 208 
 209     /** custom storage for debug trace info */
 210     private final DebugTraceInfoStack debugInfoStack;
 211 
 212     /**
 213      * value of "sun.io.serialization.extendedDebugInfo" property,
 214      * as true or false for extended information about exception's place
 215      */
 216     @SuppressWarnings("removal")
 217     private static final boolean extendedDebugInfo =
 218         java.security.AccessController.doPrivileged(
 219             new sun.security.action.GetBooleanAction(
 220                 "sun.io.serialization.extendedDebugInfo")).booleanValue();
 221 
 222     /**
 223      * Creates an ObjectOutputStream that writes to the specified OutputStream.
 224      * This constructor writes the serialization stream header to the
 225      * underlying stream; callers may wish to flush the stream immediately to
 226      * ensure that constructors for receiving ObjectInputStreams will not block
 227      * when reading the header.
 228      *
 229      * <p>If a security manager is installed, this constructor will check for
 230      * the "enableSubclassImplementation" SerializablePermission when invoked
 231      * directly or indirectly by the constructor of a subclass which overrides
 232      * the ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared
 233      * methods.
 234      *
 235      * @param   out output stream to write to
 236      * @throws  IOException if an I/O error occurs while writing stream header
 237      * @throws  SecurityException if untrusted subclass illegally overrides
 238      *          security-sensitive methods
 239      * @throws  NullPointerException if {@code out} is {@code null}
 240      * @since   1.4
 241      * @see     ObjectOutputStream#ObjectOutputStream()
 242      * @see     ObjectOutputStream#putFields()
 243      * @see     ObjectInputStream#ObjectInputStream(InputStream)
 244      */
 245     public ObjectOutputStream(OutputStream out) throws IOException {
 246         verifySubclass();
 247         bout = new BlockDataOutputStream(out);
 248         handles = new HandleTable(10, (float) 3.00);
 249         subs = new ReplaceTable(10, (float) 3.00);
 250         enableOverride = false;
 251         writeStreamHeader();
 252         bout.setBlockDataMode(true);
 253         if (extendedDebugInfo) {
 254             debugInfoStack = new DebugTraceInfoStack();
 255         } else {
 256             debugInfoStack = null;
 257         }
 258     }
 259 
 260     /**
 261      * Provide a way for subclasses that are completely reimplementing
 262      * ObjectOutputStream to not have to allocate private data just used by
 263      * this implementation of ObjectOutputStream.
 264      *
 265      * <p>If there is a security manager installed, this method first calls the
 266      * security manager's {@code checkPermission} method with a
 267      * {@code SerializablePermission("enableSubclassImplementation")}
 268      * permission to ensure it's ok to enable subclassing.
 269      *
 270      * @throws  SecurityException if a security manager exists and its
 271      *          {@code checkPermission} method denies enabling
 272      *          subclassing.
 273      * @throws  IOException if an I/O error occurs while creating this stream
 274      * @see SecurityManager#checkPermission
 275      * @see java.io.SerializablePermission
 276      */
 277     protected ObjectOutputStream() throws IOException, SecurityException {
 278         @SuppressWarnings("removal")
 279         SecurityManager sm = System.getSecurityManager();
 280         if (sm != null) {
 281             sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
 282         }
 283         bout = null;
 284         handles = null;
 285         subs = null;
 286         enableOverride = true;
 287         debugInfoStack = null;
 288     }
 289 
 290     /**
 291      * Specify stream protocol version to use when writing the stream.
 292      *
 293      * <p>This routine provides a hook to enable the current version of
 294      * Serialization to write in a format that is backwards compatible to a
 295      * previous version of the stream format.
 296      *
 297      * <p>Every effort will be made to avoid introducing additional
 298      * backwards incompatibilities; however, sometimes there is no
 299      * other alternative.
 300      *
 301      * @param   version use ProtocolVersion from java.io.ObjectStreamConstants.
 302      * @throws  IllegalStateException if called after any objects
 303      *          have been serialized.
 304      * @throws  IllegalArgumentException if invalid version is passed in.
 305      * @throws  IOException if I/O errors occur
 306      * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
 307      * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_2
 308      * @since   1.2
 309      */
 310     public void useProtocolVersion(int version) throws IOException {
 311         if (handles.size() != 0) {
 312             // REMIND: implement better check for pristine stream?
 313             throw new IllegalStateException("stream non-empty");
 314         }
 315         switch (version) {
 316             case PROTOCOL_VERSION_1:
 317             case PROTOCOL_VERSION_2:
 318                 protocol = version;
 319                 break;
 320 
 321             default:
 322                 throw new IllegalArgumentException(
 323                     "unknown version: " + version);
 324         }
 325     }
 326 
 327     /**
 328      * Write the specified object to the ObjectOutputStream.  The class of the
 329      * object, the signature of the class, and the values of the non-transient
 330      * and non-static fields of the class and all of its supertypes are
 331      * written.  Default serialization for a class can be overridden using the
 332      * writeObject and the readObject methods.  Objects referenced by this
 333      * object are written transitively so that a complete equivalent graph of
 334      * objects can be reconstructed by an ObjectInputStream.
 335      *
 336      * <p>Exceptions are thrown for problems with the OutputStream and for
 337      * classes that should not be serialized.  All exceptions are fatal to the
 338      * OutputStream, which is left in an indeterminate state, and it is up to
 339      * the caller to ignore or recover the stream state.
 340      *
 341      * @throws  InvalidClassException Something is wrong with a class used by
 342      *          serialization.
 343      * @throws  NotSerializableException Some object to be serialized does not
 344      *          implement the java.io.Serializable interface.
 345      * @throws  IOException Any exception thrown by the underlying
 346      *          OutputStream.
 347      */
 348     public final void writeObject(Object obj) throws IOException {
 349         if (enableOverride) {
 350             writeObjectOverride(obj);
 351             return;
 352         }
 353         try {
 354             writeObject0(obj, false);
 355         } catch (IOException ex) {
 356             if (depth == 0) {
 357                 writeFatalException(ex);
 358             }
 359             throw ex;
 360         }
 361     }
 362 
 363     /**
 364      * Method used by subclasses to override the default writeObject method.
 365      * This method is called by trusted subclasses of ObjectOutputStream that
 366      * constructed ObjectOutputStream using the protected no-arg constructor.
 367      * The subclass is expected to provide an override method with the modifier
 368      * "final".
 369      *
 370      * @param   obj object to be written to the underlying stream
 371      * @throws  IOException if there are I/O errors while writing to the
 372      *          underlying stream
 373      * @see #ObjectOutputStream()
 374      * @see #writeObject(Object)
 375      * @since 1.2
 376      */
 377     protected void writeObjectOverride(Object obj) throws IOException {
 378     }
 379 
 380     /**
 381      * Writes an "unshared" object to the ObjectOutputStream.  This method is
 382      * identical to writeObject, except that it always writes the given object
 383      * as a new, unique object in the stream (as opposed to a back-reference
 384      * pointing to a previously serialized instance).  Specifically:
 385      * <ul>
 386      *   <li>An object written via writeUnshared is always serialized in the
 387      *       same manner as a newly appearing object (an object that has not
 388      *       been written to the stream yet), regardless of whether or not the
 389      *       object has been written previously.
 390      *
 391      *   <li>If writeObject is used to write an object that has been previously
 392      *       written with writeUnshared, the previous writeUnshared operation
 393      *       is treated as if it were a write of a separate object.  In other
 394      *       words, ObjectOutputStream will never generate back-references to
 395      *       object data written by calls to writeUnshared.
 396      * </ul>
 397      * While writing an object via writeUnshared does not in itself guarantee a
 398      * unique reference to the object when it is deserialized, it allows a
 399      * single object to be defined multiple times in a stream, so that multiple
 400      * calls to readUnshared by the receiver will not conflict.  Note that the
 401      * rules described above only apply to the base-level object written with
 402      * writeUnshared, and not to any transitively referenced sub-objects in the
 403      * object graph to be serialized.
 404      *
 405      * <p>ObjectOutputStream subclasses which override this method can only be
 406      * constructed in security contexts possessing the
 407      * "enableSubclassImplementation" SerializablePermission; any attempt to
 408      * instantiate such a subclass without this permission will cause a
 409      * SecurityException to be thrown.
 410      *
 411      * @param   obj object to write to stream
 412      * @throws  NotSerializableException if an object in the graph to be
 413      *          serialized does not implement the Serializable interface
 414      * @throws  InvalidClassException if a problem exists with the class of an
 415      *          object to be serialized
 416      * @throws  IOException if an I/O error occurs during serialization
 417      * @since 1.4
 418      */
 419     public void writeUnshared(Object obj) throws IOException {
 420         try {
 421             writeObject0(obj, true);
 422         } catch (IOException ex) {
 423             if (depth == 0) {
 424                 writeFatalException(ex);
 425             }
 426             throw ex;
 427         }
 428     }
 429 
 430     /**
 431      * Write the non-static and non-transient fields of the current class to
 432      * this stream.  This may only be called from the writeObject method of the
 433      * class being serialized. It will throw the NotActiveException if it is
 434      * called otherwise.
 435      *
 436      * @throws  IOException if I/O errors occur while writing to the underlying
 437      *          {@code OutputStream}
 438      */
 439     public void defaultWriteObject() throws IOException {
 440         SerialCallbackContext ctx = curContext;
 441         if (ctx == null) {
 442             throw new NotActiveException("not in call to writeObject");
 443         }
 444         Object curObj = ctx.getObj();
 445         ObjectStreamClass curDesc = ctx.getDesc();
 446         bout.setBlockDataMode(false);
 447         defaultWriteFields(curObj, curDesc);
 448         bout.setBlockDataMode(true);
 449     }
 450 
 451     /**
 452      * Retrieve the object used to buffer persistent fields to be written to
 453      * the stream.  The fields will be written to the stream when writeFields
 454      * method is called.
 455      *
 456      * @return  an instance of the class Putfield that holds the serializable
 457      *          fields
 458      * @throws  IOException if I/O errors occur
 459      * @since 1.2
 460      */
 461     public ObjectOutputStream.PutField putFields() throws IOException {
 462         if (curPut == null) {
 463             SerialCallbackContext ctx = curContext;
 464             if (ctx == null) {
 465                 throw new NotActiveException("not in call to writeObject");
 466             }
 467             ctx.checkAndSetUsed();
 468             ObjectStreamClass curDesc = ctx.getDesc();
 469             curPut = new PutFieldImpl(curDesc);
 470         }
 471         return curPut;
 472     }
 473 
 474     /**
 475      * Write the buffered fields to the stream.
 476      *
 477      * @throws  IOException if I/O errors occur while writing to the underlying
 478      *          stream
 479      * @throws  NotActiveException Called when a classes writeObject method was
 480      *          not called to write the state of the object.
 481      * @since 1.2
 482      */
 483     public void writeFields() throws IOException {
 484         if (curPut == null) {
 485             throw new NotActiveException("no current PutField object");
 486         }
 487         bout.setBlockDataMode(false);
 488         curPut.writeFields();
 489         bout.setBlockDataMode(true);
 490     }
 491 
 492     /**
 493      * Reset will disregard the state of any objects already written to the
 494      * stream.  The state is reset to be the same as a new ObjectOutputStream.
 495      * The current point in the stream is marked as reset so the corresponding
 496      * ObjectInputStream will be reset at the same point.  Objects previously
 497      * written to the stream will not be referred to as already being in the
 498      * stream.  They will be written to the stream again.
 499      *
 500      * @throws  IOException if reset() is invoked while serializing an object.
 501      */
 502     public void reset() throws IOException {
 503         if (depth != 0) {
 504             throw new IOException("stream active");
 505         }
 506         bout.setBlockDataMode(false);
 507         bout.writeByte(TC_RESET);
 508         clear();
 509         bout.setBlockDataMode(true);
 510     }
 511 
 512     /**
 513      * Subclasses may implement this method to allow class data to be stored in
 514      * the stream. By default this method does nothing.  The corresponding
 515      * method in ObjectInputStream is resolveClass.  This method is called
 516      * exactly once for each unique class in the stream.  The class name and
 517      * signature will have already been written to the stream.  This method may
 518      * make free use of the ObjectOutputStream to save any representation of
 519      * the class it deems suitable (for example, the bytes of the class file).
 520      * The resolveClass method in the corresponding subclass of
 521      * ObjectInputStream must read and use any data or objects written by
 522      * annotateClass.
 523      *
 524      * @param   cl the class to annotate custom data for
 525      * @throws  IOException Any exception thrown by the underlying
 526      *          OutputStream.
 527      */
 528     protected void annotateClass(Class<?> cl) throws IOException {
 529     }
 530 
 531     /**
 532      * Subclasses may implement this method to store custom data in the stream
 533      * along with descriptors for dynamic proxy classes.
 534      *
 535      * <p>This method is called exactly once for each unique proxy class
 536      * descriptor in the stream.  The default implementation of this method in
 537      * {@code ObjectOutputStream} does nothing.
 538      *
 539      * <p>The corresponding method in {@code ObjectInputStream} is
 540      * {@code resolveProxyClass}.  For a given subclass of
 541      * {@code ObjectOutputStream} that overrides this method, the
 542      * {@code resolveProxyClass} method in the corresponding subclass of
 543      * {@code ObjectInputStream} must read any data or objects written by
 544      * {@code annotateProxyClass}.
 545      *
 546      * @param   cl the proxy class to annotate custom data for
 547      * @throws  IOException any exception thrown by the underlying
 548      *          {@code OutputStream}
 549      * @see ObjectInputStream#resolveProxyClass(String[])
 550      * @since   1.3
 551      */
 552     protected void annotateProxyClass(Class<?> cl) throws IOException {
 553     }
 554 
 555     /**
 556      * This method will allow trusted subclasses of ObjectOutputStream to
 557      * substitute one object for another during serialization. Replacing
 558      * objects is disabled until enableReplaceObject is called. The
 559      * enableReplaceObject method checks that the stream requesting to do
 560      * replacement can be trusted.  The first occurrence of each object written
 561      * into the serialization stream is passed to replaceObject.  Subsequent
 562      * references to the object are replaced by the object returned by the
 563      * original call to replaceObject.  To ensure that the private state of
 564      * objects is not unintentionally exposed, only trusted streams may use
 565      * replaceObject.
 566      *
 567      * <p>The ObjectOutputStream.writeObject method takes a parameter of type
 568      * Object (as opposed to type Serializable) to allow for cases where
 569      * non-serializable objects are replaced by serializable ones.
 570      *
 571      * <p>When a subclass is replacing objects it must ensure that either a
 572      * complementary substitution must be made during deserialization or that
 573      * the substituted object is compatible with every field where the
 574      * reference will be stored.  Objects whose type is not a subclass of the
 575      * type of the field or array element abort the serialization by raising an
 576      * exception and the object is not be stored.
 577      *
 578      * <p>This method is called only once when each object is first
 579      * encountered.  All subsequent references to the object will be redirected
 580      * to the new object. This method should return the object to be
 581      * substituted or the original object.
 582      *
 583      * <p>Null can be returned as the object to be substituted, but may cause
 584      * NullReferenceException in classes that contain references to the
 585      * original object since they may be expecting an object instead of
 586      * null.
 587      *
 588      * @param   obj the object to be replaced
 589      * @return  the alternate object that replaced the specified one
 590      * @throws  IOException Any exception thrown by the underlying
 591      *          OutputStream.
 592      */
 593     protected Object replaceObject(Object obj) throws IOException {
 594         return obj;
 595     }
 596 
 597     /**
 598      * Enables the stream to do replacement of objects written to the stream.  When
 599      * enabled, the {@link #replaceObject} method is called for every object being
 600      * serialized.
 601      *
 602      * <p>If object replacement is currently not enabled, and
 603      * {@code enable} is true, and there is a security manager installed,
 604      * this method first calls the security manager's
 605      * {@code checkPermission} method with the
 606      * {@code SerializablePermission("enableSubstitution")} permission to
 607      * ensure that the caller is permitted to enable the stream to do replacement
 608      * of objects written to the stream.
 609      *
 610      * @param   enable true for enabling use of {@code replaceObject} for
 611      *          every object being serialized
 612      * @return  the previous setting before this method was invoked
 613      * @throws  SecurityException if a security manager exists and its
 614      *          {@code checkPermission} method denies enabling the stream
 615      *          to do replacement of objects written to the stream.
 616      * @see SecurityManager#checkPermission
 617      * @see java.io.SerializablePermission
 618      */
 619     protected boolean enableReplaceObject(boolean enable)
 620         throws SecurityException
 621     {
 622         if (enable == enableReplace) {
 623             return enable;
 624         }
 625         if (enable) {
 626             @SuppressWarnings("removal")
 627             SecurityManager sm = System.getSecurityManager();
 628             if (sm != null) {
 629                 sm.checkPermission(SUBSTITUTION_PERMISSION);
 630             }
 631         }
 632         enableReplace = enable;
 633         return !enableReplace;
 634     }
 635 
 636     /**
 637      * The writeStreamHeader method is provided so subclasses can append or
 638      * prepend their own header to the stream.  It writes the magic number and
 639      * version to the stream.
 640      *
 641      * @throws  IOException if I/O errors occur while writing to the underlying
 642      *          stream
 643      */
 644     protected void writeStreamHeader() throws IOException {
 645         bout.writeShort(STREAM_MAGIC);
 646         bout.writeShort(STREAM_VERSION);
 647     }
 648 
 649     /**
 650      * Write the specified class descriptor to the ObjectOutputStream.  Class
 651      * descriptors are used to identify the classes of objects written to the
 652      * stream.  Subclasses of ObjectOutputStream may override this method to
 653      * customize the way in which class descriptors are written to the
 654      * serialization stream.  The corresponding method in ObjectInputStream,
 655      * {@code readClassDescriptor}, should then be overridden to
 656      * reconstitute the class descriptor from its custom stream representation.
 657      * By default, this method writes class descriptors according to the format
 658      * defined in the Object Serialization specification.
 659      *
 660      * <p>Note that this method will only be called if the ObjectOutputStream
 661      * is not using the old serialization stream format (set by calling
 662      * ObjectOutputStream's {@code useProtocolVersion} method).  If this
 663      * serialization stream is using the old format
 664      * ({@code PROTOCOL_VERSION_1}), the class descriptor will be written
 665      * internally in a manner that cannot be overridden or customized.
 666      *
 667      * @param   desc class descriptor to write to the stream
 668      * @throws  IOException If an I/O error has occurred.
 669      * @see java.io.ObjectInputStream#readClassDescriptor()
 670      * @see #useProtocolVersion(int)
 671      * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1
 672      * @since 1.3
 673      */
 674     protected void writeClassDescriptor(ObjectStreamClass desc)
 675         throws IOException
 676     {
 677         desc.writeNonProxy(this);
 678     }
 679 
 680     /**
 681      * Writes a byte. This method will block until the byte is actually
 682      * written.
 683      *
 684      * @param   val the byte to be written to the stream
 685      * @throws  IOException If an I/O error has occurred.
 686      */
 687     public void write(int val) throws IOException {
 688         bout.write(val);
 689     }
 690 
 691     /**
 692      * Writes an array of bytes. This method will block until the bytes are
 693      * actually written.
 694      *
 695      * @param   buf the data to be written
 696      * @throws  IOException If an I/O error has occurred.
 697      */
 698     public void write(byte[] buf) throws IOException {
 699         bout.write(buf, 0, buf.length, false);
 700     }
 701 
 702     /**
 703      * Writes a sub array of bytes.
 704      *
 705      * @param   buf the data to be written
 706      * @param   off the start offset in the data
 707      * @param   len the number of bytes that are written
 708      * @throws  IOException If an I/O error has occurred.
 709      */
 710     public void write(byte[] buf, int off, int len) throws IOException {
 711         if (buf == null) {
 712             throw new NullPointerException();
 713         }
 714         int endoff = off + len;
 715         if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
 716             throw new IndexOutOfBoundsException();
 717         }
 718         bout.write(buf, off, len, false);
 719     }
 720 
 721     /**
 722      * Flushes the stream. This will write any buffered output bytes and flush
 723      * through to the underlying stream.
 724      *
 725      * @throws  IOException If an I/O error has occurred.
 726      */
 727     public void flush() throws IOException {
 728         bout.flush();
 729     }
 730 
 731     /**
 732      * Drain any buffered data in ObjectOutputStream.  Similar to flush but
 733      * does not propagate the flush to the underlying stream.
 734      *
 735      * @throws  IOException if I/O errors occur while writing to the underlying
 736      *          stream
 737      */
 738     protected void drain() throws IOException {
 739         bout.drain();
 740     }
 741 
 742     /**
 743      * Closes the stream. This method must be called to release any resources
 744      * associated with the stream.
 745      *
 746      * @throws  IOException If an I/O error has occurred.
 747      */
 748     public void close() throws IOException {
 749         flush();
 750         clear();
 751         bout.close();
 752     }
 753 
 754     /**
 755      * Writes a boolean.
 756      *
 757      * @param   val the boolean to be written
 758      * @throws  IOException if I/O errors occur while writing to the underlying
 759      *          stream
 760      */
 761     public void writeBoolean(boolean val) throws IOException {
 762         bout.writeBoolean(val);
 763     }
 764 
 765     /**
 766      * Writes an 8 bit byte.
 767      *
 768      * @param   val the byte value to be written
 769      * @throws  IOException if I/O errors occur while writing to the underlying
 770      *          stream
 771      */
 772     public void writeByte(int val) throws IOException  {
 773         bout.writeByte(val);
 774     }
 775 
 776     /**
 777      * Writes a 16 bit short.
 778      *
 779      * @param   val the short value to be written
 780      * @throws  IOException if I/O errors occur while writing to the underlying
 781      *          stream
 782      */
 783     public void writeShort(int val)  throws IOException {
 784         bout.writeShort(val);
 785     }
 786 
 787     /**
 788      * Writes a 16 bit char.
 789      *
 790      * @param   val the char value to be written
 791      * @throws  IOException if I/O errors occur while writing to the underlying
 792      *          stream
 793      */
 794     public void writeChar(int val)  throws IOException {
 795         bout.writeChar(val);
 796     }
 797 
 798     /**
 799      * Writes a 32 bit int.
 800      *
 801      * @param   val the integer value to be written
 802      * @throws  IOException if I/O errors occur while writing to the underlying
 803      *          stream
 804      */
 805     public void writeInt(int val)  throws IOException {
 806         bout.writeInt(val);
 807     }
 808 
 809     /**
 810      * Writes a 64 bit long.
 811      *
 812      * @param   val the long value to be written
 813      * @throws  IOException if I/O errors occur while writing to the underlying
 814      *          stream
 815      */
 816     public void writeLong(long val)  throws IOException {
 817         bout.writeLong(val);
 818     }
 819 
 820     /**
 821      * Writes a 32 bit float.
 822      *
 823      * @param   val the float value to be written
 824      * @throws  IOException if I/O errors occur while writing to the underlying
 825      *          stream
 826      */
 827     public void writeFloat(float val) throws IOException {
 828         bout.writeFloat(val);
 829     }
 830 
 831     /**
 832      * Writes a 64 bit double.
 833      *
 834      * @param   val the double value to be written
 835      * @throws  IOException if I/O errors occur while writing to the underlying
 836      *          stream
 837      */
 838     public void writeDouble(double val) throws IOException {
 839         bout.writeDouble(val);
 840     }
 841 
 842     /**
 843      * Writes a String as a sequence of bytes.
 844      *
 845      * @param   str the String of bytes to be written
 846      * @throws  IOException if I/O errors occur while writing to the underlying
 847      *          stream
 848      */
 849     public void writeBytes(String str) throws IOException {
 850         bout.writeBytes(str);
 851     }
 852 
 853     /**
 854      * Writes a String as a sequence of chars.
 855      *
 856      * @param   str the String of chars to be written
 857      * @throws  IOException if I/O errors occur while writing to the underlying
 858      *          stream
 859      */
 860     public void writeChars(String str) throws IOException {
 861         bout.writeChars(str);
 862     }
 863 
 864     /**
 865      * Primitive data write of this String in
 866      * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
 867      * format.  Note that there is a
 868      * significant difference between writing a String into the stream as
 869      * primitive data or as an Object. A String instance written by writeObject
 870      * is written into the stream as a String initially. Future writeObject()
 871      * calls write references to the string into the stream.
 872      *
 873      * @param   str the String to be written
 874      * @throws  IOException if I/O errors occur while writing to the underlying
 875      *          stream
 876      */
 877     public void writeUTF(String str) throws IOException {
 878         bout.writeUTF(str);
 879     }
 880 
 881     /**
 882      * Provide programmatic access to the persistent fields to be written
 883      * to ObjectOutput.
 884      *
 885      * @since 1.2
 886      */
 887     public abstract static class PutField {
 888         /**
 889          * Constructor for subclasses to call.
 890          */
 891         public PutField() {}
 892 
 893         /**
 894          * Put the value of the named boolean field into the persistent field.
 895          *
 896          * @param  name the name of the serializable field
 897          * @param  val the value to assign to the field
 898          * @throws IllegalArgumentException if {@code name} does not
 899          * match the name of a serializable field for the class whose fields
 900          * are being written, or if the type of the named field is not
 901          * {@code boolean}
 902          */
 903         public abstract void put(String name, boolean val);
 904 
 905         /**
 906          * Put the value of the named byte field into the persistent field.
 907          *
 908          * @param  name the name of the serializable field
 909          * @param  val the value to assign to the field
 910          * @throws IllegalArgumentException if {@code name} does not
 911          * match the name of a serializable field for the class whose fields
 912          * are being written, or if the type of the named field is not
 913          * {@code byte}
 914          */
 915         public abstract void put(String name, byte val);
 916 
 917         /**
 918          * Put the value of the named char field into the persistent field.
 919          *
 920          * @param  name the name of the serializable field
 921          * @param  val the value to assign to the field
 922          * @throws IllegalArgumentException if {@code name} does not
 923          * match the name of a serializable field for the class whose fields
 924          * are being written, or if the type of the named field is not
 925          * {@code char}
 926          */
 927         public abstract void put(String name, char val);
 928 
 929         /**
 930          * Put the value of the named short field into the persistent field.
 931          *
 932          * @param  name the name of the serializable field
 933          * @param  val the value to assign to the field
 934          * @throws IllegalArgumentException if {@code name} does not
 935          * match the name of a serializable field for the class whose fields
 936          * are being written, or if the type of the named field is not
 937          * {@code short}
 938          */
 939         public abstract void put(String name, short val);
 940 
 941         /**
 942          * Put the value of the named int field into the persistent field.
 943          *
 944          * @param  name the name of the serializable field
 945          * @param  val the value to assign to the field
 946          * @throws IllegalArgumentException if {@code name} does not
 947          * match the name of a serializable field for the class whose fields
 948          * are being written, or if the type of the named field is not
 949          * {@code int}
 950          */
 951         public abstract void put(String name, int val);
 952 
 953         /**
 954          * Put the value of the named long field into the persistent field.
 955          *
 956          * @param  name the name of the serializable field
 957          * @param  val the value to assign to the field
 958          * @throws IllegalArgumentException if {@code name} does not
 959          * match the name of a serializable field for the class whose fields
 960          * are being written, or if the type of the named field is not
 961          * {@code long}
 962          */
 963         public abstract void put(String name, long val);
 964 
 965         /**
 966          * Put the value of the named float field into the persistent field.
 967          *
 968          * @param  name the name of the serializable field
 969          * @param  val the value to assign to the field
 970          * @throws IllegalArgumentException if {@code name} does not
 971          * match the name of a serializable field for the class whose fields
 972          * are being written, or if the type of the named field is not
 973          * {@code float}
 974          */
 975         public abstract void put(String name, float val);
 976 
 977         /**
 978          * Put the value of the named double field into the persistent field.
 979          *
 980          * @param  name the name of the serializable field
 981          * @param  val the value to assign to the field
 982          * @throws IllegalArgumentException if {@code name} does not
 983          * match the name of a serializable field for the class whose fields
 984          * are being written, or if the type of the named field is not
 985          * {@code double}
 986          */
 987         public abstract void put(String name, double val);
 988 
 989         /**
 990          * Put the value of the named Object field into the persistent field.
 991          *
 992          * @param  name the name of the serializable field
 993          * @param  val the value to assign to the field
 994          *         (which may be {@code null})
 995          * @throws IllegalArgumentException if {@code name} does not
 996          * match the name of a serializable field for the class whose fields
 997          * are being written, or if the type of the named field is not a
 998          * reference type
 999          */
1000         public abstract void put(String name, Object val);
1001 
1002         /**
1003          * Write the data and fields to the specified ObjectOutput stream,
1004          * which must be the same stream that produced this
1005          * {@code PutField} object.
1006          *
1007          * @param  out the stream to write the data and fields to
1008          * @throws IOException if I/O errors occur while writing to the
1009          *         underlying stream
1010          * @throws IllegalArgumentException if the specified stream is not
1011          *         the same stream that produced this {@code PutField}
1012          *         object
1013          * @deprecated This method does not write the values contained by this
1014          *         {@code PutField} object in a proper format, and may
1015          *         result in corruption of the serialization stream.  The
1016          *         correct way to write {@code PutField} data is by
1017          *         calling the {@link java.io.ObjectOutputStream#writeFields()}
1018          *         method.
1019          */
1020         @Deprecated
1021         public abstract void write(ObjectOutput out) throws IOException;
1022     }
1023 
1024 
1025     /**
1026      * Returns protocol version in use.
1027      */
1028     int getProtocolVersion() {
1029         return protocol;
1030     }
1031 
1032     /**
1033      * Writes string without allowing it to be replaced in stream.  Used by
1034      * ObjectStreamClass to write class descriptor type strings.
1035      */
1036     void writeTypeString(String str) throws IOException {
1037         int handle;
1038         if (str == null) {
1039             writeNull();
1040         } else if ((handle = handles.lookup(str)) != -1) {
1041             writeHandle(handle);
1042         } else {
1043             writeString(str, false);
1044         }
1045     }
1046 
1047     /**
1048      * Verifies that this (possibly subclass) instance can be constructed
1049      * without violating security constraints: the subclass must not override
1050      * security-sensitive non-final methods, or else the
1051      * "enableSubclassImplementation" SerializablePermission is checked.
1052      */
1053     private void verifySubclass() {
1054         Class<?> cl = getClass();
1055         if (cl == ObjectOutputStream.class) {
1056             return;
1057         }
1058         @SuppressWarnings("removal")
1059         SecurityManager sm = System.getSecurityManager();
1060         if (sm == null) {
1061             return;
1062         }
1063         processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1064         WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1065         Boolean result = Caches.subclassAudits.get(key);
1066         if (result == null) {
1067             result = auditSubclass(cl);
1068             Caches.subclassAudits.putIfAbsent(key, result);
1069         }
1070         if (!result) {
1071             sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
1072         }
1073     }
1074 
1075     /**
1076      * Performs reflective checks on given subclass to verify that it doesn't
1077      * override security-sensitive non-final methods.  Returns TRUE if subclass
1078      * is "safe", FALSE otherwise.
1079      */
1080     @SuppressWarnings("removal")
1081     private static Boolean auditSubclass(Class<?> subcl) {
1082         return AccessController.doPrivileged(
1083             new PrivilegedAction<>() {
1084                 public Boolean run() {
1085                     for (Class<?> cl = subcl;
1086                          cl != ObjectOutputStream.class;
1087                          cl = cl.getSuperclass())
1088                     {
1089                         try {
1090                             cl.getDeclaredMethod(
1091                                 "writeUnshared", new Class<?>[] { Object.class });
1092                             return Boolean.FALSE;
1093                         } catch (NoSuchMethodException ex) {
1094                         }
1095                         try {
1096                             cl.getDeclaredMethod("putFields", (Class<?>[]) null);
1097                             return Boolean.FALSE;
1098                         } catch (NoSuchMethodException ex) {
1099                         }
1100                     }
1101                     return Boolean.TRUE;
1102                 }
1103             }
1104         );
1105     }
1106 
1107     /**
1108      * Clears internal data structures.
1109      */
1110     private void clear() {
1111         subs.clear();
1112         handles.clear();
1113     }
1114 
1115     /**
1116      * Underlying writeObject/writeUnshared implementation.
1117      */
1118     private void writeObject0(Object obj, boolean unshared)
1119         throws IOException
1120     {
1121         boolean oldMode = bout.setBlockDataMode(false);
1122         depth++;
1123         try {
1124             // handle previously written and non-replaceable objects
1125             int h;
1126             if ((obj = subs.lookup(obj)) == null) {
1127                 writeNull();
1128                 return;
1129             } else if (!unshared && (h = handles.lookup(obj)) != -1) {
1130                 writeHandle(h);
1131                 return;
1132             } else if (obj instanceof Class) {
1133                 writeClass((Class) obj, unshared);
1134                 return;
1135             } else if (obj instanceof ObjectStreamClass) {
1136                 writeClassDesc((ObjectStreamClass) obj, unshared);
1137                 return;
1138             }
1139 
1140             // check for replacement object
1141             Object orig = obj;
1142             Class<?> cl = obj.getClass();
1143             ObjectStreamClass desc;
1144             for (;;) {
1145                 // REMIND: skip this check for strings/arrays?
1146                 Class<?> repCl;
1147                 desc = ObjectStreamClass.lookup(cl, true);
1148                 if (!desc.hasWriteReplaceMethod() ||
1149                     (obj = desc.invokeWriteReplace(obj)) == null ||
1150                     (repCl = obj.getClass()) == cl)
1151                 {
1152                     break;
1153                 }
1154                 cl = repCl;
1155             }
1156             if (enableReplace) {
1157                 Object rep = replaceObject(obj);
1158                 if (rep != obj && rep != null) {
1159                     cl = rep.getClass();
1160                     desc = ObjectStreamClass.lookup(cl, true);
1161                 }
1162                 obj = rep;
1163             }
1164 
1165             // if object replaced, run through original checks a second time
1166             if (obj != orig) {
1167                 subs.assign(orig, obj);
1168                 if (obj == null) {
1169                     writeNull();
1170                     return;
1171                 } else if (!unshared && (h = handles.lookup(obj)) != -1) {
1172                     writeHandle(h);
1173                     return;
1174                 } else if (obj instanceof Class) {
1175                     writeClass((Class) obj, unshared);
1176                     return;
1177                 } else if (obj instanceof ObjectStreamClass) {
1178                     writeClassDesc((ObjectStreamClass) obj, unshared);
1179                     return;
1180                 }
1181             }
1182 
1183             // remaining cases
1184             if (obj instanceof String) {
1185                 writeString((String) obj, unshared);
1186             } else if (cl.isArray()) {
1187                 writeArray(obj, desc, unshared);
1188             } else if (obj instanceof Enum) {
1189                 writeEnum((Enum<?>) obj, desc, unshared);
1190             } else if (obj instanceof Serializable) {
1191                 writeOrdinaryObject(obj, desc, unshared);
1192             } else {
1193                 if (extendedDebugInfo) {
1194                     throw new NotSerializableException(
1195                         cl.getName() + "\n" + debugInfoStack.toString());
1196                 } else {
1197                     throw new NotSerializableException(cl.getName());
1198                 }
1199             }
1200         } finally {
1201             depth--;
1202             bout.setBlockDataMode(oldMode);
1203         }
1204     }
1205 
1206     /**
1207      * Writes null code to stream.
1208      */
1209     private void writeNull() throws IOException {
1210         bout.writeByte(TC_NULL);
1211     }
1212 
1213     /**
1214      * Writes given object handle to stream.
1215      */
1216     private void writeHandle(int handle) throws IOException {
1217         bout.writeByte(TC_REFERENCE);
1218         bout.writeInt(baseWireHandle + handle);
1219     }
1220 
1221     /**
1222      * Writes representation of given class to stream.
1223      */
1224     private void writeClass(Class<?> cl, boolean unshared) throws IOException {
1225         bout.writeByte(TC_CLASS);
1226         writeClassDesc(ObjectStreamClass.lookup(cl, true), false);
1227         handles.assign(unshared ? null : cl);
1228     }
1229 
1230     /**
1231      * Writes representation of given class descriptor to stream.
1232      */
1233     private void writeClassDesc(ObjectStreamClass desc, boolean unshared)
1234         throws IOException
1235     {
1236         int handle;
1237         if (desc == null) {
1238             writeNull();
1239         } else if (!unshared && (handle = handles.lookup(desc)) != -1) {
1240             writeHandle(handle);
1241         } else if (desc.isProxy()) {
1242             writeProxyDesc(desc, unshared);
1243         } else {
1244             writeNonProxyDesc(desc, unshared);
1245         }
1246     }
1247 
1248     private boolean isCustomSubclass() {
1249         // Return true if this class is a custom subclass of ObjectOutputStream
1250         return getClass().getClassLoader()
1251                    != ObjectOutputStream.class.getClassLoader();
1252     }
1253 
1254     /**
1255      * Writes class descriptor representing a dynamic proxy class to stream.
1256      */
1257     private void writeProxyDesc(ObjectStreamClass desc, boolean unshared)
1258         throws IOException
1259     {
1260         bout.writeByte(TC_PROXYCLASSDESC);
1261         handles.assign(unshared ? null : desc);
1262 
1263         Class<?> cl = desc.forClass();
1264         Class<?>[] ifaces = cl.getInterfaces();
1265         bout.writeInt(ifaces.length);
1266         for (int i = 0; i < ifaces.length; i++) {
1267             bout.writeUTF(ifaces[i].getName());
1268         }
1269 
1270         bout.setBlockDataMode(true);
1271         if (cl != null && isCustomSubclass()) {
1272             ReflectUtil.checkPackageAccess(cl);
1273         }
1274         annotateProxyClass(cl);
1275         bout.setBlockDataMode(false);
1276         bout.writeByte(TC_ENDBLOCKDATA);
1277 
1278         writeClassDesc(desc.getSuperDesc(), false);
1279     }
1280 
1281     /**
1282      * Writes class descriptor representing a standard (i.e., not a dynamic
1283      * proxy) class to stream.
1284      */
1285     private void writeNonProxyDesc(ObjectStreamClass desc, boolean unshared)
1286         throws IOException
1287     {
1288         bout.writeByte(TC_CLASSDESC);
1289         handles.assign(unshared ? null : desc);
1290 
1291         if (protocol == PROTOCOL_VERSION_1) {
1292             // do not invoke class descriptor write hook with old protocol
1293             desc.writeNonProxy(this);
1294         } else {
1295             writeClassDescriptor(desc);
1296         }
1297 
1298         Class<?> cl = desc.forClass();
1299         bout.setBlockDataMode(true);
1300         if (cl != null && isCustomSubclass()) {
1301             ReflectUtil.checkPackageAccess(cl);
1302         }
1303         annotateClass(cl);
1304         bout.setBlockDataMode(false);
1305         bout.writeByte(TC_ENDBLOCKDATA);
1306 
1307         writeClassDesc(desc.getSuperDesc(), false);
1308     }
1309 
1310     /**
1311      * Writes given string to stream, using standard or long UTF format
1312      * depending on string length.
1313      */
1314     private void writeString(String str, boolean unshared) throws IOException {
1315         handles.assign(unshared ? null : str);
1316         long utflen = bout.getUTFLength(str);
1317         if (utflen <= 0xFFFF) {
1318             bout.writeByte(TC_STRING);
1319             bout.writeUTF(str, utflen);
1320         } else {
1321             bout.writeByte(TC_LONGSTRING);
1322             bout.writeLongUTF(str, utflen);
1323         }
1324     }
1325 
1326     /**
1327      * Writes given array object to stream.
1328      */
1329     private void writeArray(Object array,
1330                             ObjectStreamClass desc,
1331                             boolean unshared)
1332         throws IOException
1333     {
1334         bout.writeByte(TC_ARRAY);
1335         writeClassDesc(desc, false);
1336         handles.assign(unshared ? null : array);
1337 
1338         Class<?> ccl = desc.forClass().getComponentType();
1339         if (ccl.isPrimitive()) {
1340             if (ccl == Integer.TYPE) {
1341                 int[] ia = (int[]) array;
1342                 bout.writeInt(ia.length);
1343                 bout.writeInts(ia, 0, ia.length);
1344             } else if (ccl == Byte.TYPE) {
1345                 byte[] ba = (byte[]) array;
1346                 bout.writeInt(ba.length);
1347                 bout.write(ba, 0, ba.length, true);
1348             } else if (ccl == Long.TYPE) {
1349                 long[] ja = (long[]) array;
1350                 bout.writeInt(ja.length);
1351                 bout.writeLongs(ja, 0, ja.length);
1352             } else if (ccl == Float.TYPE) {
1353                 float[] fa = (float[]) array;
1354                 bout.writeInt(fa.length);
1355                 bout.writeFloats(fa, 0, fa.length);
1356             } else if (ccl == Double.TYPE) {
1357                 double[] da = (double[]) array;
1358                 bout.writeInt(da.length);
1359                 bout.writeDoubles(da, 0, da.length);
1360             } else if (ccl == Short.TYPE) {
1361                 short[] sa = (short[]) array;
1362                 bout.writeInt(sa.length);
1363                 bout.writeShorts(sa, 0, sa.length);
1364             } else if (ccl == Character.TYPE) {
1365                 char[] ca = (char[]) array;
1366                 bout.writeInt(ca.length);
1367                 bout.writeChars(ca, 0, ca.length);
1368             } else if (ccl == Boolean.TYPE) {
1369                 boolean[] za = (boolean[]) array;
1370                 bout.writeInt(za.length);
1371                 bout.writeBooleans(za, 0, za.length);
1372             } else {
1373                 throw new InternalError();
1374             }
1375         } else {
1376             Object[] objs = (Object[]) array;
1377             int len = objs.length;
1378             bout.writeInt(len);
1379             if (extendedDebugInfo) {
1380                 debugInfoStack.push(
1381                     "array (class \"" + array.getClass().getName() +
1382                     "\", size: " + len  + ")");
1383             }
1384             try {
1385                 for (int i = 0; i < len; i++) {
1386                     if (extendedDebugInfo) {
1387                         debugInfoStack.push(
1388                             "element of array (index: " + i + ")");
1389                     }
1390                     try {
1391                         writeObject0(objs[i], false);
1392                     } finally {
1393                         if (extendedDebugInfo) {
1394                             debugInfoStack.pop();
1395                         }
1396                     }
1397                 }
1398             } finally {
1399                 if (extendedDebugInfo) {
1400                     debugInfoStack.pop();
1401                 }
1402             }
1403         }
1404     }
1405 
1406     /**
1407      * Writes given enum constant to stream.
1408      */
1409     private void writeEnum(Enum<?> en,
1410                            ObjectStreamClass desc,
1411                            boolean unshared)
1412         throws IOException
1413     {
1414         bout.writeByte(TC_ENUM);
1415         ObjectStreamClass sdesc = desc.getSuperDesc();
1416         writeClassDesc((sdesc.forClass() == Enum.class) ? desc : sdesc, false);
1417         handles.assign(unshared ? null : en);
1418         writeString(en.name(), false);
1419     }
1420 
1421     /**
1422      * Writes representation of an "ordinary" (i.e., not a String, Class,
1423      * ObjectStreamClass, array, or enum constant) serializable object to the
1424      * stream.
1425      */
1426     private void writeOrdinaryObject(Object obj,
1427                                      ObjectStreamClass desc,
1428                                      boolean unshared)
1429         throws IOException
1430     {
1431         if (extendedDebugInfo) {
1432             debugInfoStack.push(
1433                 (depth == 1 ? "root " : "") + "object (class \"" +
1434                 obj.getClass().getName() + "\", " + obj.toString() + ")");
1435         }
1436         try {
1437             desc.checkSerialize();
1438 
1439             bout.writeByte(TC_OBJECT);
1440             writeClassDesc(desc, false);
1441             handles.assign(unshared ? null : obj);
1442 
1443             if (desc.isRecord()) {
1444                 writeRecordData(obj, desc);
1445             } else if (desc.isExternalizable() && !desc.isProxy()) {
1446                 writeExternalData((Externalizable) obj);
1447             } else {
1448                 writeSerialData(obj, desc);
1449             }
1450         } finally {
1451             if (extendedDebugInfo) {
1452                 debugInfoStack.pop();
1453             }
1454         }
1455     }
1456 
1457     /**
1458      * Writes externalizable data of given object by invoking its
1459      * writeExternal() method.
1460      */
1461     private void writeExternalData(Externalizable obj) throws IOException {
1462         PutFieldImpl oldPut = curPut;
1463         curPut = null;
1464 
1465         if (extendedDebugInfo) {
1466             debugInfoStack.push("writeExternal data");
1467         }
1468         SerialCallbackContext oldContext = curContext;
1469         try {
1470             curContext = null;
1471             if (protocol == PROTOCOL_VERSION_1) {
1472                 obj.writeExternal(this);
1473             } else {
1474                 bout.setBlockDataMode(true);
1475                 obj.writeExternal(this);
1476                 bout.setBlockDataMode(false);
1477                 bout.writeByte(TC_ENDBLOCKDATA);
1478             }
1479         } finally {
1480             curContext = oldContext;
1481             if (extendedDebugInfo) {
1482                 debugInfoStack.pop();
1483             }
1484         }
1485 
1486         curPut = oldPut;
1487     }
1488 
1489     /** Writes the record component values for the given record object. */
1490     private void writeRecordData(Object obj, ObjectStreamClass desc)
1491         throws IOException
1492     {
1493         assert obj.getClass().isRecord();
1494         ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
1495         if (slots.length != 1) {
1496             throw new InvalidClassException(
1497                     "expected a single record slot length, but found: " + slots.length);
1498         }
1499 
1500         defaultWriteFields(obj, desc);  // #### seems unnecessary to use the accessors
1501     }
1502 
1503     /**
1504      * Writes instance data for each serializable class of given object, from
1505      * superclass to subclass.
1506      */
1507     private void writeSerialData(Object obj, ObjectStreamClass desc)
1508         throws IOException
1509     {
1510         ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
1511         for (int i = 0; i < slots.length; i++) {
1512             ObjectStreamClass slotDesc = slots[i].desc;
1513             if (slotDesc.hasWriteObjectMethod()) {
1514                 PutFieldImpl oldPut = curPut;
1515                 curPut = null;
1516                 SerialCallbackContext oldContext = curContext;
1517 
1518                 if (extendedDebugInfo) {
1519                     debugInfoStack.push(
1520                         "custom writeObject data (class \"" +
1521                         slotDesc.getName() + "\")");
1522                 }
1523                 try {
1524                     curContext = new SerialCallbackContext(obj, slotDesc);
1525                     bout.setBlockDataMode(true);
1526                     slotDesc.invokeWriteObject(obj, this);
1527                     bout.setBlockDataMode(false);
1528                     bout.writeByte(TC_ENDBLOCKDATA);
1529                 } finally {
1530                     curContext.setUsed();
1531                     curContext = oldContext;
1532                     if (extendedDebugInfo) {
1533                         debugInfoStack.pop();
1534                     }
1535                 }
1536 
1537                 curPut = oldPut;
1538             } else {
1539                 defaultWriteFields(obj, slotDesc);
1540             }
1541         }
1542     }
1543 
1544     /**
1545      * Fetches and writes values of serializable fields of given object to
1546      * stream.  The given class descriptor specifies which field values to
1547      * write, and in which order they should be written.
1548      */
1549     private void defaultWriteFields(Object obj, ObjectStreamClass desc)
1550         throws IOException
1551     {
1552         Class<?> cl = desc.forClass();
1553         if (cl != null && obj != null && !cl.isInstance(obj)) {
1554             throw new ClassCastException();
1555         }
1556 
1557         desc.checkDefaultSerialize();
1558 
1559         int primDataSize = desc.getPrimDataSize();
1560         if (primDataSize > 0) {
1561             if (primVals == null || primVals.length < primDataSize) {
1562                 primVals = new byte[primDataSize];
1563             }
1564             desc.getPrimFieldValues(obj, primVals);
1565             bout.write(primVals, 0, primDataSize, false);
1566         }
1567 
1568         int numObjFields = desc.getNumObjFields();
1569         if (numObjFields > 0) {
1570             ObjectStreamField[] fields = desc.getFields(false);
1571             Object[] objVals = new Object[numObjFields];
1572             int numPrimFields = fields.length - objVals.length;
1573             desc.getObjFieldValues(obj, objVals);
1574             for (int i = 0; i < objVals.length; i++) {
1575                 if (extendedDebugInfo) {
1576                     debugInfoStack.push(
1577                         "field (class \"" + desc.getName() + "\", name: \"" +
1578                         fields[numPrimFields + i].getName() + "\", type: \"" +
1579                         fields[numPrimFields + i].getType() + "\")");
1580                 }
1581                 try {
1582                     writeObject0(objVals[i],
1583                                  fields[numPrimFields + i].isUnshared());
1584                 } finally {
1585                     if (extendedDebugInfo) {
1586                         debugInfoStack.pop();
1587                     }
1588                 }
1589             }
1590         }
1591     }
1592 
1593     /**
1594      * Attempts to write to stream fatal IOException that has caused
1595      * serialization to abort.
1596      */
1597     private void writeFatalException(IOException ex) throws IOException {
1598         /*
1599          * Note: the serialization specification states that if a second
1600          * IOException occurs while attempting to serialize the original fatal
1601          * exception to the stream, then a StreamCorruptedException should be
1602          * thrown (section 2.1).  However, due to a bug in previous
1603          * implementations of serialization, StreamCorruptedExceptions were
1604          * rarely (if ever) actually thrown--the "root" exceptions from
1605          * underlying streams were thrown instead.  This historical behavior is
1606          * followed here for consistency.
1607          */
1608         clear();
1609         boolean oldMode = bout.setBlockDataMode(false);
1610         try {
1611             bout.writeByte(TC_EXCEPTION);
1612             writeObject0(ex, false);
1613             clear();
1614         } finally {
1615             bout.setBlockDataMode(oldMode);
1616         }
1617     }
1618 
1619     /**
1620      * Default PutField implementation.
1621      */
1622     private class PutFieldImpl extends PutField {
1623 
1624         /** class descriptor describing serializable fields */
1625         private final ObjectStreamClass desc;
1626         /** primitive field values */
1627         private final byte[] primVals;
1628         /** object field values */
1629         private final Object[] objVals;
1630 
1631         /**
1632          * Creates PutFieldImpl object for writing fields defined in given
1633          * class descriptor.
1634          */
1635         PutFieldImpl(ObjectStreamClass desc) {
1636             this.desc = desc;
1637             primVals = new byte[desc.getPrimDataSize()];
1638             objVals = new Object[desc.getNumObjFields()];
1639         }
1640 
1641         public void put(String name, boolean val) {
1642             Bits.putBoolean(primVals, getFieldOffset(name, Boolean.TYPE), val);
1643         }
1644 
1645         public void put(String name, byte val) {
1646             primVals[getFieldOffset(name, Byte.TYPE)] = val;
1647         }
1648 
1649         public void put(String name, char val) {
1650             Bits.putChar(primVals, getFieldOffset(name, Character.TYPE), val);
1651         }
1652 
1653         public void put(String name, short val) {
1654             Bits.putShort(primVals, getFieldOffset(name, Short.TYPE), val);
1655         }
1656 
1657         public void put(String name, int val) {
1658             Bits.putInt(primVals, getFieldOffset(name, Integer.TYPE), val);
1659         }
1660 
1661         public void put(String name, float val) {
1662             Bits.putFloat(primVals, getFieldOffset(name, Float.TYPE), val);
1663         }
1664 
1665         public void put(String name, long val) {
1666             Bits.putLong(primVals, getFieldOffset(name, Long.TYPE), val);
1667         }
1668 
1669         public void put(String name, double val) {
1670             Bits.putDouble(primVals, getFieldOffset(name, Double.TYPE), val);
1671         }
1672 
1673         public void put(String name, Object val) {
1674             objVals[getFieldOffset(name, Object.class)] = val;
1675         }
1676 
1677         // deprecated in ObjectOutputStream.PutField
1678         public void write(ObjectOutput out) throws IOException {
1679             /*
1680              * Applications should *not* use this method to write PutField
1681              * data, as it will lead to stream corruption if the PutField
1682              * object writes any primitive data (since block data mode is not
1683              * unset/set properly, as is done in OOS.writeFields()).  This
1684              * broken implementation is being retained solely for behavioral
1685              * compatibility, in order to support applications which use
1686              * OOS.PutField.write() for writing only non-primitive data.
1687              *
1688              * Serialization of unshared objects is not implemented here since
1689              * it is not necessary for backwards compatibility; also, unshared
1690              * semantics may not be supported by the given ObjectOutput
1691              * instance.  Applications which write unshared objects using the
1692              * PutField API must use OOS.writeFields().
1693              */
1694             if (ObjectOutputStream.this != out) {
1695                 throw new IllegalArgumentException("wrong stream");
1696             }
1697             out.write(primVals, 0, primVals.length);
1698 
1699             ObjectStreamField[] fields = desc.getFields(false);
1700             int numPrimFields = fields.length - objVals.length;
1701             // REMIND: warn if numPrimFields > 0?
1702             for (int i = 0; i < objVals.length; i++) {
1703                 if (fields[numPrimFields + i].isUnshared()) {
1704                     throw new IOException("cannot write unshared object");
1705                 }
1706                 out.writeObject(objVals[i]);
1707             }
1708         }
1709 
1710         /**
1711          * Writes buffered primitive data and object fields to stream.
1712          */
1713         void writeFields() throws IOException {
1714             bout.write(primVals, 0, primVals.length, false);
1715 
1716             ObjectStreamField[] fields = desc.getFields(false);
1717             int numPrimFields = fields.length - objVals.length;
1718             for (int i = 0; i < objVals.length; i++) {
1719                 if (extendedDebugInfo) {
1720                     debugInfoStack.push(
1721                         "field (class \"" + desc.getName() + "\", name: \"" +
1722                         fields[numPrimFields + i].getName() + "\", type: \"" +
1723                         fields[numPrimFields + i].getType() + "\")");
1724                 }
1725                 try {
1726                     writeObject0(objVals[i],
1727                                  fields[numPrimFields + i].isUnshared());
1728                 } finally {
1729                     if (extendedDebugInfo) {
1730                         debugInfoStack.pop();
1731                     }
1732                 }
1733             }
1734         }
1735 
1736         /**
1737          * Returns offset of field with given name and type.  A specified type
1738          * of null matches all types, Object.class matches all non-primitive
1739          * types, and any other non-null type matches assignable types only.
1740          * Throws IllegalArgumentException if no matching field found.
1741          */
1742         private int getFieldOffset(String name, Class<?> type) {
1743             ObjectStreamField field = desc.getField(name, type);
1744             if (field == null) {
1745                 throw new IllegalArgumentException("no such field " + name +
1746                                                    " with type " + type);
1747             }
1748             return field.getOffset();
1749         }
1750     }
1751 
1752     /**
1753      * Buffered output stream with two modes: in default mode, outputs data in
1754      * same format as DataOutputStream; in "block data" mode, outputs data
1755      * bracketed by block data markers (see object serialization specification
1756      * for details).
1757      */
1758     private static class BlockDataOutputStream
1759         extends OutputStream implements DataOutput
1760     {
1761         /** maximum data block length */
1762         private static final int MAX_BLOCK_SIZE = 1024;
1763         /** maximum data block header length */
1764         private static final int MAX_HEADER_SIZE = 5;
1765         /** (tunable) length of char buffer (for writing strings) */
1766         private static final int CHAR_BUF_SIZE = 256;
1767 
1768         /** buffer for writing general/block data */
1769         private final byte[] buf = new byte[MAX_BLOCK_SIZE];
1770         /** buffer for writing block data headers */
1771         private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
1772         /** char buffer for fast string writes */
1773         private final char[] cbuf = new char[CHAR_BUF_SIZE];
1774 
1775         /** block data mode */
1776         private boolean blkmode = false;
1777         /** current offset into buf */
1778         private int pos = 0;
1779 
1780         /** underlying output stream */
1781         private final OutputStream out;
1782         /** loopback stream (for data writes that span data blocks) */
1783         private final DataOutputStream dout;
1784 
1785         /**
1786          * Creates new BlockDataOutputStream on top of given underlying stream.
1787          * Block data mode is turned off by default.
1788          */
1789         BlockDataOutputStream(OutputStream out) {
1790             this.out = out;
1791             dout = new DataOutputStream(this);
1792         }
1793 
1794         /**
1795          * Sets block data mode to the given mode (true == on, false == off)
1796          * and returns the previous mode value.  If the new mode is the same as
1797          * the old mode, no action is taken.  If the new mode differs from the
1798          * old mode, any buffered data is flushed before switching to the new
1799          * mode.
1800          */
1801         boolean setBlockDataMode(boolean mode) throws IOException {
1802             if (blkmode == mode) {
1803                 return blkmode;
1804             }
1805             drain();
1806             blkmode = mode;
1807             return !blkmode;
1808         }
1809 
1810         /**
1811          * Returns true if the stream is currently in block data mode, false
1812          * otherwise.
1813          */
1814         boolean getBlockDataMode() {
1815             return blkmode;
1816         }
1817 
1818         /* ----------------- generic output stream methods ----------------- */
1819         /*
1820          * The following methods are equivalent to their counterparts in
1821          * OutputStream, except that they partition written data into data
1822          * blocks when in block data mode.
1823          */
1824 
1825         public void write(int b) throws IOException {
1826             if (pos >= MAX_BLOCK_SIZE) {
1827                 drain();
1828             }
1829             buf[pos++] = (byte) b;
1830         }
1831 
1832         public void write(byte[] b) throws IOException {
1833             write(b, 0, b.length, false);
1834         }
1835 
1836         public void write(byte[] b, int off, int len) throws IOException {
1837             write(b, off, len, false);
1838         }
1839 
1840         public void flush() throws IOException {
1841             drain();
1842             out.flush();
1843         }
1844 
1845         public void close() throws IOException {
1846             flush();
1847             out.close();
1848         }
1849 
1850         /**
1851          * Writes specified span of byte values from given array.  If copy is
1852          * true, copies the values to an intermediate buffer before writing
1853          * them to underlying stream (to avoid exposing a reference to the
1854          * original byte array).
1855          */
1856         void write(byte[] b, int off, int len, boolean copy)
1857             throws IOException
1858         {
1859             if (!(copy || blkmode)) {           // write directly
1860                 drain();
1861                 out.write(b, off, len);
1862                 return;
1863             }
1864 
1865             while (len > 0) {
1866                 if (pos >= MAX_BLOCK_SIZE) {
1867                     drain();
1868                 }
1869                 if (len >= MAX_BLOCK_SIZE && !copy && pos == 0) {
1870                     // avoid unnecessary copy
1871                     writeBlockHeader(MAX_BLOCK_SIZE);
1872                     out.write(b, off, MAX_BLOCK_SIZE);
1873                     off += MAX_BLOCK_SIZE;
1874                     len -= MAX_BLOCK_SIZE;
1875                 } else {
1876                     int wlen = Math.min(len, MAX_BLOCK_SIZE - pos);
1877                     System.arraycopy(b, off, buf, pos, wlen);
1878                     pos += wlen;
1879                     off += wlen;
1880                     len -= wlen;
1881                 }
1882             }
1883         }
1884 
1885         /**
1886          * Writes all buffered data from this stream to the underlying stream,
1887          * but does not flush underlying stream.
1888          */
1889         void drain() throws IOException {
1890             if (pos == 0) {
1891                 return;
1892             }
1893             if (blkmode) {
1894                 writeBlockHeader(pos);
1895             }
1896             out.write(buf, 0, pos);
1897             pos = 0;
1898         }
1899 
1900         /**
1901          * Writes block data header.  Data blocks shorter than 256 bytes are
1902          * prefixed with a 2-byte header; all others start with a 5-byte
1903          * header.
1904          */
1905         private void writeBlockHeader(int len) throws IOException {
1906             if (len <= 0xFF) {
1907                 hbuf[0] = TC_BLOCKDATA;
1908                 hbuf[1] = (byte) len;
1909                 out.write(hbuf, 0, 2);
1910             } else {
1911                 hbuf[0] = TC_BLOCKDATALONG;
1912                 Bits.putInt(hbuf, 1, len);
1913                 out.write(hbuf, 0, 5);
1914             }
1915         }
1916 
1917 
1918         /* ----------------- primitive data output methods ----------------- */
1919         /*
1920          * The following methods are equivalent to their counterparts in
1921          * DataOutputStream, except that they partition written data into data
1922          * blocks when in block data mode.
1923          */
1924 
1925         public void writeBoolean(boolean v) throws IOException {
1926             if (pos >= MAX_BLOCK_SIZE) {
1927                 drain();
1928             }
1929             Bits.putBoolean(buf, pos++, v);
1930         }
1931 
1932         public void writeByte(int v) throws IOException {
1933             if (pos >= MAX_BLOCK_SIZE) {
1934                 drain();
1935             }
1936             buf[pos++] = (byte) v;
1937         }
1938 
1939         public void writeChar(int v) throws IOException {
1940             if (pos + 2 <= MAX_BLOCK_SIZE) {
1941                 Bits.putChar(buf, pos, (char) v);
1942                 pos += 2;
1943             } else {
1944                 dout.writeChar(v);
1945             }
1946         }
1947 
1948         public void writeShort(int v) throws IOException {
1949             if (pos + 2 <= MAX_BLOCK_SIZE) {
1950                 Bits.putShort(buf, pos, (short) v);
1951                 pos += 2;
1952             } else {
1953                 dout.writeShort(v);
1954             }
1955         }
1956 
1957         public void writeInt(int v) throws IOException {
1958             if (pos + 4 <= MAX_BLOCK_SIZE) {
1959                 Bits.putInt(buf, pos, v);
1960                 pos += 4;
1961             } else {
1962                 dout.writeInt(v);
1963             }
1964         }
1965 
1966         public void writeFloat(float v) throws IOException {
1967             if (pos + 4 <= MAX_BLOCK_SIZE) {
1968                 Bits.putFloat(buf, pos, v);
1969                 pos += 4;
1970             } else {
1971                 dout.writeFloat(v);
1972             }
1973         }
1974 
1975         public void writeLong(long v) throws IOException {
1976             if (pos + 8 <= MAX_BLOCK_SIZE) {
1977                 Bits.putLong(buf, pos, v);
1978                 pos += 8;
1979             } else {
1980                 dout.writeLong(v);
1981             }
1982         }
1983 
1984         public void writeDouble(double v) throws IOException {
1985             if (pos + 8 <= MAX_BLOCK_SIZE) {
1986                 Bits.putDouble(buf, pos, v);
1987                 pos += 8;
1988             } else {
1989                 dout.writeDouble(v);
1990             }
1991         }
1992 
1993         public void writeBytes(String s) throws IOException {
1994             int endoff = s.length();
1995             int cpos = 0;
1996             int csize = 0;
1997             for (int off = 0; off < endoff; ) {
1998                 if (cpos >= csize) {
1999                     cpos = 0;
2000                     csize = Math.min(endoff - off, CHAR_BUF_SIZE);
2001                     s.getChars(off, off + csize, cbuf, 0);
2002                 }
2003                 if (pos >= MAX_BLOCK_SIZE) {
2004                     drain();
2005                 }
2006                 int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos);
2007                 int stop = pos + n;
2008                 while (pos < stop) {
2009                     buf[pos++] = (byte) cbuf[cpos++];
2010                 }
2011                 off += n;
2012             }
2013         }
2014 
2015         public void writeChars(String s) throws IOException {
2016             int endoff = s.length();
2017             for (int off = 0; off < endoff; ) {
2018                 int csize = Math.min(endoff - off, CHAR_BUF_SIZE);
2019                 s.getChars(off, off + csize, cbuf, 0);
2020                 writeChars(cbuf, 0, csize);
2021                 off += csize;
2022             }
2023         }
2024 
2025         public void writeUTF(String s) throws IOException {
2026             writeUTF(s, getUTFLength(s));
2027         }
2028 
2029 
2030         /* -------------- primitive data array output methods -------------- */
2031         /*
2032          * The following methods write out spans of primitive data values.
2033          * Though equivalent to calling the corresponding primitive write
2034          * methods repeatedly, these methods are optimized for writing groups
2035          * of primitive data values more efficiently.
2036          */
2037 
2038         void writeBooleans(boolean[] v, int off, int len) throws IOException {
2039             int endoff = off + len;
2040             while (off < endoff) {
2041                 if (pos >= MAX_BLOCK_SIZE) {
2042                     drain();
2043                 }
2044                 int stop = Math.min(endoff, off + (MAX_BLOCK_SIZE - pos));
2045                 while (off < stop) {
2046                     Bits.putBoolean(buf, pos++, v[off++]);
2047                 }
2048             }
2049         }
2050 
2051         void writeChars(char[] v, int off, int len) throws IOException {
2052             int limit = MAX_BLOCK_SIZE - 2;
2053             int endoff = off + len;
2054             while (off < endoff) {
2055                 if (pos <= limit) {
2056                     int avail = (MAX_BLOCK_SIZE - pos) >> 1;
2057                     int stop = Math.min(endoff, off + avail);
2058                     while (off < stop) {
2059                         Bits.putChar(buf, pos, v[off++]);
2060                         pos += 2;
2061                     }
2062                 } else {
2063                     dout.writeChar(v[off++]);
2064                 }
2065             }
2066         }
2067 
2068         void writeShorts(short[] v, int off, int len) throws IOException {
2069             int limit = MAX_BLOCK_SIZE - 2;
2070             int endoff = off + len;
2071             while (off < endoff) {
2072                 if (pos <= limit) {
2073                     int avail = (MAX_BLOCK_SIZE - pos) >> 1;
2074                     int stop = Math.min(endoff, off + avail);
2075                     while (off < stop) {
2076                         Bits.putShort(buf, pos, v[off++]);
2077                         pos += 2;
2078                     }
2079                 } else {
2080                     dout.writeShort(v[off++]);
2081                 }
2082             }
2083         }
2084 
2085         void writeInts(int[] v, int off, int len) throws IOException {
2086             int limit = MAX_BLOCK_SIZE - 4;
2087             int endoff = off + len;
2088             while (off < endoff) {
2089                 if (pos <= limit) {
2090                     int avail = (MAX_BLOCK_SIZE - pos) >> 2;
2091                     int stop = Math.min(endoff, off + avail);
2092                     while (off < stop) {
2093                         Bits.putInt(buf, pos, v[off++]);
2094                         pos += 4;
2095                     }
2096                 } else {
2097                     dout.writeInt(v[off++]);
2098                 }
2099             }
2100         }
2101 
2102         void writeFloats(float[] v, int off, int len) throws IOException {
2103             int limit = MAX_BLOCK_SIZE - 4;
2104             int endoff = off + len;
2105             while (off < endoff) {
2106                 if (pos <= limit) {
2107                     int avail = (MAX_BLOCK_SIZE - pos) >> 2;
2108                     int stop = Math.min(endoff, off + avail);
2109                     while (off < stop) {
2110                         Bits.putFloat(buf, pos, v[off++]);
2111                         pos += 4;
2112                     }
2113                 } else {
2114                     dout.writeFloat(v[off++]);
2115                 }
2116             }
2117         }
2118 
2119         void writeLongs(long[] v, int off, int len) throws IOException {
2120             int limit = MAX_BLOCK_SIZE - 8;
2121             int endoff = off + len;
2122             while (off < endoff) {
2123                 if (pos <= limit) {
2124                     int avail = (MAX_BLOCK_SIZE - pos) >> 3;
2125                     int stop = Math.min(endoff, off + avail);
2126                     while (off < stop) {
2127                         Bits.putLong(buf, pos, v[off++]);
2128                         pos += 8;
2129                     }
2130                 } else {
2131                     dout.writeLong(v[off++]);
2132                 }
2133             }
2134         }
2135 
2136         void writeDoubles(double[] v, int off, int len) throws IOException {
2137             int limit = MAX_BLOCK_SIZE - 8;
2138             int endoff = off + len;
2139             while (off < endoff) {
2140                 if (pos <= limit) {
2141                     int avail = (MAX_BLOCK_SIZE - pos) >> 3;
2142                     int stop = Math.min(endoff, off + avail);
2143                     while (off < stop) {
2144                         Bits.putDouble(buf, pos, v[off++]);
2145                         pos += 8;
2146                     }
2147                 } else {
2148                     dout.writeDouble(v[off++]);
2149                 }
2150             }
2151         }
2152 
2153         /**
2154          * Returns the length in bytes of the UTF encoding of the given string.
2155          */
2156         long getUTFLength(String s) {
2157             int len = s.length();
2158             long utflen = 0;
2159             for (int off = 0; off < len; ) {
2160                 int csize = Math.min(len - off, CHAR_BUF_SIZE);
2161                 s.getChars(off, off + csize, cbuf, 0);
2162                 for (int cpos = 0; cpos < csize; cpos++) {
2163                     char c = cbuf[cpos];
2164                     if (c >= 0x0001 && c <= 0x007F) {
2165                         utflen++;
2166                     } else if (c > 0x07FF) {
2167                         utflen += 3;
2168                     } else {
2169                         utflen += 2;
2170                     }
2171                 }
2172                 off += csize;
2173             }
2174             return utflen;
2175         }
2176 
2177         /**
2178          * Writes the given string in UTF format.  This method is used in
2179          * situations where the UTF encoding length of the string is already
2180          * known; specifying it explicitly avoids a prescan of the string to
2181          * determine its UTF length.
2182          */
2183         void writeUTF(String s, long utflen) throws IOException {
2184             if (utflen > 0xFFFFL) {
2185                 throw new UTFDataFormatException();
2186             }
2187             writeShort((int) utflen);
2188             if (utflen == (long) s.length()) {
2189                 writeBytes(s);
2190             } else {
2191                 writeUTFBody(s);
2192             }
2193         }
2194 
2195         /**
2196          * Writes given string in "long" UTF format.  "Long" UTF format is
2197          * identical to standard UTF, except that it uses an 8 byte header
2198          * (instead of the standard 2 bytes) to convey the UTF encoding length.
2199          */
2200         void writeLongUTF(String s) throws IOException {
2201             writeLongUTF(s, getUTFLength(s));
2202         }
2203 
2204         /**
2205          * Writes given string in "long" UTF format, where the UTF encoding
2206          * length of the string is already known.
2207          */
2208         void writeLongUTF(String s, long utflen) throws IOException {
2209             writeLong(utflen);
2210             if (utflen == (long) s.length()) {
2211                 writeBytes(s);
2212             } else {
2213                 writeUTFBody(s);
2214             }
2215         }
2216 
2217         /**
2218          * Writes the "body" (i.e., the UTF representation minus the 2-byte or
2219          * 8-byte length header) of the UTF encoding for the given string.
2220          */
2221         private void writeUTFBody(String s) throws IOException {
2222             int limit = MAX_BLOCK_SIZE - 3;
2223             int len = s.length();
2224             for (int off = 0; off < len; ) {
2225                 int csize = Math.min(len - off, CHAR_BUF_SIZE);
2226                 s.getChars(off, off + csize, cbuf, 0);
2227                 for (int cpos = 0; cpos < csize; cpos++) {
2228                     char c = cbuf[cpos];
2229                     if (pos <= limit) {
2230                         if (c <= 0x007F && c != 0) {
2231                             buf[pos++] = (byte) c;
2232                         } else if (c > 0x07FF) {
2233                             buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F));
2234                             buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F));
2235                             buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F));
2236                             pos += 3;
2237                         } else {
2238                             buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F));
2239                             buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F));
2240                             pos += 2;
2241                         }
2242                     } else {    // write one byte at a time to normalize block
2243                         if (c <= 0x007F && c != 0) {
2244                             write(c);
2245                         } else if (c > 0x07FF) {
2246                             write(0xE0 | ((c >> 12) & 0x0F));
2247                             write(0x80 | ((c >> 6) & 0x3F));
2248                             write(0x80 | ((c >> 0) & 0x3F));
2249                         } else {
2250                             write(0xC0 | ((c >> 6) & 0x1F));
2251                             write(0x80 | ((c >> 0) & 0x3F));
2252                         }
2253                     }
2254                 }
2255                 off += csize;
2256             }
2257         }
2258     }
2259 
2260     /**
2261      * Lightweight identity hash table which maps objects to integer handles,
2262      * assigned in ascending order.
2263      */
2264     private static class HandleTable {
2265 
2266         /* number of mappings in table/next available handle */
2267         private int size;
2268         /* size threshold determining when to expand hash spine */
2269         private int threshold;
2270         /* factor for computing size threshold */
2271         private final float loadFactor;
2272         /* maps hash value -> candidate handle value */
2273         private int[] spine;
2274         /* maps handle value -> next candidate handle value */
2275         private int[] next;
2276         /* maps handle value -> associated object */
2277         private Object[] objs;
2278 
2279         /**
2280          * Creates new HandleTable with given capacity and load factor.
2281          */
2282         HandleTable(int initialCapacity, float loadFactor) {
2283             this.loadFactor = loadFactor;
2284             spine = new int[initialCapacity];
2285             next = new int[initialCapacity];
2286             objs = new Object[initialCapacity];
2287             threshold = (int) (initialCapacity * loadFactor);
2288             clear();
2289         }
2290 
2291         /**
2292          * Assigns next available handle to given object, and returns handle
2293          * value.  Handles are assigned in ascending order starting at 0.
2294          */
2295         int assign(Object obj) {
2296             if (size >= next.length) {
2297                 growEntries();
2298             }
2299             if (size >= threshold) {
2300                 growSpine();
2301             }
2302             insert(obj, size);
2303             return size++;
2304         }
2305 
2306         /**
2307          * Looks up and returns handle associated with given object, or -1 if
2308          * no mapping found.
2309          */
2310         int lookup(Object obj) {
2311             if (size == 0) {
2312                 return -1;
2313             }
2314             int index = hash(obj) % spine.length;
2315             for (int i = spine[index]; i >= 0; i = next[i]) {
2316                 if (objs[i] == obj) {
2317                     return i;
2318                 }
2319             }
2320             return -1;
2321         }
2322 
2323         /**
2324          * Resets table to its initial (empty) state.
2325          */
2326         void clear() {
2327             Arrays.fill(spine, -1);
2328             Arrays.fill(objs, 0, size, null);
2329             size = 0;
2330         }
2331 
2332         /**
2333          * Returns the number of mappings currently in table.
2334          */
2335         int size() {
2336             return size;
2337         }
2338 
2339         /**
2340          * Inserts mapping object -> handle mapping into table.  Assumes table
2341          * is large enough to accommodate new mapping.
2342          */
2343         private void insert(Object obj, int handle) {
2344             int index = hash(obj) % spine.length;
2345             objs[handle] = obj;
2346             next[handle] = spine[index];
2347             spine[index] = handle;
2348         }
2349 
2350         /**
2351          * Expands the hash "spine" -- equivalent to increasing the number of
2352          * buckets in a conventional hash table.
2353          */
2354         private void growSpine() {
2355             spine = new int[(spine.length << 1) + 1];
2356             threshold = (int) (spine.length * loadFactor);
2357             Arrays.fill(spine, -1);
2358             for (int i = 0; i < size; i++) {
2359                 insert(objs[i], i);
2360             }
2361         }
2362 
2363         /**
2364          * Increases hash table capacity by lengthening entry arrays.
2365          */
2366         private void growEntries() {
2367             int newLength = (next.length << 1) + 1;
2368             int[] newNext = new int[newLength];
2369             System.arraycopy(next, 0, newNext, 0, size);
2370             next = newNext;
2371 
2372             Object[] newObjs = new Object[newLength];
2373             System.arraycopy(objs, 0, newObjs, 0, size);
2374             objs = newObjs;
2375         }
2376 
2377         /**
2378          * Returns hash value for given object.
2379          */
2380         private int hash(Object obj) {
2381             return System.identityHashCode(obj) & 0x7FFFFFFF;
2382         }
2383     }
2384 
2385     /**
2386      * Lightweight identity hash table which maps objects to replacement
2387      * objects.
2388      */
2389     private static class ReplaceTable {
2390 
2391         /* maps object -> index */
2392         private final HandleTable htab;
2393         /* maps index -> replacement object */
2394         private Object[] reps;
2395 
2396         /**
2397          * Creates new ReplaceTable with given capacity and load factor.
2398          */
2399         ReplaceTable(int initialCapacity, float loadFactor) {
2400             htab = new HandleTable(initialCapacity, loadFactor);
2401             reps = new Object[initialCapacity];
2402         }
2403 
2404         /**
2405          * Enters mapping from object to replacement object.
2406          */
2407         void assign(Object obj, Object rep) {
2408             int index = htab.assign(obj);
2409             while (index >= reps.length) {
2410                 grow();
2411             }
2412             reps[index] = rep;
2413         }
2414 
2415         /**
2416          * Looks up and returns replacement for given object.  If no
2417          * replacement is found, returns the lookup object itself.
2418          */
2419         Object lookup(Object obj) {
2420             int index = htab.lookup(obj);
2421             return (index >= 0) ? reps[index] : obj;
2422         }
2423 
2424         /**
2425          * Resets table to its initial (empty) state.
2426          */
2427         void clear() {
2428             Arrays.fill(reps, 0, htab.size(), null);
2429             htab.clear();
2430         }
2431 
2432         /**
2433          * Returns the number of mappings currently in table.
2434          */
2435         int size() {
2436             return htab.size();
2437         }
2438 
2439         /**
2440          * Increases table capacity.
2441          */
2442         private void grow() {
2443             Object[] newReps = new Object[(reps.length << 1) + 1];
2444             System.arraycopy(reps, 0, newReps, 0, reps.length);
2445             reps = newReps;
2446         }
2447     }
2448 
2449     /**
2450      * Stack to keep debug information about the state of the
2451      * serialization process, for embedding in exception messages.
2452      */
2453     private static class DebugTraceInfoStack {
2454         private final List<String> stack;
2455 
2456         DebugTraceInfoStack() {
2457             stack = new ArrayList<>();
2458         }
2459 
2460         /**
2461          * Removes all of the elements from enclosed list.
2462          */
2463         void clear() {
2464             stack.clear();
2465         }
2466 
2467         /**
2468          * Removes the object at the top of enclosed list.
2469          */
2470         void pop() {
2471             stack.remove(stack.size()-1);
2472         }
2473 
2474         /**
2475          * Pushes a String onto the top of enclosed list.
2476          */
2477         void push(String entry) {
2478             stack.add("\t- " + entry);
2479         }
2480 
2481         /**
2482          * Returns a string representation of this object
2483          */
2484         public String toString() {
2485             StringJoiner sj = new StringJoiner("\n");
2486             for (int i = stack.size() - 1; i >= 0; i--) {
2487                 sj.add(stack.get(i));
2488             }
2489             return sj.toString();
2490         }
2491     }
2492 
2493 }