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