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