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.isPrimitiveClass()) {
1187                 throw new NotSerializableException(cl.getName());
1188             } else if (cl.isArray()) {
1189                 writeArray(obj, desc, unshared);
1190             } else if (obj instanceof Enum) {
1191                 writeEnum((Enum<?>) obj, desc, unshared);
1192             } else if (obj instanceof Serializable) {
1193                 writeOrdinaryObject(obj, desc, unshared);
1194             } else {
1195                 if (extendedDebugInfo) {
1196                     throw new NotSerializableException(
1197                         cl.getName() + "\n" + debugInfoStack.toString());
1198                 } else {
1199                     throw new NotSerializableException(cl.getName());
1200                 }
1201             }
1202         } finally {
1203             depth--;
1204             bout.setBlockDataMode(oldMode);
1205         }
1206     }
1207 
1208     /**
1209      * Writes null code to stream.
1210      */
1211     private void writeNull() throws IOException {
1212         bout.writeByte(TC_NULL);
1213     }
1214 
1215     /**
1216      * Writes given object handle to stream.
1217      */
1218     private void writeHandle(int handle) throws IOException {
1219         bout.writeByte(TC_REFERENCE);
1220         bout.writeInt(baseWireHandle + handle);
1221     }
1222 
1223     /**
1224      * Writes representation of given class to stream.
1225      */
1226     private void writeClass(Class<?> cl, boolean unshared) throws IOException {
1227         bout.writeByte(TC_CLASS);
1228         writeClassDesc(ObjectStreamClass.lookup(cl, true), false);
1229         handles.assign(unshared ? null : cl);
1230     }
1231 
1232     /**
1233      * Writes representation of given class descriptor to stream.
1234      */
1235     private void writeClassDesc(ObjectStreamClass desc, boolean unshared)
1236         throws IOException
1237     {
1238         int handle;
1239         if (desc == null) {
1240             writeNull();
1241         } else if (!unshared && (handle = handles.lookup(desc)) != -1) {
1242             writeHandle(handle);
1243         } else if (desc.isProxy()) {
1244             writeProxyDesc(desc, unshared);
1245         } else {
1246             writeNonProxyDesc(desc, unshared);
1247         }
1248     }
1249 
1250     private boolean isCustomSubclass() {
1251         // Return true if this class is a custom subclass of ObjectOutputStream
1252         return getClass().getClassLoader()
1253                    != ObjectOutputStream.class.getClassLoader();
1254     }
1255 
1256     /**
1257      * Writes class descriptor representing a dynamic proxy class to stream.
1258      */
1259     private void writeProxyDesc(ObjectStreamClass desc, boolean unshared)
1260         throws IOException
1261     {
1262         bout.writeByte(TC_PROXYCLASSDESC);
1263         handles.assign(unshared ? null : desc);
1264 
1265         Class<?> cl = desc.forClass();
1266         Class<?>[] ifaces = cl.getInterfaces();
1267         bout.writeInt(ifaces.length);
1268         for (int i = 0; i < ifaces.length; i++) {
1269             bout.writeUTF(ifaces[i].getName());
1270         }
1271 
1272         bout.setBlockDataMode(true);
1273         if (cl != null && isCustomSubclass()) {
1274             ReflectUtil.checkPackageAccess(cl);
1275         }
1276         annotateProxyClass(cl);
1277         bout.setBlockDataMode(false);
1278         bout.writeByte(TC_ENDBLOCKDATA);
1279 
1280         writeClassDesc(desc.getSuperDesc(), false);
1281     }
1282 
1283     /**
1284      * Writes class descriptor representing a standard (i.e., not a dynamic
1285      * proxy) class to stream.
1286      */
1287     private void writeNonProxyDesc(ObjectStreamClass desc, boolean unshared)
1288         throws IOException
1289     {
1290         bout.writeByte(TC_CLASSDESC);
1291         handles.assign(unshared ? null : desc);
1292 
1293         if (protocol == PROTOCOL_VERSION_1) {
1294             // do not invoke class descriptor write hook with old protocol
1295             desc.writeNonProxy(this);
1296         } else {
1297             writeClassDescriptor(desc);
1298         }
1299 
1300         Class<?> cl = desc.forClass();
1301         bout.setBlockDataMode(true);
1302         if (cl != null && isCustomSubclass()) {
1303             ReflectUtil.checkPackageAccess(cl);
1304         }
1305         annotateClass(cl);
1306         bout.setBlockDataMode(false);
1307         bout.writeByte(TC_ENDBLOCKDATA);
1308 
1309         writeClassDesc(desc.getSuperDesc(), false);
1310     }
1311 
1312     /**
1313      * Writes given string to stream, using standard or long UTF format
1314      * depending on string length.
1315      */
1316     private void writeString(String str, boolean unshared) throws IOException {
1317         handles.assign(unshared ? null : str);
1318         long utflen = bout.getUTFLength(str);
1319         if (utflen <= 0xFFFF) {
1320             bout.writeByte(TC_STRING);
1321             bout.writeUTF(str, utflen);
1322         } else {
1323             bout.writeByte(TC_LONGSTRING);
1324             bout.writeLongUTF(str, utflen);
1325         }
1326     }
1327 
1328     /**
1329      * Writes given array object to stream.
1330      */
1331     private void writeArray(Object array,
1332                             ObjectStreamClass desc,
1333                             boolean unshared)
1334         throws IOException
1335     {
1336         bout.writeByte(TC_ARRAY);
1337         writeClassDesc(desc, false);
1338         handles.assign(unshared ? null : array);
1339 
1340         Class<?> ccl = desc.forClass().getComponentType();
1341         if (ccl.isPrimitive()) {
1342             if (ccl == Integer.TYPE) {
1343                 int[] ia = (int[]) array;
1344                 bout.writeInt(ia.length);
1345                 bout.writeInts(ia, 0, ia.length);
1346             } else if (ccl == Byte.TYPE) {
1347                 byte[] ba = (byte[]) array;
1348                 bout.writeInt(ba.length);
1349                 bout.write(ba, 0, ba.length, true);
1350             } else if (ccl == Long.TYPE) {
1351                 long[] ja = (long[]) array;
1352                 bout.writeInt(ja.length);
1353                 bout.writeLongs(ja, 0, ja.length);
1354             } else if (ccl == Float.TYPE) {
1355                 float[] fa = (float[]) array;
1356                 bout.writeInt(fa.length);
1357                 bout.writeFloats(fa, 0, fa.length);
1358             } else if (ccl == Double.TYPE) {
1359                 double[] da = (double[]) array;
1360                 bout.writeInt(da.length);
1361                 bout.writeDoubles(da, 0, da.length);
1362             } else if (ccl == Short.TYPE) {
1363                 short[] sa = (short[]) array;
1364                 bout.writeInt(sa.length);
1365                 bout.writeShorts(sa, 0, sa.length);
1366             } else if (ccl == Character.TYPE) {
1367                 char[] ca = (char[]) array;
1368                 bout.writeInt(ca.length);
1369                 bout.writeChars(ca, 0, ca.length);
1370             } else if (ccl == Boolean.TYPE) {
1371                 boolean[] za = (boolean[]) array;
1372                 bout.writeInt(za.length);
1373                 bout.writeBooleans(za, 0, za.length);
1374             } else {
1375                 throw new InternalError();
1376             }
1377         } else {
1378             Object[] objs = (Object[]) array;
1379             int len = objs.length;
1380             bout.writeInt(len);
1381             if (extendedDebugInfo) {
1382                 debugInfoStack.push(
1383                     "array (class \"" + array.getClass().getName() +
1384                     "\", size: " + len  + ")");
1385             }
1386             try {
1387                 for (int i = 0; i < len; i++) {
1388                     if (extendedDebugInfo) {
1389                         debugInfoStack.push(
1390                             "element of array (index: " + i + ")");
1391                     }
1392                     try {
1393                         writeObject0(objs[i], false);
1394                     } finally {
1395                         if (extendedDebugInfo) {
1396                             debugInfoStack.pop();
1397                         }
1398                     }
1399                 }
1400             } finally {
1401                 if (extendedDebugInfo) {
1402                     debugInfoStack.pop();
1403                 }
1404             }
1405         }
1406     }
1407 
1408     /**
1409      * Writes given enum constant to stream.
1410      */
1411     private void writeEnum(Enum<?> en,
1412                            ObjectStreamClass desc,
1413                            boolean unshared)
1414         throws IOException
1415     {
1416         bout.writeByte(TC_ENUM);
1417         ObjectStreamClass sdesc = desc.getSuperDesc();
1418         writeClassDesc((sdesc.forClass() == Enum.class) ? desc : sdesc, false);
1419         handles.assign(unshared ? null : en);
1420         writeString(en.name(), false);
1421     }
1422 
1423     /**
1424      * Writes representation of an "ordinary" (i.e., not a String, Class,
1425      * ObjectStreamClass, array, or enum constant) serializable object to the
1426      * stream.
1427      */
1428     private void writeOrdinaryObject(Object obj,
1429                                      ObjectStreamClass desc,
1430                                      boolean unshared)
1431         throws IOException
1432     {
1433         if (extendedDebugInfo) {
1434             debugInfoStack.push(
1435                 (depth == 1 ? "root " : "") + "object (class \"" +
1436                 obj.getClass().getName() + "\", " + obj.toString() + ")");
1437         }
1438         try {
1439             desc.checkSerialize();
1440 
1441             bout.writeByte(TC_OBJECT);
1442             writeClassDesc(desc, false);
1443             handles.assign(unshared ? null : obj);
1444 
1445             if (desc.isRecord()) {
1446                 writeRecordData(obj, desc);
1447             } else if (desc.isExternalizable() && !desc.isProxy()) {
1448                 writeExternalData((Externalizable) obj);
1449             } else {
1450                 writeSerialData(obj, desc);
1451             }
1452         } finally {
1453             if (extendedDebugInfo) {
1454                 debugInfoStack.pop();
1455             }
1456         }
1457     }
1458 
1459     /**
1460      * Writes externalizable data of given object by invoking its
1461      * writeExternal() method.
1462      */
1463     private void writeExternalData(Externalizable obj) throws IOException {
1464         PutFieldImpl oldPut = curPut;
1465         curPut = null;
1466 
1467         if (extendedDebugInfo) {
1468             debugInfoStack.push("writeExternal data");
1469         }
1470         SerialCallbackContext oldContext = curContext;
1471         try {
1472             curContext = null;
1473             if (protocol == PROTOCOL_VERSION_1) {
1474                 obj.writeExternal(this);
1475             } else {
1476                 bout.setBlockDataMode(true);
1477                 obj.writeExternal(this);
1478                 bout.setBlockDataMode(false);
1479                 bout.writeByte(TC_ENDBLOCKDATA);
1480             }
1481         } finally {
1482             curContext = oldContext;
1483             if (extendedDebugInfo) {
1484                 debugInfoStack.pop();
1485             }
1486         }
1487 
1488         curPut = oldPut;
1489     }
1490 
1491     /** Writes the record component values for the given record object. */
1492     private void writeRecordData(Object obj, ObjectStreamClass desc)
1493         throws IOException
1494     {
1495         assert obj.getClass().isRecord();
1496         ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
1497         if (slots.length != 1) {
1498             throw new InvalidClassException(
1499                     "expected a single record slot length, but found: " + slots.length);
1500         }
1501 
1502         defaultWriteFields(obj, desc);  // #### seems unnecessary to use the accessors
1503     }
1504 
1505     /**
1506      * Writes instance data for each serializable class of given object, from
1507      * superclass to subclass.
1508      */
1509     private void writeSerialData(Object obj, ObjectStreamClass desc)
1510         throws IOException
1511     {
1512         ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
1513         for (int i = 0; i < slots.length; i++) {
1514             ObjectStreamClass slotDesc = slots[i].desc;
1515             if (slotDesc.hasWriteObjectMethod()) {
1516                 PutFieldImpl oldPut = curPut;
1517                 curPut = null;
1518                 SerialCallbackContext oldContext = curContext;
1519 
1520                 if (extendedDebugInfo) {
1521                     debugInfoStack.push(
1522                         "custom writeObject data (class \"" +
1523                         slotDesc.getName() + "\")");
1524                 }
1525                 try {
1526                     curContext = new SerialCallbackContext(obj, slotDesc);
1527                     bout.setBlockDataMode(true);
1528                     slotDesc.invokeWriteObject(obj, this);
1529                     bout.setBlockDataMode(false);
1530                     bout.writeByte(TC_ENDBLOCKDATA);
1531                 } finally {
1532                     curContext.setUsed();
1533                     curContext = oldContext;
1534                     if (extendedDebugInfo) {
1535                         debugInfoStack.pop();
1536                     }
1537                 }
1538 
1539                 curPut = oldPut;
1540             } else {
1541                 defaultWriteFields(obj, slotDesc);
1542             }
1543         }
1544     }
1545 
1546     /**
1547      * Fetches and writes values of serializable fields of given object to
1548      * stream.  The given class descriptor specifies which field values to
1549      * write, and in which order they should be written.
1550      */
1551     private void defaultWriteFields(Object obj, ObjectStreamClass desc)
1552         throws IOException
1553     {
1554         Class<?> cl = desc.forClass();
1555         if (cl != null && obj != null && !cl.isInstance(obj)) {
1556             throw new ClassCastException();
1557         }
1558 
1559         desc.checkDefaultSerialize();
1560 
1561         int primDataSize = desc.getPrimDataSize();
1562         if (primDataSize > 0) {
1563             if (primVals == null || primVals.length < primDataSize) {
1564                 primVals = new byte[primDataSize];
1565             }
1566             desc.getPrimFieldValues(obj, primVals);
1567             bout.write(primVals, 0, primDataSize, false);
1568         }
1569 
1570         int numObjFields = desc.getNumObjFields();
1571         if (numObjFields > 0) {
1572             ObjectStreamField[] fields = desc.getFields(false);
1573             Object[] objVals = new Object[numObjFields];
1574             int numPrimFields = fields.length - objVals.length;
1575             desc.getObjFieldValues(obj, objVals);
1576             for (int i = 0; i < objVals.length; i++) {
1577                 if (extendedDebugInfo) {
1578                     debugInfoStack.push(
1579                         "field (class \"" + desc.getName() + "\", name: \"" +
1580                         fields[numPrimFields + i].getName() + "\", type: \"" +
1581                         fields[numPrimFields + i].getType() + "\")");
1582                 }
1583                 try {
1584                     writeObject0(objVals[i],
1585                                  fields[numPrimFields + i].isUnshared());
1586                 } finally {
1587                     if (extendedDebugInfo) {
1588                         debugInfoStack.pop();
1589                     }
1590                 }
1591             }
1592         }
1593     }
1594 
1595     /**
1596      * Attempts to write to stream fatal IOException that has caused
1597      * serialization to abort.
1598      */
1599     private void writeFatalException(IOException ex) throws IOException {
1600         /*
1601          * Note: the serialization specification states that if a second
1602          * IOException occurs while attempting to serialize the original fatal
1603          * exception to the stream, then a StreamCorruptedException should be
1604          * thrown (section 2.1).  However, due to a bug in previous
1605          * implementations of serialization, StreamCorruptedExceptions were
1606          * rarely (if ever) actually thrown--the "root" exceptions from
1607          * underlying streams were thrown instead.  This historical behavior is
1608          * followed here for consistency.
1609          */
1610         clear();
1611         boolean oldMode = bout.setBlockDataMode(false);
1612         try {
1613             bout.writeByte(TC_EXCEPTION);
1614             writeObject0(ex, false);
1615             clear();
1616         } finally {
1617             bout.setBlockDataMode(oldMode);
1618         }
1619     }
1620 
1621     /**
1622      * Default PutField implementation.
1623      */
1624     private class PutFieldImpl extends PutField {
1625 
1626         /** class descriptor describing serializable fields */
1627         private final ObjectStreamClass desc;
1628         /** primitive field values */
1629         private final byte[] primVals;
1630         /** object field values */
1631         private final Object[] objVals;
1632 
1633         /**
1634          * Creates PutFieldImpl object for writing fields defined in given
1635          * class descriptor.
1636          */
1637         PutFieldImpl(ObjectStreamClass desc) {
1638             this.desc = desc;
1639             primVals = new byte[desc.getPrimDataSize()];
1640             objVals = new Object[desc.getNumObjFields()];
1641         }
1642 
1643         public void put(String name, boolean val) {
1644             Bits.putBoolean(primVals, getFieldOffset(name, Boolean.TYPE), val);
1645         }
1646 
1647         public void put(String name, byte val) {
1648             primVals[getFieldOffset(name, Byte.TYPE)] = val;
1649         }
1650 
1651         public void put(String name, char val) {
1652             Bits.putChar(primVals, getFieldOffset(name, Character.TYPE), val);
1653         }
1654 
1655         public void put(String name, short val) {
1656             Bits.putShort(primVals, getFieldOffset(name, Short.TYPE), val);
1657         }
1658 
1659         public void put(String name, int val) {
1660             Bits.putInt(primVals, getFieldOffset(name, Integer.TYPE), val);
1661         }
1662 
1663         public void put(String name, float val) {
1664             Bits.putFloat(primVals, getFieldOffset(name, Float.TYPE), val);
1665         }
1666 
1667         public void put(String name, long val) {
1668             Bits.putLong(primVals, getFieldOffset(name, Long.TYPE), val);
1669         }
1670 
1671         public void put(String name, double val) {
1672             Bits.putDouble(primVals, getFieldOffset(name, Double.TYPE), val);
1673         }
1674 
1675         public void put(String name, Object val) {
1676             objVals[getFieldOffset(name, Object.class)] = val;
1677         }
1678 
1679         // deprecated in ObjectOutputStream.PutField
1680         public void write(ObjectOutput out) throws IOException {
1681             /*
1682              * Applications should *not* use this method to write PutField
1683              * data, as it will lead to stream corruption if the PutField
1684              * object writes any primitive data (since block data mode is not
1685              * unset/set properly, as is done in OOS.writeFields()).  This
1686              * broken implementation is being retained solely for behavioral
1687              * compatibility, in order to support applications which use
1688              * OOS.PutField.write() for writing only non-primitive data.
1689              *
1690              * Serialization of unshared objects is not implemented here since
1691              * it is not necessary for backwards compatibility; also, unshared
1692              * semantics may not be supported by the given ObjectOutput
1693              * instance.  Applications which write unshared objects using the
1694              * PutField API must use OOS.writeFields().
1695              */
1696             if (ObjectOutputStream.this != out) {
1697                 throw new IllegalArgumentException("wrong stream");
1698             }
1699             out.write(primVals, 0, primVals.length);
1700 
1701             ObjectStreamField[] fields = desc.getFields(false);
1702             int numPrimFields = fields.length - objVals.length;
1703             // REMIND: warn if numPrimFields > 0?
1704             for (int i = 0; i < objVals.length; i++) {
1705                 if (fields[numPrimFields + i].isUnshared()) {
1706                     throw new IOException("cannot write unshared object");
1707                 }
1708                 out.writeObject(objVals[i]);
1709             }
1710         }
1711 
1712         /**
1713          * Writes buffered primitive data and object fields to stream.
1714          */
1715         void writeFields() throws IOException {
1716             bout.write(primVals, 0, primVals.length, false);
1717 
1718             ObjectStreamField[] fields = desc.getFields(false);
1719             int numPrimFields = fields.length - objVals.length;
1720             for (int i = 0; i < objVals.length; i++) {
1721                 if (extendedDebugInfo) {
1722                     debugInfoStack.push(
1723                         "field (class \"" + desc.getName() + "\", name: \"" +
1724                         fields[numPrimFields + i].getName() + "\", type: \"" +
1725                         fields[numPrimFields + i].getType() + "\")");
1726                 }
1727                 try {
1728                     writeObject0(objVals[i],
1729                                  fields[numPrimFields + i].isUnshared());
1730                 } finally {
1731                     if (extendedDebugInfo) {
1732                         debugInfoStack.pop();
1733                     }
1734                 }
1735             }
1736         }
1737 
1738         /**
1739          * Returns offset of field with given name and type.  A specified type
1740          * of null matches all types, Object.class matches all non-primitive
1741          * types, and any other non-null type matches assignable types only.
1742          * Throws IllegalArgumentException if no matching field found.
1743          */
1744         private int getFieldOffset(String name, Class<?> type) {
1745             ObjectStreamField field = desc.getField(name, type);
1746             if (field == null) {
1747                 throw new IllegalArgumentException("no such field " + name +
1748                                                    " with type " + type);
1749             }
1750             return field.getOffset();
1751         }
1752     }
1753 
1754     /**
1755      * Buffered output stream with two modes: in default mode, outputs data in
1756      * same format as DataOutputStream; in "block data" mode, outputs data
1757      * bracketed by block data markers (see object serialization specification
1758      * for details).
1759      */
1760     private static class BlockDataOutputStream
1761         extends OutputStream implements DataOutput
1762     {
1763         /** maximum data block length */
1764         private static final int MAX_BLOCK_SIZE = 1024;
1765         /** maximum data block header length */
1766         private static final int MAX_HEADER_SIZE = 5;
1767         /** (tunable) length of char buffer (for writing strings) */
1768         private static final int CHAR_BUF_SIZE = 256;
1769 
1770         /** buffer for writing general/block data */
1771         private final byte[] buf = new byte[MAX_BLOCK_SIZE];
1772         /** buffer for writing block data headers */
1773         private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
1774         /** char buffer for fast string writes */
1775         private final char[] cbuf = new char[CHAR_BUF_SIZE];
1776 
1777         /** block data mode */
1778         private boolean blkmode = false;
1779         /** current offset into buf */
1780         private int pos = 0;
1781 
1782         /** underlying output stream */
1783         private final OutputStream out;
1784         /** loopback stream (for data writes that span data blocks) */
1785         private final DataOutputStream dout;
1786 
1787         /**
1788          * Creates new BlockDataOutputStream on top of given underlying stream.
1789          * Block data mode is turned off by default.
1790          */
1791         BlockDataOutputStream(OutputStream out) {
1792             this.out = out;
1793             dout = new DataOutputStream(this);
1794         }
1795 
1796         /**
1797          * Sets block data mode to the given mode (true == on, false == off)
1798          * and returns the previous mode value.  If the new mode is the same as
1799          * the old mode, no action is taken.  If the new mode differs from the
1800          * old mode, any buffered data is flushed before switching to the new
1801          * mode.
1802          */
1803         boolean setBlockDataMode(boolean mode) throws IOException {
1804             if (blkmode == mode) {
1805                 return blkmode;
1806             }
1807             drain();
1808             blkmode = mode;
1809             return !blkmode;
1810         }
1811 
1812         /**
1813          * Returns true if the stream is currently in block data mode, false
1814          * otherwise.
1815          */
1816         boolean getBlockDataMode() {
1817             return blkmode;
1818         }
1819 
1820         /* ----------------- generic output stream methods ----------------- */
1821         /*
1822          * The following methods are equivalent to their counterparts in
1823          * OutputStream, except that they partition written data into data
1824          * blocks when in block data mode.
1825          */
1826 
1827         public void write(int b) throws IOException {
1828             if (pos >= MAX_BLOCK_SIZE) {
1829                 drain();
1830             }
1831             buf[pos++] = (byte) b;
1832         }
1833 
1834         public void write(byte[] b) throws IOException {
1835             write(b, 0, b.length, false);
1836         }
1837 
1838         public void write(byte[] b, int off, int len) throws IOException {
1839             write(b, off, len, false);
1840         }
1841 
1842         public void flush() throws IOException {
1843             drain();
1844             out.flush();
1845         }
1846 
1847         public void close() throws IOException {
1848             flush();
1849             out.close();
1850         }
1851 
1852         /**
1853          * Writes specified span of byte values from given array.  If copy is
1854          * true, copies the values to an intermediate buffer before writing
1855          * them to underlying stream (to avoid exposing a reference to the
1856          * original byte array).
1857          */
1858         void write(byte[] b, int off, int len, boolean copy)
1859             throws IOException
1860         {
1861             if (!(copy || blkmode)) {           // write directly
1862                 drain();
1863                 out.write(b, off, len);
1864                 return;
1865             }
1866 
1867             while (len > 0) {
1868                 if (pos >= MAX_BLOCK_SIZE) {
1869                     drain();
1870                 }
1871                 if (len >= MAX_BLOCK_SIZE && !copy && pos == 0) {
1872                     // avoid unnecessary copy
1873                     writeBlockHeader(MAX_BLOCK_SIZE);
1874                     out.write(b, off, MAX_BLOCK_SIZE);
1875                     off += MAX_BLOCK_SIZE;
1876                     len -= MAX_BLOCK_SIZE;
1877                 } else {
1878                     int wlen = Math.min(len, MAX_BLOCK_SIZE - pos);
1879                     System.arraycopy(b, off, buf, pos, wlen);
1880                     pos += wlen;
1881                     off += wlen;
1882                     len -= wlen;
1883                 }
1884             }
1885         }
1886 
1887         /**
1888          * Writes all buffered data from this stream to the underlying stream,
1889          * but does not flush underlying stream.
1890          */
1891         void drain() throws IOException {
1892             if (pos == 0) {
1893                 return;
1894             }
1895             if (blkmode) {
1896                 writeBlockHeader(pos);
1897             }
1898             out.write(buf, 0, pos);
1899             pos = 0;
1900         }
1901 
1902         /**
1903          * Writes block data header.  Data blocks shorter than 256 bytes are
1904          * prefixed with a 2-byte header; all others start with a 5-byte
1905          * header.
1906          */
1907         private void writeBlockHeader(int len) throws IOException {
1908             if (len <= 0xFF) {
1909                 hbuf[0] = TC_BLOCKDATA;
1910                 hbuf[1] = (byte) len;
1911                 out.write(hbuf, 0, 2);
1912             } else {
1913                 hbuf[0] = TC_BLOCKDATALONG;
1914                 Bits.putInt(hbuf, 1, len);
1915                 out.write(hbuf, 0, 5);
1916             }
1917         }
1918 
1919 
1920         /* ----------------- primitive data output methods ----------------- */
1921         /*
1922          * The following methods are equivalent to their counterparts in
1923          * DataOutputStream, except that they partition written data into data
1924          * blocks when in block data mode.
1925          */
1926 
1927         public void writeBoolean(boolean v) throws IOException {
1928             if (pos >= MAX_BLOCK_SIZE) {
1929                 drain();
1930             }
1931             Bits.putBoolean(buf, pos++, v);
1932         }
1933 
1934         public void writeByte(int v) throws IOException {
1935             if (pos >= MAX_BLOCK_SIZE) {
1936                 drain();
1937             }
1938             buf[pos++] = (byte) v;
1939         }
1940 
1941         public void writeChar(int v) throws IOException {
1942             if (pos + 2 <= MAX_BLOCK_SIZE) {
1943                 Bits.putChar(buf, pos, (char) v);
1944                 pos += 2;
1945             } else {
1946                 dout.writeChar(v);
1947             }
1948         }
1949 
1950         public void writeShort(int v) throws IOException {
1951             if (pos + 2 <= MAX_BLOCK_SIZE) {
1952                 Bits.putShort(buf, pos, (short) v);
1953                 pos += 2;
1954             } else {
1955                 dout.writeShort(v);
1956             }
1957         }
1958 
1959         public void writeInt(int v) throws IOException {
1960             if (pos + 4 <= MAX_BLOCK_SIZE) {
1961                 Bits.putInt(buf, pos, v);
1962                 pos += 4;
1963             } else {
1964                 dout.writeInt(v);
1965             }
1966         }
1967 
1968         public void writeFloat(float v) throws IOException {
1969             if (pos + 4 <= MAX_BLOCK_SIZE) {
1970                 Bits.putFloat(buf, pos, v);
1971                 pos += 4;
1972             } else {
1973                 dout.writeFloat(v);
1974             }
1975         }
1976 
1977         public void writeLong(long v) throws IOException {
1978             if (pos + 8 <= MAX_BLOCK_SIZE) {
1979                 Bits.putLong(buf, pos, v);
1980                 pos += 8;
1981             } else {
1982                 dout.writeLong(v);
1983             }
1984         }
1985 
1986         public void writeDouble(double v) throws IOException {
1987             if (pos + 8 <= MAX_BLOCK_SIZE) {
1988                 Bits.putDouble(buf, pos, v);
1989                 pos += 8;
1990             } else {
1991                 dout.writeDouble(v);
1992             }
1993         }
1994 
1995         public void writeBytes(String s) throws IOException {
1996             int endoff = s.length();
1997             int cpos = 0;
1998             int csize = 0;
1999             for (int off = 0; off < endoff; ) {
2000                 if (cpos >= csize) {
2001                     cpos = 0;
2002                     csize = Math.min(endoff - off, CHAR_BUF_SIZE);
2003                     s.getChars(off, off + csize, cbuf, 0);
2004                 }
2005                 if (pos >= MAX_BLOCK_SIZE) {
2006                     drain();
2007                 }
2008                 int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos);
2009                 int stop = pos + n;
2010                 while (pos < stop) {
2011                     buf[pos++] = (byte) cbuf[cpos++];
2012                 }
2013                 off += n;
2014             }
2015         }
2016 
2017         public void writeChars(String s) throws IOException {
2018             int endoff = s.length();
2019             for (int off = 0; off < endoff; ) {
2020                 int csize = Math.min(endoff - off, CHAR_BUF_SIZE);
2021                 s.getChars(off, off + csize, cbuf, 0);
2022                 writeChars(cbuf, 0, csize);
2023                 off += csize;
2024             }
2025         }
2026 
2027         public void writeUTF(String s) throws IOException {
2028             writeUTF(s, getUTFLength(s));
2029         }
2030 
2031 
2032         /* -------------- primitive data array output methods -------------- */
2033         /*
2034          * The following methods write out spans of primitive data values.
2035          * Though equivalent to calling the corresponding primitive write
2036          * methods repeatedly, these methods are optimized for writing groups
2037          * of primitive data values more efficiently.
2038          */
2039 
2040         void writeBooleans(boolean[] v, int off, int len) throws IOException {
2041             int endoff = off + len;
2042             while (off < endoff) {
2043                 if (pos >= MAX_BLOCK_SIZE) {
2044                     drain();
2045                 }
2046                 int stop = Math.min(endoff, off + (MAX_BLOCK_SIZE - pos));
2047                 while (off < stop) {
2048                     Bits.putBoolean(buf, pos++, v[off++]);
2049                 }
2050             }
2051         }
2052 
2053         void writeChars(char[] v, int off, int len) throws IOException {
2054             int limit = MAX_BLOCK_SIZE - 2;
2055             int endoff = off + len;
2056             while (off < endoff) {
2057                 if (pos <= limit) {
2058                     int avail = (MAX_BLOCK_SIZE - pos) >> 1;
2059                     int stop = Math.min(endoff, off + avail);
2060                     while (off < stop) {
2061                         Bits.putChar(buf, pos, v[off++]);
2062                         pos += 2;
2063                     }
2064                 } else {
2065                     dout.writeChar(v[off++]);
2066                 }
2067             }
2068         }
2069 
2070         void writeShorts(short[] v, int off, int len) throws IOException {
2071             int limit = MAX_BLOCK_SIZE - 2;
2072             int endoff = off + len;
2073             while (off < endoff) {
2074                 if (pos <= limit) {
2075                     int avail = (MAX_BLOCK_SIZE - pos) >> 1;
2076                     int stop = Math.min(endoff, off + avail);
2077                     while (off < stop) {
2078                         Bits.putShort(buf, pos, v[off++]);
2079                         pos += 2;
2080                     }
2081                 } else {
2082                     dout.writeShort(v[off++]);
2083                 }
2084             }
2085         }
2086 
2087         void writeInts(int[] v, int off, int len) throws IOException {
2088             int limit = MAX_BLOCK_SIZE - 4;
2089             int endoff = off + len;
2090             while (off < endoff) {
2091                 if (pos <= limit) {
2092                     int avail = (MAX_BLOCK_SIZE - pos) >> 2;
2093                     int stop = Math.min(endoff, off + avail);
2094                     while (off < stop) {
2095                         Bits.putInt(buf, pos, v[off++]);
2096                         pos += 4;
2097                     }
2098                 } else {
2099                     dout.writeInt(v[off++]);
2100                 }
2101             }
2102         }
2103 
2104         void writeFloats(float[] v, int off, int len) throws IOException {
2105             int limit = MAX_BLOCK_SIZE - 4;
2106             int endoff = off + len;
2107             while (off < endoff) {
2108                 if (pos <= limit) {
2109                     int avail = (MAX_BLOCK_SIZE - pos) >> 2;
2110                     int stop = Math.min(endoff, off + avail);
2111                     while (off < stop) {
2112                         Bits.putFloat(buf, pos, v[off++]);
2113                         pos += 4;
2114                     }
2115                 } else {
2116                     dout.writeFloat(v[off++]);
2117                 }
2118             }
2119         }
2120 
2121         void writeLongs(long[] v, int off, int len) throws IOException {
2122             int limit = MAX_BLOCK_SIZE - 8;
2123             int endoff = off + len;
2124             while (off < endoff) {
2125                 if (pos <= limit) {
2126                     int avail = (MAX_BLOCK_SIZE - pos) >> 3;
2127                     int stop = Math.min(endoff, off + avail);
2128                     while (off < stop) {
2129                         Bits.putLong(buf, pos, v[off++]);
2130                         pos += 8;
2131                     }
2132                 } else {
2133                     dout.writeLong(v[off++]);
2134                 }
2135             }
2136         }
2137 
2138         void writeDoubles(double[] v, int off, int len) throws IOException {
2139             int limit = MAX_BLOCK_SIZE - 8;
2140             int endoff = off + len;
2141             while (off < endoff) {
2142                 if (pos <= limit) {
2143                     int avail = (MAX_BLOCK_SIZE - pos) >> 3;
2144                     int stop = Math.min(endoff, off + avail);
2145                     while (off < stop) {
2146                         Bits.putDouble(buf, pos, v[off++]);
2147                         pos += 8;
2148                     }
2149                 } else {
2150                     dout.writeDouble(v[off++]);
2151                 }
2152             }
2153         }
2154 
2155         /**
2156          * Returns the length in bytes of the UTF encoding of the given string.
2157          */
2158         long getUTFLength(String s) {
2159             int len = s.length();
2160             long utflen = 0;
2161             for (int off = 0; off < len; ) {
2162                 int csize = Math.min(len - off, CHAR_BUF_SIZE);
2163                 s.getChars(off, off + csize, cbuf, 0);
2164                 for (int cpos = 0; cpos < csize; cpos++) {
2165                     char c = cbuf[cpos];
2166                     if (c >= 0x0001 && c <= 0x007F) {
2167                         utflen++;
2168                     } else if (c > 0x07FF) {
2169                         utflen += 3;
2170                     } else {
2171                         utflen += 2;
2172                     }
2173                 }
2174                 off += csize;
2175             }
2176             return utflen;
2177         }
2178 
2179         /**
2180          * Writes the given string in UTF format.  This method is used in
2181          * situations where the UTF encoding length of the string is already
2182          * known; specifying it explicitly avoids a prescan of the string to
2183          * determine its UTF length.
2184          */
2185         void writeUTF(String s, long utflen) throws IOException {
2186             if (utflen > 0xFFFFL) {
2187                 throw new UTFDataFormatException();
2188             }
2189             writeShort((int) utflen);
2190             if (utflen == (long) s.length()) {
2191                 writeBytes(s);
2192             } else {
2193                 writeUTFBody(s);
2194             }
2195         }
2196 
2197         /**
2198          * Writes given string in "long" UTF format.  "Long" UTF format is
2199          * identical to standard UTF, except that it uses an 8 byte header
2200          * (instead of the standard 2 bytes) to convey the UTF encoding length.
2201          */
2202         void writeLongUTF(String s) throws IOException {
2203             writeLongUTF(s, getUTFLength(s));
2204         }
2205 
2206         /**
2207          * Writes given string in "long" UTF format, where the UTF encoding
2208          * length of the string is already known.
2209          */
2210         void writeLongUTF(String s, long utflen) throws IOException {
2211             writeLong(utflen);
2212             if (utflen == (long) s.length()) {
2213                 writeBytes(s);
2214             } else {
2215                 writeUTFBody(s);
2216             }
2217         }
2218 
2219         /**
2220          * Writes the "body" (i.e., the UTF representation minus the 2-byte or
2221          * 8-byte length header) of the UTF encoding for the given string.
2222          */
2223         private void writeUTFBody(String s) throws IOException {
2224             int limit = MAX_BLOCK_SIZE - 3;
2225             int len = s.length();
2226             for (int off = 0; off < len; ) {
2227                 int csize = Math.min(len - off, CHAR_BUF_SIZE);
2228                 s.getChars(off, off + csize, cbuf, 0);
2229                 for (int cpos = 0; cpos < csize; cpos++) {
2230                     char c = cbuf[cpos];
2231                     if (pos <= limit) {
2232                         if (c <= 0x007F && c != 0) {
2233                             buf[pos++] = (byte) c;
2234                         } else if (c > 0x07FF) {
2235                             buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F));
2236                             buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F));
2237                             buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F));
2238                             pos += 3;
2239                         } else {
2240                             buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F));
2241                             buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F));
2242                             pos += 2;
2243                         }
2244                     } else {    // write one byte at a time to normalize block
2245                         if (c <= 0x007F && c != 0) {
2246                             write(c);
2247                         } else if (c > 0x07FF) {
2248                             write(0xE0 | ((c >> 12) & 0x0F));
2249                             write(0x80 | ((c >> 6) & 0x3F));
2250                             write(0x80 | ((c >> 0) & 0x3F));
2251                         } else {
2252                             write(0xC0 | ((c >> 6) & 0x1F));
2253                             write(0x80 | ((c >> 0) & 0x3F));
2254                         }
2255                     }
2256                 }
2257                 off += csize;
2258             }
2259         }
2260     }
2261 
2262     /**
2263      * Lightweight identity hash table which maps objects to integer handles,
2264      * assigned in ascending order.
2265      */
2266     private static class HandleTable {
2267 
2268         /* number of mappings in table/next available handle */
2269         private int size;
2270         /* size threshold determining when to expand hash spine */
2271         private int threshold;
2272         /* factor for computing size threshold */
2273         private final float loadFactor;
2274         /* maps hash value -> candidate handle value */
2275         private int[] spine;
2276         /* maps handle value -> next candidate handle value */
2277         private int[] next;
2278         /* maps handle value -> associated object */
2279         private Object[] objs;
2280 
2281         /**
2282          * Creates new HandleTable with given capacity and load factor.
2283          */
2284         HandleTable(int initialCapacity, float loadFactor) {
2285             this.loadFactor = loadFactor;
2286             spine = new int[initialCapacity];
2287             next = new int[initialCapacity];
2288             objs = new Object[initialCapacity];
2289             threshold = (int) (initialCapacity * loadFactor);
2290             clear();
2291         }
2292 
2293         /**
2294          * Assigns next available handle to given object, and returns handle
2295          * value.  Handles are assigned in ascending order starting at 0.
2296          */
2297         int assign(Object obj) {
2298             if (size >= next.length) {
2299                 growEntries();
2300             }
2301             if (size >= threshold) {
2302                 growSpine();
2303             }
2304             insert(obj, size);
2305             return size++;
2306         }
2307 
2308         /**
2309          * Looks up and returns handle associated with given object, or -1 if
2310          * no mapping found.
2311          */
2312         int lookup(Object obj) {
2313             if (size == 0) {
2314                 return -1;
2315             }
2316             int index = hash(obj) % spine.length;
2317             for (int i = spine[index]; i >= 0; i = next[i]) {
2318                 if (objs[i] == obj) {
2319                     return i;
2320                 }
2321             }
2322             return -1;
2323         }
2324 
2325         /**
2326          * Resets table to its initial (empty) state.
2327          */
2328         void clear() {
2329             Arrays.fill(spine, -1);
2330             Arrays.fill(objs, 0, size, null);
2331             size = 0;
2332         }
2333 
2334         /**
2335          * Returns the number of mappings currently in table.
2336          */
2337         int size() {
2338             return size;
2339         }
2340 
2341         /**
2342          * Inserts mapping object -> handle mapping into table.  Assumes table
2343          * is large enough to accommodate new mapping.
2344          */
2345         private void insert(Object obj, int handle) {
2346             int index = hash(obj) % spine.length;
2347             objs[handle] = obj;
2348             next[handle] = spine[index];
2349             spine[index] = handle;
2350         }
2351 
2352         /**
2353          * Expands the hash "spine" -- equivalent to increasing the number of
2354          * buckets in a conventional hash table.
2355          */
2356         private void growSpine() {
2357             spine = new int[(spine.length << 1) + 1];
2358             threshold = (int) (spine.length * loadFactor);
2359             Arrays.fill(spine, -1);
2360             for (int i = 0; i < size; i++) {
2361                 insert(objs[i], i);
2362             }
2363         }
2364 
2365         /**
2366          * Increases hash table capacity by lengthening entry arrays.
2367          */
2368         private void growEntries() {
2369             int newLength = (next.length << 1) + 1;
2370             int[] newNext = new int[newLength];
2371             System.arraycopy(next, 0, newNext, 0, size);
2372             next = newNext;
2373 
2374             Object[] newObjs = new Object[newLength];
2375             System.arraycopy(objs, 0, newObjs, 0, size);
2376             objs = newObjs;
2377         }
2378 
2379         /**
2380          * Returns hash value for given object.
2381          */
2382         private int hash(Object obj) {
2383             return System.identityHashCode(obj) & 0x7FFFFFFF;
2384         }
2385     }
2386 
2387     /**
2388      * Lightweight identity hash table which maps objects to replacement
2389      * objects.
2390      */
2391     private static class ReplaceTable {
2392 
2393         /* maps object -> index */
2394         private final HandleTable htab;
2395         /* maps index -> replacement object */
2396         private Object[] reps;
2397 
2398         /**
2399          * Creates new ReplaceTable with given capacity and load factor.
2400          */
2401         ReplaceTable(int initialCapacity, float loadFactor) {
2402             htab = new HandleTable(initialCapacity, loadFactor);
2403             reps = new Object[initialCapacity];
2404         }
2405 
2406         /**
2407          * Enters mapping from object to replacement object.
2408          */
2409         void assign(Object obj, Object rep) {
2410             int index = htab.assign(obj);
2411             while (index >= reps.length) {
2412                 grow();
2413             }
2414             reps[index] = rep;
2415         }
2416 
2417         /**
2418          * Looks up and returns replacement for given object.  If no
2419          * replacement is found, returns the lookup object itself.
2420          */
2421         Object lookup(Object obj) {
2422             int index = htab.lookup(obj);
2423             return (index >= 0) ? reps[index] : obj;
2424         }
2425 
2426         /**
2427          * Resets table to its initial (empty) state.
2428          */
2429         void clear() {
2430             Arrays.fill(reps, 0, htab.size(), null);
2431             htab.clear();
2432         }
2433 
2434         /**
2435          * Returns the number of mappings currently in table.
2436          */
2437         int size() {
2438             return htab.size();
2439         }
2440 
2441         /**
2442          * Increases table capacity.
2443          */
2444         private void grow() {
2445             Object[] newReps = new Object[(reps.length << 1) + 1];
2446             System.arraycopy(reps, 0, newReps, 0, reps.length);
2447             reps = newReps;
2448         }
2449     }
2450 
2451     /**
2452      * Stack to keep debug information about the state of the
2453      * serialization process, for embedding in exception messages.
2454      */
2455     private static class DebugTraceInfoStack {
2456         private final List<String> stack;
2457 
2458         DebugTraceInfoStack() {
2459             stack = new ArrayList<>();
2460         }
2461 
2462         /**
2463          * Removes all of the elements from enclosed list.
2464          */
2465         void clear() {
2466             stack.clear();
2467         }
2468 
2469         /**
2470          * Removes the object at the top of enclosed list.
2471          */
2472         void pop() {
2473             stack.remove(stack.size()-1);
2474         }
2475 
2476         /**
2477          * Pushes a String onto the top of enclosed list.
2478          */
2479         void push(String entry) {
2480             stack.add("\t- " + entry);
2481         }
2482 
2483         /**
2484          * Returns a string representation of this object
2485          */
2486         public String toString() {
2487             StringJoiner sj = new StringJoiner("\n");
2488             for (int i = stack.size() - 1; i >= 0; i--) {
2489                 sj.add(stack.get(i));
2490             }
2491             return sj.toString();
2492         }
2493     }
2494 
2495 }